'Python API KeyError
I'm new to both python and APIs. lol. But google isn't helping. I have the below simple authentication request and am getting a KeyError: 'token' from the line, authorization = {"Authorization": "Bearer " + token['token']}
I appreciate any guidance you can provide!
#!/usr/bin/python3
import requests
import argparse
import math
import os
import json
export_format_map = {
"csv": "zip",
"json": "json",
"kml": "kml"
}
def download_logs(args):
"""
NOTE: Requires user credentials
Downloads log files from user-specified host in user-specified file format.
"""
rest_api = "https://address.here/api/1.0"
# Step 1. Login and get token to authenticate requests
print(f"Logging into {rest_api}...")
# Get username and password from environment variables
username = os.environ.get('USERNAME')
password = os.environ.get('PASSWORD')
# Put the credentials into a dictionary object
credentials = {"email": username, "password": password}
r = requests.post(f"{rest_api}/authentication/login", json=credentials)
# Build the JWT compliant authorization dictionary
token = json.loads(r.text)
authorization = {"Authorization": "Bearer " + token['token']}
# Step 2. Gather a list of contacts filtered to be within the min/max timestamps
def get_agents(params):
"""Sends GET request to API with provided parameters; Returns response."""
response = requests.get(
url=f"{rest_api}/agent",
params=params,
headers=authorization
).json()
return response
#code continues.....
I have also tried setting up the token request like this with the same error:
TOKEN = requests.post(
url=f"{rest_api}/authentication/login",
data={
"email": input("\nusername/email: "),
"password": getpass.getpass(),
}
).json()
authorization = {"Authorization": "Bearer " + TOKEN['token']}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
