从 Python 客户端访问后端 API

如果要从 Python 客户端访问 Cloud Endpoints API,需要使用 Google API Python 客户端库。 如果 API 无需任何身份验证,则您的客户端可以访问 API,具体如以下示例代码所示:

import pprint

from googleapiclient.discovery import build


def main():
  # Build a service object for interacting with the API.
  api_root = 'https://guestbook.appspot.com/_ah/api'
  api = 'guestbook'
  version = 'v0.2'
  discovery_url = '%s/discovery/v1/apis/%s/%s/rest' % (api_root, api, version)
  service = build(api, version, discoveryServiceUrl=discovery_url)

  # Fetch all greetings and print them out.
  response = service.greetings().list().execute()
  pprint.pprint(response)

  # Fetch a single greeting and print it out.
  response = service.greetings().get(id='9001').execute()
  pprint.pprint(response)


if __name__ == '__main__':
  main()

在此示例代码中:

  • api_root 是用于提供 API 方法的前端根网址。通常网址为 https://YOUR_PROJECT_ID.appspot.com/_ah/api,其中 YOUR_PROJECT_ID 表示您的 Google Cloud
  • api 是 API 的名称。
  • version 是后端 API 的版本。

访问需要身份验证的 API

如果后端 API 要求进行身份验证,则需同时使用 Google API Python 客户端库OAuth2.0 客户端库

您的客户端可以使用类似以下形式的代码获取所需授权并访问 API:

import argparse
import pprint
import sys

from googleapiclient import discovery
import httplib2
import oauth2client
from oauth2client import tools


CLIENT_ID = 'YOUR_CLIENT_ID'
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
SCOPE = 'https://www.googleapis.com/auth/userinfo.email'
USER_AGENT = 'my-cmdline-tool/1.0'
OAUTH_DISPLAY_NAME = 'My Commandline Tool'


def main(argv):
  # Parse command line flags used by the oauth2client library.
  parser = argparse.ArgumentParser(
      description='Auth sample',
      formatter_class=argparse.RawDescriptionHelpFormatter,
      parents=[tools.argparser])
  flags = parser.parse_args(argv[1:])

  # Acquire and store oauth token.
  storage = oauth2client.file.Storage('guestbook.dat')
  credentials = storage.get()

  if credentials is None or credentials.invalid:
    flow = oauth2client.client.OAuth2WebServerFlow(
        client_id=YOUR_CLIENT_ID,
        client_secret=YOUR_CLIENT_SECRET,
        scope=SCOPE,
        user_agent=USER_AGENT,
        oauth_displayname=OAUTH_DISPLAY_NAME)
    credentials = tools.run_flow(flow, storage, flags)
  http = httplib2.Http()
  http = credentials.authorize(http)

  # Build a service object for interacting with the API.
  api_root = 'https://guestbook.appspot.com/_ah/api'
  api = 'guestbook'
  version = 'v0.2'
  discovery_url = '%s/discovery/v1/apis/%s/%s/rest' % (api_root, api, version)
  service = discovery.build(
      api, version, discoveryServiceUrl=discovery_url, http=http)

  # Fetch all greetings and print them out.
  response = service.greetings().list().execute()
  pprint.pprint(response)

  # Fetch a single greeting and print it out.
  response = service.greetings().get(id='9001').execute()
  pprint.pprint(response)


if __name__ == '__main__':
  main(sys.argv)

请注意,必须按所示方式设置 SCOPE。如需了解 YOUR_CLIENT_IDYOUR_CLIENT_SECRET,请参阅创建客户端 ID