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 메서드가 노출되는 프런트엔드 루트 URL입니다. 일반적으로 URL은 https://YOUR_PROJECT_ID.appspot.com/_ah/api이며, 여기서 YOUR_PROJECT_ID는 Google Cloud를 나타냅니다.
  • api는 API의 이름입니다.
  • version는 백엔드 API의 버전입니다.

인증이 필요한 API에 액세스

백엔드 API에 인증이 필요한 경우, Google APIs 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 만들기를 참조하세요.