I've been looking to many questions similar to mine but I could not find a solution.
I'm using requests to perform a POST request. I've tried a lot of combinations inside the request but nothing returns a 201 ok.
Here is my code:
import json
import requests
if __name__ == '__main__':
headers = {'content-type' : 'application/json'}
url = "http://myserver/ext/v3.1/test_device"
message = {"atribute_a": "value", "atribute_b": "valueb"}
params = {"priority":"normal"}
r = requests.post(url, params=params, headers=headers, data = json.dumps(message) )
print(r)
I've also tried withou json.dumps but it also gives me 400 bad request. I've also tried to add the params directly to the url like: ...?priority=normal but with no success.
The easiest technique is to use json instead of data as followed:
requests.post(url, headers=headers, params=params, json=data)
Based on the comments, your server is actually expecting data as a stringified JSON object.
As far as the params are concerned, it'd most probably help if they're declared as a tuple of tuples (or a dict of dicts)
Try the following -
headers = {
'content-type': 'application/json',
}
params = (
('priority', 'normal'),
)
data = {
"atribute_a": "value",
"atribute_b": false
}
requests.post(url, headers=headers, params=params, data=str(data))
Related
I am trying to access the cites species api to get information on a input species name.
Reference document: http://api.speciesplus.net/documentation/v1/references.html
I tried to use the api with the provided API Key.
I get error code 401.
Here is the code
import requests
APIKEY='XXXXXXXXXXXX' # Replaced with provided api key
r = requests.get('https://api.speciesplus.net/api/v1/taxon_concepts.xml?name=Mammalia&X-Authentication-Token={APIKEY}')
r
As #jonrsharpe said in comment:
"Headers and query parameters aren't the same thing..."
You have to set APIKEY as header - don't put it in URL.
You may also put parameters as dictionary and requests will append them to URL - and code will be more readable.
import requests
APIKEY = 'XXXXXXXXXXXX'
headers = {
"X-Authentication-Token": APIKEY,
}
payload = {
"name": "Mammalia",
}
url = "https://api.speciesplus.net/api/v1/taxon_concepts.xml"
response = requests.get(url, params=payload, headers=headers)
print(response.status_code)
print(response.text)
EDIT:
If you skip .xml in URL then you get data as JSON and it can be more useful
url = "https://api.speciesplus.net/api/v1/taxon_concepts"
response = requests.get(url, params=payload, headers=headers)
print(response.status_code)
print(response.text)
data = response.json()
for item in data:
print(item['citation'])
There is some api endpoint, which i try to send POST request with code like this
import requests
url = 'https://deviantart.com/api/v1/oauth2/collections/folders/create'
headers = {'Content-Type': 'application/json'}
data = {'folder': 'folder_name'}
params = {'access_token': '<authorization_code_flow_token>'}
r = requests.post(url=url,
headers=headers,
params=params,
json=data)
print(r.text)
But i get 400 response:
{
"error":"invalid_request",
"error_description":"Request field validation failed.",
"error_details":{"folder":"folder is required"},
"status":"error"
}
I don't understand why it fails, because their example with curl works fine.
curl https://www.deviantart.com/api/v1/oauth2/collections/folders/create \
-d "folder=Awesome Collection" \
-d access_token=Alph4num3r1ct0k3nv4lu3
And I was successful with post responses to get authenticated.
I tried to change content-type header(json and x-www-formurlencoded) and pass data-payload different ways(passing json string to data param, passing dict to json, passing paylod as query string). But It does not work. I dont have a clue what i am doing wrong. It seems like i send payload wrong or put wrong headers, but i tried a lot of "combinations" and still no effect.
For next hour you if you want try to help you can use access_token:
ba4550889c8c36c8d82093906145d9fd66775c959030d3d772
The following code will work.
import requests
url = "https://www.deviantart.com/api/v1/oauth2/collections/folders/create"
payload={'folder': 'Awesome Collection',
'access_token': 'ba4550889c8c36c8d82093906145d9fd66775c959030d3d772'}
files=[]
headers = {}
response = requests.request("POST", url, headers=headers, data=payload, files=files)
print(response.text)
My response looks like:
[
{"_id":"5f6060d0d279373c0017447d","name":"Faizan","email":"faizan#test.com"}
]
I want to get the name in python. I am tryting:
response = requests.get(url)
data = response.json()
The error I am getting is:
JSONDecodeError at /get/
this might help you
import requests
import json
dburl = 'https://postman-9e13.restdb.io/rest/contact'
headers = {'x-apikey': '7267cbb3c251a01dd8563ca447194e78af67d', 'Content-Type': 'application/json'}
params = {"name":"Faizan","email":"faizan#test.com"}
r = requests.get(dburl, params=params, headers=headers)
print(r.json())
after seeing the result, you can pass to your templates like this
geodata = response.json()
return render(request, 'main/get.html', { 'name': geodata[0]['name'] })
or you can change accordingly.
The snippet you shared is correct, however the problem might be with the URL.
response = requests.get(url)
data = response.json()
Here, .json() only works for the response which is in the JSON format only. If it is showing that error that means your URL returning the HTML document.
I am trying to post some information into an API based on their recommended format. When I use Postman( tool to test APIs), I see that the response has the isSuccess flag set to true. However, when I write the same code in Python using the requests library, I get the isSuccess flag as false
As mentioned about, I verified the headers and the json data object, both are the same yet the results defer
import requests
data = {"AccountNumber":"100007777",
"ActivityID":"78",
"ActivityDT":"2019-08-07 12:00:00",
"ActivityValue":"1"
}
url = "http://<IP>/<API_PATH>"
headers = {
"X-Tenant":"Default",
"Content-Type":"application/json"
}
response = requests.post(url,data=data, headers = headers)
print(response.content)
This code should successfully post the data and I should get a isSuccess:true in my response variable.
Can anyone help me figure out what might be wrong?
Can you try to change;
response = requests.post(url,data=data, headers = headers)
to;
response = requests.post(url,json=data, headers = headers)
or;
response = requests.post(url,body=data, headers = headers)
I have to use a webservice endpoint that needs both JSON and non-json in the query and I don't know how to do it with the requests package. the same code provided has http.client in it, and I don't have access to that package in this project for unrelated reasons
The example code is:
import http.client
conn=http.client.HTTPSConnection('some.url')
payload="{\"some_json_dict_key\": \"some_json_dict_value\"}"
headers={'content-type': "application/json", 'accept': "application/json"}
conn.request("POST", "/someEndpoint?param1=value_of_param1", payload, headers)
res = conn.getresponse()
data = res.read().decode('utf-8')
The code i have tried which doesnt work:
import requests
headers={'content-type': "application/json", 'accept': "application/json"}
params={'param1': 'value_of_param1'}
json_payload = "{\"some_json_dict_key\": \"some_json_dict_value\"}"
url = 'https://some.url/someEndpoint'
response = requests.post(url, headers=headers, data=params, json=json_payload)
however that doesn't seem to work i get the exception
{'httpMessage': 'Bad Request', 'moreInformation': 'The body of the request, which was expected to be JSON, was invalid, and could not be decoded. The start of an object { or an array [ was expected.'}
According to the documentation:
Instead of encoding the dict yourself, you can also pass it directly using the json parameter (added in version 2.4.2) and it will be encoded automatically:
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> r = requests.post(url, json=payload)
but you're passing a string into the json parameter (I admit that the error message could be clearer). All other parameters are json/dict objects. Make json_payload an actual dictionary.
json_payload = {"some_json_dict_key": "some_json_dict_value"} # real dictionary, not a json string
url = 'https://some.url/someEndpoint'
response = requests.post(url, headers=headers, data=params, json=json_payload)
You must realize that a POST request can pass information in two places: In the body (data) of the request, and in the URL string (the request parameters, like a GET request does). In the example you didn't fully emulate, the parameters are in the URL string, and the body, according to the error message you got back, must consist of a single JSON object. Therefore, use the params dictionary for the URL parameters, like this:
response = requests.post(url, headers=headers, params=params, data=json_payload)
That ought to do it, unless there are other details to take care of.