[英]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.我使用flask restplus 构建了一个rest api,并使用swagger 文档对其进行了测试,它似乎功能齐全并且工作正常。 I now want to test the API using the python requests library, but I'm getting the following error:
我现在想使用 python requests 库测试 API,但出现以下错误:
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?
我确实有权访问服务帐户凭据 json 文件,但只是想知道如何将其传递给请求?
Code Example:代码示例:
url = 'https://crosssellapi-project-id.appspot.com/auth/login'
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.我认为最好的方法是使用 python 的
google-auth
库。
$ 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.我建议创建一个服务帐户,赋予它IAP-secured Web App User角色,然后下载该服务帐户的 JSON 密钥。
Go to API's & Services > Credentials and copy the Client ID
of the OAuth 2.0 client you want to use for your API.转至API 和服务 > 凭据并复制要用于 API 的 OAuth 2.0 客户端的
Client ID
。
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 .如果您想了解有关
google-auth
更多信息,请查看此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.