Created
June 30, 2021 15:56
-
-
Save AMcManigal/01f7bfe99dba41c0414460a805a02bf1 to your computer and use it in GitHub Desktop.
Manheim API Auth Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json, os | |
from oauthlib.oauth2 import BackendApplicationClient | |
from requests_oauthlib import OAuth2Session | |
from oauthlib.oauth2 import TokenExpiredError | |
from requests.models import Response | |
# Example Values | |
# CLIENT_ID=123456 | |
# CLIENT_SECRET=secret | |
# ENVIRONMENT=integration1. | |
# SCOPES=scope1 scope2 | |
# GRANT_TYPE=client_credentials | |
client_id = os.getenv('CLIENT_ID') | |
client_secret = os.getenv('CLIENT_SECRET') | |
token_endpoint = f'https://{os.getenv("ENVIRONMENT")}api.manheim.com/oauth2/token.oauth2' | |
scopes = os.getenv('SCOPES') | |
grant_type = os.getenv('GRANT_TYPE') | |
def get_client() -> 'OAuth2Session': | |
backend_client = BackendApplicationClient(client_id=client_id, client_secret=client_secret) | |
oauth_client = OAuth2Session(client=backend_client) | |
get_token(oauth_client) | |
return oauth_client | |
def get_token(oauth_client: OAuth2Session) -> str: | |
body = oauth_client.fetch_token( | |
token_url=token_endpoint, | |
client_id=client_id, | |
client_secret=client_secret, | |
body=f'grant_type={grant_type}&scope={scopes}' | |
) | |
return body['access_token'] | |
def token_valid(resp: Response): | |
if resp.status_code == 401 and 'Server' in resp.headers and 'Mashery Proxy' in resp.headers['Server']: | |
return False | |
return True | |
def make_request(client: OAuth2Session, method: str, url: str, **kwargs): | |
try: | |
resp = client.request(method, url, *kwargs) | |
if not token_valid(resp): | |
raise TokenExpiredError() | |
return resp | |
except TokenExpiredError as e: | |
get_token(client) | |
resp = client.request(method, url, *kwargs) | |
if not token_valid(resp): | |
print(e) | |
print(json.loads(resp.text)) | |
exit(1) | |
return resp | |
url = f"https://{os.getenv('ENVIRONMENT')}api.manheim.com/valuations/colors" | |
headers = {"Content-Type":"application/x-www-form-urlencoded"} | |
client = get_client() | |
print(json.loads(make_request(client, 'GET', url, headers=headers).text)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
requests~=2.25.1 | |
requests-oauthlib | |
oauthlib~=3.1.1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment