Access token in python

Jump to solution
steven_hill
Community Explorer

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.  

Labels (6)
0 Likes
1 Solution
mclark19
Community Participant

@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

 

View solution in original post