You can download this code by clicking the button below.
This code is now available for download.
This function uses the OAuth2 client and session from the OAuthlib library to obtain an access token. It takes client ID, client secret, token URL, authorization URL, redirect URI, and authorization code as parameters, and then returns the access token.
Technology Stack : OAuthlib
Code Type : Function
Code Difficulty : Intermediate
def fetch_access_token(client_id, client_secret, token_url, auth_url, redirect_uri, code):
from oauthlib.oauth2 import BackendApplicationClient, TokenRequest
from oauthlib.oauth2 import BackendSession
from requests import post
# Create an OAuth2 client with the backend application client
client = BackendApplicationClient(client_id=client_id)
# Create a token request
token_request = TokenRequest(
client=client,
token_url=token_url,
authorization_url=auth_url,
redirect_uri=redirect_uri,
code=code,
auth_method='client_secret_post'
)
# Create a session with the token request
session = BackendSession(client=client)
# Exchange the code for a token
token_response = session.post(token_url, data=token_request.to_dict())
# Return the access token
return token_response.json().get('access_token')