2

I am trying to send a POST request (in Python) to a server that is expecting an array containing JSON. I can't seem to format the data properly. How can I format the following payload to behave like a JavaScript array for a Node.js server?

POST /api/adduser/

Node.js expected Payload:

[ 
    {'user':'jon','email':'[email protected]'}, 
    {'user':'jon2','email':'[email protected]'} 
]

My current code:

import requests
import json

payload = \
[
   {
       'user': 'hello',
       'email': '[email protected]'
   },
   {
       'user': 'helloAgain',
       'email': '[email protected]'
   }
]

res = requests.post('http://localhost/api/users', data=json.dumps(payload))

#res -> 400 error -> reason:  "wrong json format - must be an array"
2
  • What happens if you try to encode the data as json?
    – brian buck
    Commented Jun 23, 2014 at 17:49
  • Brian - This is what I tried initially, but I get the error, "wrong json format - must be an array". The server that is handling the POST is nodejs. Commented Jun 25, 2014 at 8:35

2 Answers 2

1

Your expected payload is not correct (it's not JSON). Save yourself tons of headaches and use the json module:

import json
res = requests.post('http://localhost/api/users', data=json.dumps(payload))
3
  • thebjorn - That does not work. The POST is processed by a nodejs server expecting an array. Commented Jun 25, 2014 at 8:36
  • Then you either need to set appropriate headers Content-Type: application/json (although I thought requests did that automatically) -- and/or call JSON.parse on the node side..
    – thebjorn
    Commented Jun 25, 2014 at 15:28
  • Great suggestion, though I do not have access to the server code. I am writing python code to integrate with an external application. Commented Jun 26, 2014 at 12:35
0

Here is the solution:

POST /api/adduser/

Node.js expected Payload:

[ 
    {'user':'jon','email':'[email protected]'}, 
    {'user':'jon2','email':'[email protected]'} 
]

My current code:

import requests
import json

payload = \
[
   {
       'user': 'hello',
       'email': '[email protected]'
   },
   {
       'user': 'helloAgain',
       'email': '[email protected]'
   }
]

jsonPayload = json.dumps(payload)

headers = {'Content-Type': 'application/json'}

res = requests.post('http://localhost/api/users', data=jsonPayload, headers=headers)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.