0

I have an MVC Web Api and I can add new record with below request with "simple REST Client"

URL: http://localhost:4585/api/users
Headers: Content-Type: application/json; charset=utf-8

Data:
[{
"username": "name1",
"email": "mail1",
"password": "password1"
},
{
"username": "name2",
"email": "mail2",
"password": "password2"
}]

What I want is doing same thing with python. I've tried below code but the API processed only first record properly.

import json
import urllib2
data = [{ "username": "name1", "email": "mail1", "password": "password1" }, { "username": "name2", "email": "mail2", "password": "password2" }]
response = urllib2.urlopen(req, json.dumps(data))
1
  • 1
    Are there any server-side logs with more information? Commented Mar 14, 2016 at 5:22

1 Answer 1

2

I did it with requests library.

import requests

requests_session = requests.session()
requests_session.headers.update({'Content-Type': 'application/json'})
requests_session.headers.update({'charset':'utf-8'})

post_data = '[{ "username": "name1", "email": "mail1", "password": "password1" }, { "username": "name2", "email": "mail2", "password": "password2" }]'

requests_response = requests_session.post(url="http://localhost:4585/api/users", data=post_data)

print requests_response.content
Sign up to request clarification or add additional context in comments.

1 Comment

This is a good and clear solution. The trick for me was to use { 'Authorization': ..., 'Content-Type': 'application/json', 'charset':'utf-8' } object directly as headers.

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.