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

Maumee River
  • 253
  • 2
  • 7
  • 25
  • Possible duplicate of [python request with authentication (access\_token)](http://stackoverflow.com/questions/13825278/python-request-with-authentication-access-token) – OneCricketeer Apr 27 '16 at 17:48

2 Answers2

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
Kerry Hatcher
  • 601
  • 6
  • 17
  • When I try your script, I get a HTTP 500 internal service error returned. `` I tailed the API server's apache ssl access log and confirmed that there was a 500 response. – Maumee River Apr 27 '16 at 18:12
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()
Maumee River
  • 253
  • 2
  • 7
  • 25