Search code examples
pythoncurlpycurlhttplib2

Translating cURL request to python


I have to make a cURL request that sends information to the server, the working example request looks like:

curl "https://api.XX.com" -u ":test_KayuXJKEdc" -d "name=Sam" -d "address=123 Mockingbird" -d "city=Somewhere"

I've tried pycurl, httplib2, and requests, I can't figure out how to properly format this. A non-working pycurl example from one of many attempts:

import pycurl

user = ':test_KayuXJKEdc'
name = 'name=Sam'
address = 'address=123 Mockingbird'
city = 'city=Somewhere'

c = pycurl.Curl()
data = BytesIO()
c.setopt(c.URL, 'https://api.XX.com')
c.setopt(pycurl.USERNAME, user)
c.setopt(pycurl.POSTFIELDS, name)
c.setopt(pycurl.POSTFIELDS, address)
c.setopt(pycurl.POSTFIELDS, city)
c.setopt(c.WRITEFUNCTION, data.write)
c.perform()
c.close()

result = json.loads(data.getvalue().decode('latin-1'))
print(result)

I've done a lot of searching and experimenting for a couple days now. Any help is greatly appreciated. Thank you


Solution

  • Thanks to Galen's comment and a fresh start, here is how I ended up formatting and getting it to work:

    • Instead of c.USERNAME I had to use c.USERPWD. This was an API key and not a user name.
    • Reformatted the different data values to look like: {'name': 'Sam', 'city': 'Somewhere', etc...}
    • Used urlencode as per documentation before passing to c.POSTFIELDS