Skip to content
Advertisement

Python: How to Use Requests Library to Access Flask RestPlus API hosted on Google App Engine?

I built a rest api using flask restplus and I tested it using the swagger documentation, and it seems to be fully functional and working just fine. I now want to test the API using the python requests library, but I’m getting the following error:

Invalid IAP credentials: empty token

I imagine this is because I did not authorize using the credentials. I do have access to the service account credentials json file, but just wondering how I pass this into requests?

Code Example:

url = 'https://crosssellapi-project-id.appspot.com/auth/login'

r = requests.get(url, headers={'accept': 'application/json'})

Thanks in advance.

Advertisement

Answer

I think the best way to accomplish this is using the google-auth library for python.

$ pip install google-auth

I suggest to create a service account, give it the role IAP-secured Web App User and then download the JSON key for that service account.

Go to API’s & Services > Credentials and copy the Client ID of the OAuth 2.0 client you want to use for your API.

Finally use this code snippet to make a request:

from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession

SERVICE_FILENAME = '/path/to/your/service_account_key.json'
API_URL = 'https://YOUR_API_URL'
AUDIENCE = 'YOUR_OAUTH_CLIENT_ID'

credentials = service_account.IDTokenCredentials.from_service_account_file(SERVICE_FILENAME, target_audience=AUDIENCE)

session = AuthorizedSession(credentials)

r = session.get(API_URL, headers={'accept': 'application/json'})

print(r.text)

If you want to know more about google-auth check this.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement