2

I'm having an issue converting a working cURL call to an internal API to a python requests call.

Here's the working cURL call:

curl -k -H 'Authorization:Token token=12345' 'https://server.domain.com/api?query=query'

I then attempted to convert that call into a working python requests script here:

#!/usr/bin/env python
import requests

url = 'https://server.domain.com/api?query=query'
headers = {'Authorization': 'Token token=12345'}

r = requests.get(url, headers=headers, verify=False)

print r

I get a HTTP 401 or 500 error depending on how I change the headers variable around. What I do not understand is how my python request is any different then the cURL request. They are both being run from the same server, as the same user.

Any help would be appreciated

1

2 Answers 2

1

Hard to say without knowing your api, but you may have a redirect that curl is honoring that requests is not (or at least isn't send the headers on redirect).

Try using a session object to ensure all requests (and redirects) have your header.

#!/usr/bin/env python
import requests

url = 'https://server.domain.com/api?query=query'
headers = {'Authorization': 'Token token=12345'}

#start a session
s = requests.Session()

#add headers to session
s.headers.update(headers)

#use session to perform a GET request. 
r = s.get(url)

print r
Sign up to request clarification or add additional context in comments.

1 Comment

When I try your script, I get a HTTP 500 internal service error returned. <Response [500]> I tailed the API server's apache ssl access log and confirmed that there was a 500 response.
1

I figured it out, it turns out I had to specify the "accept" header value, the working script looks like this:

#!/usr/bin/env python
import requests

url = 'https://server.domain.com/api?query=query'
headers = {'Accept': 'application/app.app.v2+json', 'Authorization': 'Token token=12345'}

r = requests.get(url, headers=headers, verify=False)

print r.json()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.