Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Pour accéder à une API Cloud Endpoints à partir d'un client Python, vous devez utiliser la bibliothèque cliente des API Google pour Python.
Si l'API ne nécessite aucune authentification, votre client peut accéder à l'API comme indiqué dans l'exemple de code suivant :
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()
Dans cet exemple :
api_root est l'URL racine de l'interface avec laquelle vos méthodes d'API sont diffusées.
L'URL est généralement https://YOUR_PROJECT_ID.appspot.com/_ah/api, où YOUR_PROJECT_ID représente votre Google Cloud
api correspond au nom de l'API.
version désigne la version de l'API backend.
Accéder à une API nécessitant une authentification
Votre client peut obtenir l'autorisation requise et accéder à l'API à l'aide d'un code semblable à celui-ci :
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)
Notez que SCOPE doit être défini comme indiqué ici. Pour en savoir plus sur YOUR_CLIENT_ID et YOUR_CLIENT_SECRET, consultez la page Créer des ID client.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/04 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 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)."]]