Skip to content

Instantly share code, notes, and snippets.

@AMcManigal
Created June 30, 2021 15:56
Show Gist options
  • Save AMcManigal/01f7bfe99dba41c0414460a805a02bf1 to your computer and use it in GitHub Desktop.
Save AMcManigal/01f7bfe99dba41c0414460a805a02bf1 to your computer and use it in GitHub Desktop.
Manheim API Auth Example
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))
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