How to connect from Python to a RESTful API using keys instead of a base username and password?

I am new to programming and I was asked to take a project where I need to change the current Python code that we use to connect to the Ver 1 RESTful API. The company switched to its Ver 2 API and now requires identifiers and keys for authentication instead of the primary username and password. The old code that worked for the Ver1 API is as follows:

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 through the terminal using the cURL line, such as:

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

I searched but could not find a way to get identifiers and keys from the cURL string to allow access to the Ver 2 API using Python. Thank you for your help in helping you learn this code change!

+5
source share
1 answer

you can add HTTP headers to the request

 headers = { 'X-ABC-API-ID': 'xxxx-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) 
+7
source

Source: https://habr.com/ru/post/1233185/


All Articles