Acceder a APIs de backend desde clientes de Python

Si quieres acceder a una API de Cloud Endpoints desde un cliente de Python, debes usar la biblioteca de cliente de APIs de Google para Python. Si la API no requiere autenticación, tu cliente puede acceder a ella como se muestra en el siguiente código de ejemplo:

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()

En el código de ejemplo:

  • api_root es la URL raíz del frontend en la que se exponen los métodos de tu API. Normalmente, la URL es https://YOUR_PROJECT_ID.appspot.com/_ah/api donde YOUR_PROJECT_ID representa tu Google Cloud
  • api es el nombre de la API.
  • version es la versión de la API backend.

Acceder a una API que requiere autenticación

Si la API de backend requiere autenticación, debes usar tanto la biblioteca de cliente de las APIs de Google para Python como la biblioteca de cliente de OAuth 2.0.

Tu cliente puede obtener la autorización necesaria y acceder a la API mediante un código similar al siguiente:

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)

Ten en cuenta que SCOPE debe definirse como se muestra. Para obtener información sobre YOUR_CLIENT_ID y YOUR_CLIENT_SECRET, consulta el artículo sobre cómo crear IDs de cliente.