How to access API data using authentication type 'API key' in Python?

Question:

I need to access Sparkpost data using their API. They do so via Authentication type = ‘API key’ instead of Basic Auth. I can do Basic Auth in Python using the code below.

import requests
import json
import requests
from requests.auth import HTTPBasicAuth

Response_API = requests.get('https://api.sparkpost.com/api/v1/metrics/sending-domain?from=2023-01-09T08:00&metrics=count_sent', auth = HTTPBasicAuth('key', 'abcd1234xyz_key'))
Data = Response_API.text
print(Data)

I know I can’t use this piece of code to get the data from API using ‘API key’ type. can someone please tell me how to do this?

Asked By: Pankaj Kumar

||

Answers:

You can pass it in headers:

headers = {
    'Accept': 'application/json',
    'x-api-key': API_KEY
}

res = requests.get('https://api.sparkpost.com/api/v1/metrics/sending-domain?from=2023-01-09T08:00&metrics=count_sent', headers=headers)
print(res.text)
Answered By: NYC Coder
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.