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? 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))
Sign up to request clarification or add additional context in comments.

3 Comments

thebjorn - That does not work. The POST is processed by a nodejs server expecting an array.
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..
Great suggestion, though I do not have access to the server code. I am writing python code to integrate with an external application.
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)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.