Write curl in python code
Question: > **Possible Duplicate:**  
>  [CURL alternative in
> Python](http://stackoverflow.com/questions/2667509/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?


Answer: To **exactly mimic** this you'll need
[pycurl](http://pycurl.sourceforge.net/).

    
    
    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.

