0

Possible Duplicate:
CURL alternative in Python

I'm trying to write a python snippet that returns a JSON response. With curl it works and look like this:

curl -H 'content-type: application/json' \
     -d '' http://example.com/postservice.get_notes

How could I write code in python that returns a JSON object as the curl command does?

Community
  • 1
  • 1
Mikael
  • 5,429
  • 5
  • 30
  • 38

1 Answers1

2

To exactly mimic this you'll need pycurl.

import pycurl
import StringIO 

buf = StringIO.StringIO()

c = pycurl.Curl()
c.setopt(c.URL, 'http://example.com/postservice.get_notes')
c.setopt(c.WRITEFUNCTION, buf.write)
c.setopt(c.HTTPHEADER, ['Accept-Charset: UTF-8'])
c.setopt(c.POSTFIELDS, '')
c.perform()

json = buf.getvalue()
buf.close()

Note here content-type: application/json is not a valid request header. So it's not needed.

Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
  • Is this the best solution to do receive data from a web-service? – Mikael May 06 '12 at 21:26
  • **Best** is a relative word. So there is no *Best solution* unless you give any context or criteria. The solution I provided best matches your command line implementation. Both uses the same library (curl). So they will run the same code at the back end. – Shiplu Mokaddim May 07 '12 at 03:12