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

Tags: , ,

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 = ''

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

Thanks in advance.


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'

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'})


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

Source: stackoverflow