Python 클라이언트에서 Cloud Endpoints API에 액세스하려면 Google API Python 클라이언트 라이브러리를 사용해야 합니다.
API에 인증이 필요하지 않으면 다음 코드 예시에 표시된 것처럼 클라이언트가 API에 액세스할 수 있습니다.
importpprintfromgoogleapiclient.discoveryimportbuilddefmain():# 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에 액세스할 수 있습니다.
importargparseimportpprintimportsysfromgoogleapiclientimportdiscoveryimporthttplib2importoauth2clientfromoauth2clientimporttoolsCLIENT_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'defmain(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()ifcredentialsisNoneorcredentials.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_ID와 YOUR_CLIENT_SECRET에 대한 자세한 내용은 클라이언트 ID 만들기를 참조하세요.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2024-12-21(UTC)"],[[["\u003cp\u003eThe Google APIs Python Client Library is required to access a Cloud Endpoints API from a Python client.\u003c/p\u003e\n"],["\u003cp\u003eFor APIs that do not require authentication, you can directly access the API using the \u003ccode\u003ebuild\u003c/code\u003e function to create a service object and then call the API methods.\u003c/p\u003e\n"],["\u003cp\u003eAccessing an API that requires authentication necessitates both the Google APIs Python Client Library and the OAuth2.0 Client Library.\u003c/p\u003e\n"],["\u003cp\u003eWhen accessing an API requiring authentication, you must set up an OAuth2 flow to acquire and store an OAuth token, which will be used to authorize HTTP requests.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eapi_root\u003c/code\u003e, \u003ccode\u003eapi\u003c/code\u003e, and \u003ccode\u003eversion\u003c/code\u003e variables are used to define the root URL, the name of the API and its version respectively in the code examples.\u003c/p\u003e\n"]]],[],null,["# Accessing backend APIs from Python clients\n\nIf you want to access an Cloud Endpoints API from a Python client, you need\nto use the [Google APIs Python Client Library](https://github.com/google/google-api-python-client).\nIf the API doesn't require any authentication, your client can access the API as\nshown in the following example code: \n\n```python\nimport pprint\n\nfrom googleapiclient.discovery import build\n\n\ndef main():\n # Build a service object for interacting with the API.\n api_root = 'https://guestbook.appspot.com/_ah/api'\n api = 'guestbook'\n version = 'v0.2'\n discovery_url = '%s/discovery/v1/apis/%s/%s/rest' % (api_root, api, version)\n service = build(api, version, discoveryServiceUrl=discovery_url)\n\n # Fetch all greetings and print them out.\n response = service.greetings().list().execute()\n pprint.pprint(response)\n\n # Fetch a single greeting and print it out.\n response = service.greetings().get(id='9001').execute()\n pprint.pprint(response)\n\n\nif __name__ == '__main__':\n main()\n```\n\nIn the example code:\n\n- `api_root` is the frontend root URL under which your API methods are exposed. Usually, the URL is `https://`\u003cvar translate=\"no\"\u003eYOUR_PROJECT_ID\u003c/var\u003e`.appspot.com/_ah/api` where \u003cvar translate=\"no\"\u003eYOUR_PROJECT_ID\u003c/var\u003e represents your Google Cloud\n- `api` is the name of the API.\n- `version` is the version of the backend API.\n\n### Accessing an API requiring Authentication\n\nIf the backend API requires authentication, you need use both the\n[Google APIs Python Client Library](https://github.com/google/google-api-python-client)\nand the [OAuth2.0 Client Library](https://github.com/google/oauth2client).\n\nYour client can get the required authorization and access the API\nby using code similar to the following: \n\n```python\nimport argparse\nimport pprint\nimport sys\n\nfrom googleapiclient import discovery\nimport httplib2\nimport oauth2client\nfrom oauth2client import tools\n\n\nCLIENT_ID = '\u003cvar translate=\"no\"\u003eYOUR_CLIENT_ID\u003c/var\u003e'\nCLIENT_SECRET = '\u003cvar translate=\"no\"\u003eYOUR_CLIENT_SECRET\u003c/var\u003e'\nSCOPE = 'https://www.googleapis.com/auth/userinfo.email'\nUSER_AGENT = 'my-cmdline-tool/1.0'\nOAUTH_DISPLAY_NAME = 'My Commandline Tool'\n\n\ndef main(argv):\n # Parse command line flags used by the oauth2client library.\n parser = argparse.ArgumentParser(\n description='Auth sample',\n formatter_class=argparse.RawDescriptionHelpFormatter,\n parents=[tools.argparser])\n flags = parser.parse_args(argv[1:])\n\n # Acquire and store oauth token.\n storage = oauth2client.file.Storage('guestbook.dat')\n credentials = storage.get()\n\n if credentials is None or credentials.invalid:\n flow = oauth2client.client.OAuth2WebServerFlow(\n client_id=YOUR_CLIENT_ID,\n client_secret=YOUR_CLIENT_SECRET,\n scope=SCOPE,\n user_agent=USER_AGENT,\n oauth_displayname=OAUTH_DISPLAY_NAME)\n credentials = tools.run_flow(flow, storage, flags)\n http = httplib2.Http()\n http = credentials.authorize(http)\n\n # Build a service object for interacting with the API.\n api_root = 'https://guestbook.appspot.com/_ah/api'\n api = 'guestbook'\n version = 'v0.2'\n discovery_url = '%s/discovery/v1/apis/%s/%s/rest' % (api_root, api, version)\n service = discovery.build(\n api, version, discoveryServiceUrl=discovery_url, http=http)\n\n # Fetch all greetings and print them out.\n response = service.greetings().list().execute()\n pprint.pprint(response)\n\n # Fetch a single greeting and print it out.\n response = service.greetings().get(id='9001').execute()\n pprint.pprint(response)\n\n\nif __name__ == '__main__':\n main(sys.argv)\n```\n\nNotice that `SCOPE` must be set as shown. For information about\n\u003cvar translate=\"no\"\u003eYOUR_CLIENT_ID\u003c/var\u003e and\n\u003cvar translate=\"no\"\u003eYOUR_CLIENT_SECRET\u003c/var\u003e, see\n[Creating client IDs](/endpoints/docs/frameworks/python/creating-client-ids)."]]