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月09日T08: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?
1 Answer 1
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月09日T08:00&metrics=count_sent', headers=headers)
print(res.text)
answered Jan 10, 2023 at 19:10
NYC Coder
7,6443 gold badges14 silver badges25 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
Pankaj Kumar
thanks, by API_KEY - do you mean the actual key? by the way - either of it didn't work. It gives me NameError
NYC Coder
API_KEY is just a variable that holds the key, try just
api_key instead of x-api-keyPankaj Kumar
hmm I got you. I did all the changes and now I see error - Unauthorized. so it still didn't work
NYC Coder
Looks like the api key isn't valid
Pankaj Kumar
hey - got to know what changes need to be done. You're all right. Instead of
x-api-key I had to write Authorization and it works now. not your fault - that keyword is app specific, so for Sparkpost I need to write Authorization. thank you again for your helplang-py