0

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?

Pankaj Kumar
  • 147
  • 11

1 Answers1

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-09T08:00&metrics=count_sent', headers=headers)
print(res.text)
NYC Coder
  • 7,424
  • 2
  • 11
  • 24
  • thanks, by API_KEY - do you mean the actual key? by the way - either of it didn't work. It gives me NameError – Pankaj Kumar Jan 10 '23 at 19:40
  • API_KEY is just a variable that holds the key, try just `api_key` instead of `x-api-key` – NYC Coder Jan 10 '23 at 19:42
  • hmm I got you. I did all the changes and now I see error - Unauthorized. so it still didn't work – Pankaj Kumar Jan 10 '23 at 19:47
  • Looks like the api key isn't valid – NYC Coder Jan 10 '23 at 19:48
  • 1
    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 help – Pankaj Kumar Jan 10 '23 at 19:52