Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I connect with Python to a RESTful API using keys instead of basic authentication username and password?

I am new to programming, and was asked to take over a project where I need to change the current Python code we use to connect to a Ver 1 RESTful API. The company has switched to their Ver 2 of the API and now require IDs and Keys for authentication instead of the basic username and password. The old code that worked for the Ver 1 API looks like this:

import requests
import simplejson as json
import pprintpp as pprint

#API_Ver1 Auth
USER = 'username'
PASS = 'password'
url = 'https://somecompany.com/api/v1/groups'
s = requests.Session()
s.auth = (USER, PASS)

r = json.loads(s.get(url).text)
groups = r["data"]

I can connect to the Ver 2 API via a terminal using a cURL string like this:

curl -v -X GET -H "X-ABC-API-ID:x-x-x-x-x" -H "X-ABC-API-KEY:nnnnnnnnnnnnnnnnnnnnnnn" -H "X-DE-API-ID:x" -H "X-DE-API-KEY:nnnnnnnnnnnnnnnnnnnnnnnn" "https://www.somecompany.com/api/v2/groups/"

I have searched, but have been unsuccessful in finding a way to get the IDs and Keys from the cURL string to allow access to the Ver 2 API using Python. Thanks for your consideration in helping a noob get through this code change!

like image 273
wautry Avatar asked Oct 07 '15 17:10

wautry


People also ask

How do I authenticate API key in Python?

To authenticate, you must first send a POST request to the /session route, with your API key present in the X-IG-API-KEY header. This is where you'll need the username and password. A valid username / password then gives you security tokens to be used for subsequent requests.

How do you pass credentials in REST API?

Application credential requirements The client must create a POST call and pass the user name, password, and authString in the Request headers using the /x-www-form-urlencoded content type. The AR System server then performs the normal authentication mechanisms to validate the credentials.

How do I use REST API in Python?

There are several ways to consume a REST API from Python. However, the easiest way is to utilize the module, requests. Here, we are calling the get method defined in the requests module. The URL will determine what data will be returned back.


Video Answer


1 Answers

you can add HTTP headers to a request

headers = {
    'X-ABC-API-ID': 'x-x-x-x-x',
    'X-ABC-API-KEY': 'nnnnnnnnnnnnnnnnnnnnnnn',
    'X-DE-API-ID': 'x',
    'X-DE-API-KEY': 'nnnnnnnnnnnnnnnnnnnnnnnn'
}
r = requests.get('https://www.somecompany.com/api/v2/groups/', headers=headers)
like image 175
r-m-n Avatar answered Sep 19 '22 03:09

r-m-n