I am having trouble getting the requests library for python to work with ISO datetime parameters
headers = {"Authorization: Token [token_here]"}
body = {"start_date": "2019-07-01T05:00:00Z","end_date": "2019-07-02T00:00:00Z"}
resp = requests.get("https://website.com/api/v1/endpoint", headers=headers, params=body)
The above will turn the url into the following
https://website.com/api/v1/endpoint?%7B%22start_date%22:%20%222019-07-01T05:00:00Z%22,%20%22end_date%22:%20%222019-07-03T00:00:00Z%22%7D'
which results in a 405 for me. However, using the exact same body in body.json for httpie works fine
cat body.json
{"start_date": "2019-07-01T05:00:00Z","end_date": "2019-07-02T00:00:00Z"}
http https://website.com/api/v1/endpoint 'Authorization: Token [token_here]' < body.json
JSON should be sent as the body of a POST request. For that you can use the convenient json parameter of the requests.post method:
resp = requests.post("https://website.com/api/v1/endpoint", headers=headers, json=body)
Related
So i was following the guide for getting a OAUTH token from https://developer.spotify.com/documentation/general/guides/authorization/client-credentials/
I tried doing a python requests library of the above equivalent code but i got response 400 from the server. May I know where i am going wrong?
import requests
import json
import clientidandsecret
headers ={"Authorization": "Basic " + clientidandsecret.C_ID +":" +clientidandsecret.C_SECRET}
form = {"form":{"grant_type" :"client_credentials"}, "json":"true"}
result = requests.post("https://accounts.spotify.com/api/token", headers=headers, data=form)
print(result)
Your variable form is a Dict, if you want to use the parameter data in requests it needs to be a string, this will fix it:
import json
...
result = requests.post(url, headers=headers, data=json.dumps(form))
Or even better:
result = requests.post(url, headers=headers, json=form)
I am using the postman tool to send the requests to the api server and trying to get the code snip-it from code section of postman, but somehow the same code is not working with python
this is the code :
import requests
import json
url = "http://127.0.0.1:3333/api/v1/solve"
payload={'FileLocation': '/var/opt/rcm_dms/reg'}
files=[
('regChallengeFile',('gudsgtcnsrk_reg_challenge.json',open('/home/system/Music/gudsgtcnsrk_reg_challenge.json','rb'),'application/json'))
]
headers = {
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=payload, files=files)
print(response.text)
output : {"statusCode":"DM-6-4002","statusMessage":"Invalid request body/header"}\n
I am using the postman tool to send the requests to the api server and trying to get the code snip-it from code section of postman, but somehow the same code is not working with python
this is the code :
output : {"statusCode":"DM-6-4002","statusMessage":"Invalid request body/header"}\n
What is wrong in this example , any suggestions
Single quotes should be on both side of key FileLocation payload={'FileLocation': '/var/opt/rcm_dms/reg'} instead of payload={FileLocation': '/var/opt/rcm_dms/reg'}.
If you still get the error, check the format of value assigned in files variable i.e.,[('regChallengeFile',('gudsgtcnsrk_reg_challenge.json',open('/home/system/Music/gudsgtcnsrk_reg_challenge.json','rb'),'application/json'))]
I am trying to recreate a Curl command from the Gentle forced aligner:
https://github.com/lowerquality/gentle
Curl command:
curl -F "audio=#audio.mp3" -F "transcript=#words.txt" "http://localhost:8765/transcriptions?async=false"
Code so far:
import requests
url = 'http://localhost:8765/transcriptions/'
files = {'audio': open('C://Users//user//Desktop//gentle//audio.mp3','rb'), 'transcript':
open('C://Users//andrey_user//Desktop//gentle//words.txt', 'rb')}
headers = {}
response = requests.post(url,
files=files,
headers=headers)
print(response.text)
But it only returns the HTML and says it is a GET request, however the curl command gives me the correct result. Thanks for your help!
Try this code :
import requests
params = (
('async', 'false'),
)
files = {
'audio': ('audio.mp3', open('audio.mp3', 'rb')),
'transcript': ('words.txt', open('words.txt', 'rb')),
}
response = requests.post('http://localhost:8765/transcriptions', params=params, files=files)
print(response.text)
I believe you also have to convert the response to JSON, assuming that the library you're trying to send the request to is a REST API. I'm not sure why it says its a get request, but if that's the case, just try changing it to a get request and see if it works out.
So adding r1=response.json() should give you access to the correct JSON data
rocksteady's solution worked
He did originally refer to dictionaries. But the following code to send the JSON string also worked wonders using requests:
import requests
headers = {
'Authorization': app_token
}
url = api_url + "/b2api/v1/b2_get_upload_url"
content = json.dumps({'bucketId': bucket_id})
r = requests.post(url, data = content, headers = headers)
I'm working with an API that requires me to send JSON as a POST request to get results. Problem is that Python 3 won't allow me to do this.
The following Python 2 code works fine, in fact it's the official sample:
request = urllib2.Request(
api_url +'/b2api/v1/b2_get_upload_url',
json.dumps({ 'bucketId' : bucket_id }),
headers = { 'Authorization': account_authorization_token }
)
response = urllib2.urlopen(request)
However, using this code in Python 3 only makes it complain about data being invalid:
import json
from urllib.request import Request, urlopen
from urllib.parse import urlencode
# -! Irrelevant code has been cut out !-
headers = {
'Authorization': app_token
}
url = api_url + "/b2api/v1/b2_get_upload_url"
# Tested both with encode and without
content = json.dumps({'bucketId': bucket_id}).encode('utf-8')
request = Request(
url=url,
data=content,
headers=headers
)
response = urlopen(req)
I've tried doing urlencode(), like you're supposed to. But this returns a 400 status code from the web server, because it's expecting pure JSON. Even if the pure JSON data is invalid, I need to somehow force Python into sending it.
EDIT: As requested, here are the errors I get. Since this is a flask application, here's a screenshot of the debugger:
Screenshot
Adding .encode('utf-8') gives me an "Expected string or buffer" error
EDIT 2: Screenshot of the debugger with .encode('utf-8') added
Since I have a similar application running, but the client still was missing, I tried it myself.
The server which is running is from the following exercise:
Miguel Grinberg - designing a restful API using Flask
That's why it uses authentication.
But the interesting part: Using requests you can leave the dictionary as it is.
Look at this:
username = 'miguel'
password = 'python'
import requests
content = {"title":"Read a book"}
request = requests.get("http://127.0.0.1:5000/api/v1.0/projects", auth=(username, password), params=content)
print request.text
It seems to work :)
Update 1:
POST requests are done using requests.post(...)
This here describes it well : python requests
Update 2:
In order to complete the answer:
requests.post("http://127.0.0.1:5000/api/v1.0/projects", json=content)
sends the json-string.
json is a valid parameter of the request and internally uses json.dumps()...
I have a quick question to call an NLTK Api using python.To find the sentiment of "great";
The API syntax is
$ curl -d "text=great" http://text-processing.com/api/sentiment/
I need to use a python request to post this and to receive a json object as response.I am trying to use with
resp = requests.post(url, data=values, allow_redirects=True)
if url is http://text-processing.com/api/sentiment/
how must text parameter to be passed?
Modifying the guide from the requests documentation, to suit your requirement, this is what you do:
>>> import json
>>> url = 'http://text-processing.com/api/sentiment/'
>>> payload = {'text': 'great'}
>>> r = requests.post(url, data=json.dumps(payload))