You can download this code by clicking the button below.
This code is now available for download.
This function uses the OAuthlib library's OAuth2 client and request tools to obtain an access token from an authorization response.
Technology Stack : OAuthlib, requests
Code Type : Function
Code Difficulty : Intermediate
def fetch_access_token(client_id, client_secret, token_url, authorization_response):
from oauthlib.oauth2 import BackendApplicationClient, TokenRequest
from oauthlib.oauth2 import TokenResponse
from requests import post
# Create a backend application client
client = BackendApplicationClient(client_id=client_id)
# Create a token request
token_req = TokenRequest(
client=client,
token_url=token_url,
authorization_response=authorization_response,
body={'grant_type': 'authorization_code'}
)
# Send the token request and get the response
token_response = TokenResponse(post(token_url, data=token_req.to_dict()))
# Return the access token from the response
return token_response.access_token