gmccoy gmccoy - 5 months ago 7
JSON Question

Finding JSON POST format of an API

I'm trying to figure out the format to post data to an old undocumented API built with django python.

The API using the following code to extract the POST:

ids = json.loads(request.POST.get("data", "[]"))


The
ids
is a array of ints

The following script works to post to the API:

data = dict(data="[1,3]")
r = requests.post("http://apiurl", auth=("user", "pass"), data=data)


The following doesn't work:

data = dict(data="[1,3]")
data = json.dumps(data)
r = requests.post("http://apiurl", auth=("user", "pass"), data=data)


How would I figure out the json a third party would need to post to this API to use it?

Answer
In[2]: import json
In[3]: data = dict(data="[1,3]")
In[4]: data
Out[4]: {'data': '[1,3]'}
In[5]: json.dumps(data)
Out[5]: '{"data": "[1,3]"}'

json.dumps(data) returns string.

From requests doc

:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:Request.

So API you use handle correctly post request with json:

{"data": "[list of ints]"}
#e.g.
{"data": "[2,3,4,5]"}

and that's you can figure out the third party.

Comments