Python – Post JSON data to Web Service that is expecting a JSON

Had a really hard time trying to find the PHP-CURL equivalent in Python to post JSON data to a web service. After mixing samples from various posts, I was able to get a simple prototype working. So here’s the code to post JSON data using urllib2 in Python

import json
import urllib
import urllib2

url = "http://web-server.com:8081/welcome"
values = {'customer' : 'Varun Inc',
'email' : 'varun.verma@varun.com'}

req = urllib2.Request(url, json.dumps(values), headers={'Content-type': 'application/json', 'Accept': 'application/json'})
response = urllib2.urlopen(req)
the_page = response.read()
print the_page
Advertisements

2 thoughts on “Python – Post JSON data to Web Service that is expecting a JSON

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s