From 83fed3f7c41351b3cb46f48530f0783670a57199 Mon Sep 17 00:00:00 2001 From: Greg Gauthier Date: Fri, 19 Jul 2024 18:40:09 +0100 Subject: [PATCH] simple oath2 api client --- api-client/__init__.py | 0 api-client/eg.py | 29 +++++++++++++++++++++++++++++ requirements.txt | 3 +++ 3 files changed, 32 insertions(+) create mode 100644 api-client/__init__.py create mode 100644 api-client/eg.py create mode 100644 requirements.txt diff --git a/api-client/__init__.py b/api-client/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/api-client/eg.py b/api-client/eg.py new file mode 100644 index 0000000..3f7334d --- /dev/null +++ b/api-client/eg.py @@ -0,0 +1,29 @@ +from requests_oauthlib import OAuth2Session +from oauthlib.oauth2 import BackendApplicationClient + + +def get_token(client_id, client_secret, token_url, username, password): + client = BackendApplicationClient(client_id=client_id) + oauth = OAuth2Session(client=client) + token = oauth.fetch_token(token_url=token_url, username=username, password=password, client_id=client_id, + client_secret=client_secret) + return token + + +def api_client(base_url, token): + client = OAuth2Session(token=token) + response = client.get(base_url) + return response.content + + +client_id = '' +client_secret = '' +token_url = '' +username = '' +password = '' + +# Fetch token +token = get_token(client_id, client_secret, token_url, username, password) + +# Now we can make API calls +api_response = api_client('https://api.example.com/resource', token) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..a2003b5 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +oauthlib~=3.2.2 +requests~=2.32.3 +requests-oauthlib~=2.0.0 \ No newline at end of file