2024-07-19 17:40:09 +00:00
|
|
|
from requests_oauthlib import OAuth2Session
|
|
|
|
from oauthlib.oauth2 import BackendApplicationClient
|
|
|
|
|
|
|
|
|
2024-07-19 17:47:03 +00:00
|
|
|
def get_token(client_id, client_secret, token_url, username, password, audience, scope):
|
2024-07-19 17:40:09 +00:00
|
|
|
client = BackendApplicationClient(client_id=client_id)
|
|
|
|
oauth = OAuth2Session(client=client)
|
2024-07-19 17:47:03 +00:00
|
|
|
token = oauth.fetch_token(
|
|
|
|
token_url=token_url,
|
|
|
|
username=username,
|
|
|
|
password=password,
|
|
|
|
client_id=client_id,
|
|
|
|
client_secret=client_secret,
|
|
|
|
audience=audience,
|
|
|
|
scope=scope
|
|
|
|
)
|
2024-07-19 17:40:09 +00:00
|
|
|
return token
|
|
|
|
|
|
|
|
|
|
|
|
def api_client(base_url, token):
|
|
|
|
client = OAuth2Session(token=token)
|
|
|
|
response = client.get(base_url)
|
|
|
|
return response.content
|
|
|
|
|
|
|
|
|
|
|
|
client_id = '<your_client_id>'
|
|
|
|
client_secret = '<your_secret_id>'
|
|
|
|
token_url = '<oauth_token_url>'
|
|
|
|
username = '<your_username>'
|
|
|
|
password = '<your_password>'
|
2024-07-19 17:47:03 +00:00
|
|
|
audience = '<intended_audience>'
|
|
|
|
scope = ['scope1', 'scope2']
|
2024-07-19 17:40:09 +00:00
|
|
|
|
|
|
|
# Fetch token
|
2024-07-19 17:47:03 +00:00
|
|
|
token = get_token(client_id, client_secret, token_url, username, password, audience, scope)
|
2024-07-19 17:40:09 +00:00
|
|
|
|
|
|
|
# Now we can make API calls
|
|
|
|
api_response = api_client('https://api.example.com/resource', token)
|
2024-07-19 17:47:03 +00:00
|
|
|
|
|
|
|
print(api_response)
|