I'm trying to test the Shazam API Detect feature on a mono sample as provided by this tutorial.
My code reads the raw audio file and sends it as base64 plaintext in the body of a POST requests to the Shazam API.
The audio file can be downloaded via this link:
import requests
import base64
def shazam(payload):
url = "https://shazam.p.rapidapi.com/songs/detect"
payload = open(payload,"rb").read()
payload = base64.b64encode(payload)
payload = str(payload)
headers = {
'x-rapidapi-host': "shazam.p.rapidapi.com",
'x-rapidapi-key':str(open("./api.txt","r").read().strip()),
'content-type': "text/plain",
'accept': "text/plain"
}
response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)
shazam("/home/samples/mono.raw")
Any ideas where I'm going wrong?
I'am having problems with this API as well been searching up and down to find a solution :(
it work on me
from pydub import AudioSegment
import base64
import requests
import json
file_path="./test.raw"
url = "https://rapidapi.p.rapidapi.com/songs/detect"
encode_string = base64.b64encode(open(file_path, "rb").read())
payload=encode_string
print(type(payload))
headers = {
'content-type': "text/plain",
'x-rapidapi-key': "<<<you key>>>",
'x-rapidapi-host': "shazam.p.rapidapi.com"
}
response = requests.request("POST", url, data=payload, headers=headers)
print(json.dumps(json.loads(response.text)))
Related
import requests
url = "https://apiexample.com/load/v1/action/aaaaaaaaaaaaa"
payload={}
headers = {
'Authorization': 'OAuth oauth_consumer_key="aaaaaa",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1664837015",oauth_nonce="mKyTFn7OtsV",oauth_version="1.0",oauth_signature="aaaaaaaaaaaa"',
'Cookie': 'JSESSIONID=M7n-S-aGe8asRnTjNOUGowak5i5avsRBx6A4H8au.madsedepre'
}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)
I am trying to retrieve information from an api, and I am using postman...
How can I know what postman is doing to generate that cookie??
and how can I generate it using python requests?
Im trying to mimic this POST request from this site with this payload:
from this URL: https://surviv.io/stats/gert1
Here is an image of the request im trying to mimic.
Here is my current code in python:
import requests
headers = {'content-type': 'application/json; charset=UTF-8'}
url = 'https://surviv.io/api/user_stats'
payload = {"slug":"gert1","interval":"all","mapIdFilter":"-1"}
r = requests.post(url=url, headers=headers, data=payload)
print(r.content)
This returns:
b'<html>\r\n<head><title>500 Internal Server Error</title></head>\r\n<body bgcolor="white">\r\n<center><h1>500 Internal Server Error</h1></center>\r\n<hr><center>nginx</center>\r\n</body>\r\n</html>\r\n'
This is not what I want it return. I want it to return the exact response shown in the response tab of the user_stats requests, which contains the player's stats.
This is what I want it to return:
{"slug":"gert1","username":"GERT","player_icon":"","banned":false,"wins":61,"kills":2830,"games":2034,"kpg":"1.4","modes":[{"teamMode":1,"games":1512,"wins":46,"kills":2230,"winPct":"3.0","mostKills":21,"mostDamage":1872,"kpg":"1.5","avgDamage":169,"avgTimeAlive":92},{"teamMode":2,"games":255,"wins":4,"kills":234,"winPct":"1.6","mostKills":8,"mostDamage":861,"kpg":"0.9","avgDamage":162,"avgTimeAlive":102},{"teamMode":4,"games":267,"wins":11,"kills":366,"winPct":"4.1","mostKills":17,"mostDamage":2225,"kpg":"1.4","avgDamage":246,"avgTimeAlive":125}]}
You should use the json attribute rather than data in the post method. r = requests.post(url=url, headers=headers, json=payload)
Change your code to following your forgot to use json :
import json
import requests
headers = {'content-type': 'application/json; charset=UTF-8'}
url = 'https://surviv.io/api/user_stats'
payload = {"slug":"gert1","interval":"all","mapIdFilter":"-1"}
r = requests.post(url=url, headers=headers, data=json.dumps(payload))
print(r.content)
Tried many ways to upload the data(postman, httpie etc as given on their site) on thingworx but not able to do that.
Please have a look on the following code to upload the data on thingworx:
import requests
import json
app_key = 'xxxx'
url = 'http://pp-1804040542ze.devportal.ptc.io/Thingworx/Things/lmtech_thing/Properties/humidity'
prms = {'appKey': app_key}
hdrs = {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
data = {'humidiy': '20'}
text = json.dumps(data)
print 'data: ' + text
r = requests.put(url, params=prms, headers=hdrs, data=text)
print r.status_code
Have created thing and key successfully. but it always return 404 error.
Tried with postman too. Here are the screenshots as shown below:
The following code worked for me :-)
import requests # Import requests library to send requests to Thingworx
url = 'http://52.199.28.120:8080/Thingworx/Things/work_thing/Properties/temp'
# temp is one of my property name
value = 12 # Upload 12 on Thingworx
headers = {
'Content-Type': 'application/json',
'appkey': 'xxxxxxxxxxxxxxxxxxxxxx',
'Accept': 'application/json',
'x-thingworx-session': 'true',
'Cache-Control': 'no-cache',
}
data = {"temp": value} # JSON data to upload on Thingworx
response = requests.put(url, headers=headers, json=data)
# Note that we have to send put request
print 'Response Code:', response.status_code
# If 200 then data has been uploaded successfully
print 'Response Content:', response.content
I am trying to learn more about using http requests and the Mailchimp API, but I cannot seem to figure out how to add a member to list using a post request. I have tried multiple configurations, and I guess I made some headway since my response went from a 405, to a 401, now I'm getting a 400. I assume this means that I am being authenticated, but I am formatting the request incorrectly.
I have gotten it to work the python mailchimp library, but I want to actually learn how to use the HTTP requests. I could find very few examples of using python requests with Mailchimp.
(obviously I put in my actual list_id, my_username, and my_apikey)
import requests, json
members_url = 'https://us15.api.mailchimp.com/3.0/lists/XXXXXXXX/members/'
auth = ('my_username', 'my_apikey')
headers = {'Content-Type': 'application/json'}
data1 = {
'email_address':'blah#blah.com',
'status':'subscribed',
'merge_fields':{
'FNAME':'John',
'LNAME':'Doe'
}
}
payload = json.dumps(data1)
response = requests.post(members_url, auth=auth, headers=headers, json=payload)
This is my response:
>>> response
<Response [400]>
I'm stumped....what am I doing wrong?
This worked:
import requests, json
members_url = 'https://us15.api.mailchimp.com/3.0/lists/XXXXXXXX/members/'
auth = ('my_username', 'my_apikey')
headers = {'Content-Type': 'application/json'}
data1 = {
'email_address':'<a real email address>', #it could tell 'blah#blah.com was fake'
'status':'subscribed',
'merge_fields':{
'FNAME':'John',
'LNAME':'Doe'
}
}
response = requests.post(members_url, auth=auth, headers=headers, json=data1)
This worked:
import requests, json
members_url = 'https://us15.api.mailchimp.com/3.0/lists/XXXXXXXX/members/'
auth = ('my_username', 'my_apikey')
headers = {'Content-Type': 'application/json'}
data1 = {
'email_address':'<a real email address>', #it could tell 'blah#blah.com was fake'
'status':'subscribed',
'merge_fields':{
'FNAME':'John',
'LNAME':'Doe'
}
}
response = requests.post(members_url, auth=auth, headers=headers, json=data1)
My problems were #1 I was double encoding the json data and #2 mailchimp recognizes obviously BS email addresses like blah#blah.com
Thanks #Alasdair
I'm working with wechat APIs ...
here I've to upload an image to wechat's server using this API
http://admin.wechat.com/wiki/index.php?title=Transferring_Multimedia_Files
url = 'http://file.api.wechat.com/cgi-bin/media/upload?access_token=%s&type=image'%access_token
files = {
'file': (filename, open(filepath, 'rb')),
'Content-Type': 'image/jpeg',
'Content-Length': l
}
r = requests.post(url, files=files)
I'm not able to post data
From wechat api doc:
curl -F media=#test.jpg "http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"
Translate the command above to python:
import requests
url = 'http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE'
files = {'media': open('test.jpg', 'rb')}
requests.post(url, files=files)
Doc: https://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file
In case if you were to pass the image as part of JSON along with other attributes, you can use the below snippet.
client.py
import base64
import json
import requests
api = 'http://localhost:8080/test'
image_file = 'sample_image.png'
with open(image_file, "rb") as f:
im_bytes = f.read()
im_b64 = base64.b64encode(im_bytes).decode("utf8")
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
payload = json.dumps({"image": im_b64, "other_key": "value"})
response = requests.post(api, data=payload, headers=headers)
try:
data = response.json()
print(data)
except requests.exceptions.RequestException:
print(response.text)
server.py
import io
import json
import base64
import logging
import numpy as np
from PIL import Image
from flask import Flask, request, jsonify, abort
app = Flask(__name__)
app.logger.setLevel(logging.DEBUG)
#app.route("/test", methods=['POST'])
def test_method():
# print(request.json)
if not request.json or 'image' not in request.json:
abort(400)
# get the base64 encoded string
im_b64 = request.json['image']
# convert it into bytes
img_bytes = base64.b64decode(im_b64.encode('utf-8'))
# convert bytes data to PIL Image object
img = Image.open(io.BytesIO(img_bytes))
# PIL image object to numpy array
img_arr = np.asarray(img)
print('img shape', img_arr.shape)
# process your img_arr here
# access other keys of json
# print(request.json['other_key'])
result_dict = {'output': 'output_key'}
return result_dict
def run_server_api():
app.run(host='0.0.0.0', port=8080)
if __name__ == "__main__":
run_server_api()
Use this snippet
import os
import requests
url = 'http://host:port/endpoint'
with open(path_img, 'rb') as img:
name_img= os.path.basename(path_img)
files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }
with requests.Session() as s:
r = s.post(url,files=files)
print(r.status_code)
I confronted similar issue when I wanted to post image file to a rest API from Python (Not wechat API though). The solution for me was to use 'data' parameter to post the file in binary data instead of 'files'. Requests API reference
data = open('your_image.png','rb').read()
r = requests.post(your_url,data=data)
Hope this works for your case.
import requests
image_file_descriptor = open('test.jpg', 'rb')
# Requests makes it simple to upload Multipart-encoded files
files = {'media': image_file_descriptor}
url = '...'
requests.post(url, files=files)
image_file_descriptor.close()
Don't forget to close the descriptor, it prevents bugs: Is explicitly closing files important?
For Rest API to upload images from host to host:
import urllib2
import requests
api_host = 'https://host.url.com/upload/'
headers = {'Content-Type' : 'image/jpeg'}
image_url = 'http://image.url.com/sample.jpeg'
img_file = urllib2.urlopen(image_url)
response = requests.post(api_host, data=img_file.read(), headers=headers, verify=False)
You can use option verify set to False to omit SSL verification for HTTPS requests.
This works for me.
import requests
url = "https://example.com"
payload={}
files=[
('file',('myfile.jpg',open('/path/to/myfile.jpg','rb'),'image/jpeg'))
]
response = requests.request("POST", url, auth=("my_username","my_password"), data=payload, files=files)
print(response.text)
If you have CURL then you can directly get request from Postman.
import requests
url = "your URL"
payload={}
files=[
('upload_file',('20220212235319_1509.jpg',open('/20220212235319_1509.jpg','rb'),'image/jpeg'))
]
headers = {
'Accept-Language': 'en-US',
'Authorization': 'Bearer yourToken'
}
response = requests.request("POST", url, headers=headers, data=payload, files=files)
print(response.text)