Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Se vuoi accedere a un'API Cloud Endpoints da un client Python, devi utilizzare la libreria client Python per le API di Google.
Se l'API non richiede alcuna autenticazione, il client può accedervi come mostrato nel seguente codice di esempio:
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()
Nel codice di esempio:
api_root è l'URL principale del frontend in cui sono esposti i metodi dell'API.
Di solito, l'URL è
https://YOUR_PROJECT_ID.appspot.com/_ah/api
dove YOUR_PROJECT_ID rappresenta il tuo Google Cloud
Il client può ottenere l'autorizzazione richiesta e accedere all'API
utilizzando codice simile al seguente:
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)
Tieni presente che SCOPE deve essere impostato come mostrato. Per informazioni su
YOUR_CLIENT_ID e
YOUR_CLIENT_SECRET, consulta
Creare ID client.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-09-04 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)."]]