slysid slysid - 4 months ago 19
Python Question

Python Request Post with param data

This is the raw request for an API call:

Accept-Encoding: gzip,deflate
Content-Type: application/json
Content-Length: 86
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)


This request returns a success (2xx) response.

Now I am trying to post this request using

>>> import requests
>>> headers = {'content-type' : 'application/json'}
>>> data ={"eventType":"AAS_PORTAL_START","data{"uid":"hfe3hf45huf33545","aid":"1","vid":"1"}}
>>> url = ""
<Response [400]>

Everything looks fine to me and I am not quite sure what I posting wrong to get a 400 response.


params is for GET-style URL parameters, data is for POST-style body information. It is perfectly legal to provide both types of information in a request, and your request does so too, but you encoded the URL parameters into the URL already.

Your raw post contains JSON data though, you better use the json module to properly encode that:

import json

data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
data = json.dumps(data)

You could split out the URL parameters too:

params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}

Then post this with:

import requests
import json

headers = {'content-type': 'application/json'}
url = ''

data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}, params=params, data=json.dumps(data), headers=headers)

If you are using requests version 2.4.2 or newer, you can have the library do the JSON encoding for you; it'll set the correct Content-Header too; all you need to do is pass in the Python object to be encoded as JSON into the json keyword argument:

import requests

url = ''

data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}, params=params, json=data)