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!
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With