Atihska
Atihska

Reputation: 5128

Convert curl get command to urllib get request

I have a curl request that I want to convert to urllib in python2.

curl which works and gives son response:

curl -i -X GET -H "X-AUTH-TOKEN: $AUTH_TOKEN" \
-H "Accept: application/json" \
"https://api.xyz.com/apiv1.2/reports/nodes?start_date=2014-04-01&end_date=2014-04-21"

I tried the following code and it keeps on redirecting me to login html page as response. How can I convert the above curl request to urllib?

    headers = {"Content-Type": "application/json", "AUTH_TOKEN":'1234yyzxx'}
    data = urllib.urlencode(values)
    request = urllib2.Request(ENDPOINT + '?' + data, headers=headers)
    response = urllib2.urlopen(request)
    text = response.read()
    print text

Upvotes: 0

Views: 481

Answers (1)

Atihska
Atihska

Reputation: 5128

Found it using requests library.

import requests
import json

response = requests.get(ENDPOINT, headers=headers, params=values)
text = json.loads(response.text)

However, I wouldn't mind answers in all non-deprecated libraries (urllib, urllib2, urllib3 etc).

Which one is faster?

Upvotes: 1

Related Questions