Access token in python
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
09-20-2024
03:41 PM
This is probably an easy question, the answer to which will make me go 'Well duh'. I'm trying to get an access token for Canvas Data Portal 2 using python. I've gotten the client id and secret. I'm trying to create the request to use those to get the access token. Basically, what I want is an example of that in python. The examples I've found online are using Powershell or something else.
Solved! Go to Solution.
1 Solution
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
09-23-2024
06:12 AM
@steven_hill we use something like this:
# Function to retrieve an access token from the Instructure API using client credentials
def get_access_token(client_id, client_secret):
api_key = base64.b64encode(f"{client_id}:{client_secret}".encode()).decode('utf-8')
# Setting up target API url
url = "https://api-gateway.instructure.com/ids/auth/login"
payload = {'grant_type': 'client_credentials'}
headers = {
'Authorization': f'Basic {api_key}',
'Content-Type': 'application/x-www-form-urlencoded'
}
# POST request
response = requests.post(url, headers=headers, data=payload)
# Raise an exception if status code is not ok
response.raise_for_status()
try:
# Converting the response into json for easy manipulation
response_json = response.json()
# Extracting token from the response
access_token = response_json.get('access_token')
# If access token is not found in the response, raise an exception
if not access_token:
raise ValueError("Access token not found in the response")
except ValueError:
raise ValueError("Invalid JSON in the response")
return access_token