Python Forum

Full Version: Python requests oauth2 access token
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I am new to python programming and trying to make a RESTful api call and retrieve json payload from a GET method. I am using the below code but I get error and not sure how to proceed from here.

import sys
import requests
import json
import logging
import time

logging.captureWarnings(True)
api_url = "https://webapi.com/api/v1/data"

def get_new_token():
    acc_token_url = "https://webapi.com/connect/accesstoken"
    client_id = 'client'
    client_secret = 'secret'
    token_req_payload = {'grant_type': 'client_credentials'}
    token_response = requests.post(acc_token_url , data = token_req_payload, verify = False, allow_redirects = False, auth = (client_id, client_secret))
         
    if token_response.status_code != 200:
        print("Failed to obtain token from OAuth2 server", file = sys.stderr)
        sys.exit(1)
        print("Successfuly obtained a new token from OAuth2 server")
        tokens = json.loads(token_response.text)
    return tokens['access_token']

token = get_new_token()

while True:    
    api_call_headers = {'Authorization': 'Bearer ' + token}
    api_call_response = requests.get(api_url, headers = api_call_headers, verify = False)

if  api_call_response.status_code == 401:
    token = get_new_token()
else:
    print(api_call_response.text)
Error:
Traceback (most recent call last): NameError: name 'token_response' is not defined
Looks like your indentation needs fixing.
(Sep-20-2021, 03:51 AM)ndc85430 Wrote: [ -> ]Looks like your indentation needs fixing.

Hi, I have fixed the indentation and now run into the below error.

Error:
UnboundLocalError: local variable 'tokens' referenced before assignment
Going by the code in your previous post, since you haven't shown the updated version, here's a hint. What happens if the response has a status other than 200?
Modified code:

import sys
import requests
import json
import logging
import time

logging.captureWarnings(True)
api_url = "https://webapi.com/api/v1/data"

def get_new_token():
    acc_token_url = "https://webapi.com/connect/accesstoken"
    client_id = 'client'
    client_secret = 'secret'
    token_req_payload = {'grant_type': 'client_credentials'}
    token_response = requests.post(acc_token_url , data = token_req_payload, verify = False, allow_redirects = False, auth = (client_id, client_secret))
             
    if token_response.status_code != 200:
       print("Failed to obtain token from OAuth2 server", file = sys.stderr)
       sys.exit(1)
    print("Successfuly obtained a new token from OAuth2 server")
    tokens = json.loads(token_response.text)
    return tokens['access_token']

token = get_new_token()

while True:    
    api_call_headers = {'Authorization': 'Bearer ' + token}
    api_call_response = requests.get(api_url, headers = api_call_headers, verify = False)

if  api_call_response.status_code == 401:
    token = get_new_token()
else:
    print(api_call_response.text)
Below is the new error message I get after modifying the code.

Error:

Error:
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='www.webapi.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError(': Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond'))
Requests has own library for OAuth 2 in Doc.
requests-oauthlib.
(Sep-27-2021, 05:04 AM)snippsat Wrote: [ -> ]Requests has own library for OAuth 2 in Doc.
requests-oauthlib.

Thank you for your response. I have modified my code accordingly. Please let me know if I am doing it right.

import sys
import requests
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import BackendApplicationClient
import json
import logging
import time

logging.captureWarnings(True)
api_url = "https://webapi.com/api/v1/data"

#Obtain credentials from OAuth provider

client_id = 'client'
client_secret = 'secret'

#Fetch an access token from the provider.

client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
token = oauth.fetch_token(token_url='https://webapi.com/connect/accesstoken', client_id=client_id, client_secret=client_secret)

#Automatic token refresh and update

client = OAuth2Session(client_id, token=token)
response = client.get(api_url)
data = response.json()
Regards