Using python requests library to send json in http

2019-08-23 19:31发布

问题:

I am trying to send a http GET request using python requests library. Following is my code.

#!/usr/bin/python3
import requests
import json

URL = some-elkstack-url

datam = {'ayyo' : 'vammo'}
data_json = json.dumps(datam)
payload = {'json_payload': data_json}
header={'Content-Type': 'application/json' }
r = requests.get(url=URL, headers=header, data=datam)
a = r.json()
print('\nResponse: \n')
print(a)

I am getting this HTTP error back from the server.

{'error': {'root_cause': [{'type': 'json_parse_exception', 'reason': "Unrecognized token 'ayyo': was expecting ('true', 'false' or 'null')\n at 
[Source: org.elasticsearch.transport.netty4.ByteBufStreamInput@74cef381; line: 1, column: 6]"}], 'type': 'json_parse_exception', 'reason': "Unrecognized token 'ayyo': was expecting ('true', 'false' or 'null')\n at 
[Source: org.elasticsearch.transport.netty4.ByteBufStreamInput@74cef381; line: 1, column: 6]"}, 'status': 500}

When I do a curl from the command line, with the same json data I can get a proper response. What's going wrong in my code?

回答1:

Instead of data, you want to use the json parameter, as follows:

datam = {'ayyo' : 'vammo'}
r = requests.get(URL,headers={'Content-Type': 'application/json' }, json=datam)
a = r.json()
# so on

Hope that helps!