如何验证 http 请求,用于访问 gcp API 服务 (python)

How to authenticate http request, for accessing gcp API services (python)

为了获得启用的 GCP-api 服务列表,我试图根据此 link.

中的 HTTP 请求获取 service.list

这是我的代码:

import json
from requests.auth import HTTPBasicAuth
import requests
from google.oauth2 import service_account


auth = HTTPBasicAuth('myusername@gmail.com','xyz....')

url = 'https://serviceusage.googleapis.com/v1/projects/my-proj-id123/services'

headers = {
   "Accept": "application/json"
 }

response = requests.request(
   "GET",
   url,
   headers=headers,
   auth=auth
 )
# a=json.loads(response.text)
print(response.text) 

但是我收到这个错误:

{
  "error": {
    "code": 403,
    "message": "The request is missing a valid API key.",
    "status": "PERMISSION_DENIED"
  }
}

注意:我需要一种方法来根据此 link 获得响应,可以通过 服务帐户 或通过api 令牌 。我有服务帐户密钥 (credential.json),但我不知道将 http 请求放在哪里。请给我建议程序。

我鼓励您在与 Google 的服务交互时考虑使用 Google 的 SDK。

这些服务不仅提供有助于创建请求和响应的特定于语言的资源类型,而且您还可以获得更简单的身份验证、日志记录等。

记录在案:

设置:

PROJECT=[[YOUR-PROJECT]]
ACCOUNT=[[YOUR-ACCOUNT]]

python3 -m venv venv
source venv/bin/activate

python3 -m pip install google-auth
python3 -m pip install google-cloud-service-management

gcloud iam service-accounts create ${ACCOUNT} \
--project=${PROJECT}

EMAIL="${ACCOUNT}@${PROJECT}.iam.gserviceaccount.com"

gcloud projects add-iam-policy-binding ${PROJECT} \
--member=serviceAccount:${EMAIL} \
--role=roles/viewer

gcloud iam service-accounts keys create ${PWD}/${ACCOUNT}.json \
--iam-account=${EMAIL}

export GOOGLE_APPLICATION_CREDENTIALS=${PWD}/${ACCOUNT}.json

python3 ./main.py

main.py:

import google.auth
from google.cloud import servicemanagement_v1

credentials,project = google.auth.default()

client = servicemanagement_v1.ServiceManagerClient()

# How to construct the Request
rqst = {
     # Purely for example
    "pageSize": 5,
     # List only project's services
    "consumer_id: "project:{project}".format(
        project=project
    )
}

# Response is a ServiceListPager
resp = client.list_services(request=rqst)

# Which is iterable
for managed_service in resp:
    try:
        # This is a quirk of gRPC Transcoding
        # Convert a ManagedService to JSON
        j=servicemanagement_v1.ManagedService.to_json(managed_service)
        print(j)
    except Exception as e:
        print(e)

产量:

{
  "serviceName": "abusiveexperiencereport.googleapis.com",
  "producerProjectId": ""
}
{
  "serviceName": "acceleratedmobilepageurl.googleapis.com",
  "producerProjectId": ""
}
{
  "serviceName": "accessapproval.googleapis.com",
  "producerProjectId": ""
}
...