您可以使用 API 密钥来限制对 API 中的特定 API 方法或所有方法的访问。本页面介绍了如何设置限制以只允许拥有 API 密钥的客户端访问 API,同时还演示了如何创建 API 密钥。
如果您在 API 中设置了 API 密钥要求,则对受保护的方法、类或 API 的请求将被拒绝,除非这些请求具有在您的项目或其他项目(属于已获授权可启用您的 API 的开发者)中生成的密钥。系统不会记录创建 API 密钥时所用的项目,也不会将该项目添加到请求标头中。不过,您可以在 Endpoints 服务页面上查看与客户端关联的 Google Cloud 项目(请参阅针对特定使用方项目进行过滤)。
如果要求对特定 API 方法的所有调用都必须提供 API 密钥,请将 api_key_required=True 添加到 API 方法修饰器。
例如:
endpoints.method(# This method takes an Echo message.ECHO_RESOURCE,# This method returns an Echo message.EchoResponse,path='echo',http_method='POST',name='echo_api_key',api_key_required=True)defecho_api_key(self,request):output_content='\n'.join([request.content]*request.n)returnEchoResponse(content=output_content)
移除对某个方法的 API 密钥限制
要为某个 API 或 API 方法停用 API 密钥验证,请从相应 API 或方法的装饰器或注释中移除 api_key_required=True (Python) 或 apiKeyRequired = AnnotationBoolean.TRUE (Java),然后重新编译并重新部署。
使用 API 密钥调用 API
如果 API 或 API 方法要求提供 API 密钥,请使用名为 key 的查询参数提供密钥,如以下 cURL 示例所示:
如果您需要区分 API 的各个调用者,并且每个调用者都有自己的 Google Cloud 项目,您可以向主账号授予在其自己的 Google Cloud 项目中启用 API 的权限。这样,您的 API 用户就可以创建自己的 API 密钥,以用于您的 API。
例如,假设您的团队创建了一个 API,供公司里的各种客户端程序内部使用,并且每个客户端程序都有各自的 Google Cloud项目。如需区分 API 的调用者,您必须在不同的 Google Cloud 项目中为每个调用者创建 API 密钥。您可以向同事授予在与相应客户端程序关联的 Google Cloud 项目中启用 API 的权限。
要允许用户创建自己的 API 密钥,请执行以下操作:
在配置了您的 API 的 Google Cloud 项目中,向每个用户授予启用您的 API 的权限。
如果您需要区分 API 的调用者,且并非所有调用者都有 Google Cloud 项目,您可以为每个调用者单独创建一个 Google Cloud 项目和 API 密钥。在创建项目之前,请考虑好项目名称,以便轻松识别与该项目关联的调用者。
例如,假设您的 API 有外部客户,并且您不知道调用您的 API 的客户端程序是如何创建的。也许有些客户会使用 Google Cloud 服务并且拥有 Google Cloud 项目,而有些客户则可能并非如此。如需区分调用者,您必须为每个调用者单独创建一个 Google Cloud 项目和 API 密钥。
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["很难理解","hardToUnderstand","thumb-down"],["信息或示例代码不正确","incorrectInformationOrSampleCode","thumb-down"],["没有我需要的信息/示例","missingTheInformationSamplesINeed","thumb-down"],["翻译问题","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2025-09-04。"],[[["\u003cp\u003eAPI keys can restrict access to specific API methods or an entire API, ensuring that only clients with a valid key can make requests.\u003c/p\u003e\n"],["\u003cp\u003eTo require an API key for all calls to an API or a specific API method, you must use the \u003ccode\u003eapi_key_required=True\u003c/code\u003e setting in the API or method decorator respectively, which will reject calls without a key.\u003c/p\u003e\n"],["\u003cp\u003eThe Google Cloud project associated with an API key is not logged in the request header, however, you can find the client's project in the Endpoints Services page by filtering for the consumer project.\u003c/p\u003e\n"],["\u003cp\u003eThe method to implement API keys for your project depends on whether you need to differentiate between API callers, whether they have their own projects, and whether you need to set up different API key restrictions.\u003c/p\u003e\n"],["\u003cp\u003eWhen calling an API that requires a key, you must supply the API key as a query parameter named \u003ccode\u003ekey\u003c/code\u003e in your request URL, along with the host name, API name, and API version.\u003c/p\u003e\n"]]],[],null,["# Restricting API access with API keys\n\nYou can use [API keys](/endpoints/docs/frameworks/python/when-why-api-key) to restrict access to specific API methods or all methods in an API. This page describes how to restrict API access to those clients that have an API key and also shows how to create an API key.\n\n\u003cbr /\u003e\n\nIf you set an API key requirement in your API, requests to the protected method,\nclass, or API are rejected unless they have a key generated in your project or\nwithin other projects belonging to developers with whom you have\n[granted access to enable your API](/endpoints/docs/frameworks/control-api-callers). The\nproject that the API key was created in is not logged and is not added to the\nrequest header. You can, however, view the Google Cloud project that a\nclient is associated with on the **Endpoints Services** page, as described in\n[Filter for a specific consumer project](/endpoints/docs/frameworks/monitoring-your-api#filter_for_a_specific_consumer_project).\n\nFor information on which Google Cloud project an API key should be created in, see\n[Sharing APIs protected by API key](#sharing_apis_protected_by_api_key).\n\nRestricting access to all API methods\n-------------------------------------\n\nTo require an API key for all calls into the API, add\n`api_key_required=True` to your\n[API decorator](/endpoints/docs/frameworks/python/decorators-reference#defining_the_api_endpointsapi).\nFor example: \n\n @endpoints.api(name='echo', version='v1', api_key_required=True)\n class EchoApi(remote.Service):\n #...\n\nRestricting access to specific API methods\n------------------------------------------\n\nTo require an API key for all calls to a specific API method, add\n`api_key_required=True` to your\n[API method decorator](/endpoints/docs/frameworks/python/decorators-reference#defining_an_api_method_endpointsmethod).\nFor example: \n\n endpoints.method(\n # This method takes an Echo message.\n ECHO_RESOURCE,\n # This method returns an Echo message.\n EchoResponse,\n path='echo',\n http_method='POST',\n name='echo_api_key',\n api_key_required=True)\n def echo_api_key(self, request):\n output_content = '\\n'.join([request.content] * request.n)\n return EchoResponse(content=output_content)\n\nRemoving API key restriction for a method\n-----------------------------------------\n\nTo turn off API key validation for an API or API method, remove\n`api_key_required=True` (Python) or `apiKeyRequired = AnnotationBoolean.TRUE`\n(Java) from your API or method decorator or annotation. Then recompile and\nre-deploy.\n\nCalling an API using an API key\n-------------------------------\n\nIf an API or API method requires an API key, supply the key using a query\nparameter named `key`, as shown in this cURL example: \n\n curl \\\n -H \"Content-Type: application/json\" \\\n -X POST \\\n -d '{\"message\": \"echo\"}' \\\n \"${HOST}/_ah/api/echo/v1/echo_api_key?key=${API_KEY}\"\n\nwhere `HOST` and `API_KEY` are variables containing your API host\nname and API key, respectively. Replace `echo` with the name of your API, and\n`v1` with the version of your API.\n\nSharing APIs protected by API key\n---------------------------------\n\nAPI keys are associated with the Google Cloud project in which\nthey have been created. If you have decided to require an API key for\nyour API, the Google Cloud project that the API key gets created in depends on\nthe answers to the following questions:\n\n- Do you need to distinguish between the callers of your API so that you can use Endpoints features such as [quotas](/endpoints/docs/frameworks/quotas-overview)?\n- Do all the callers of your API have their own Google Cloud projects?\n- Do you need to set up different [API key\n restrictions](/docs/authentication/api-keys#api_key_restrictions)?\n\nYou can use the following decision tree as a guide for deciding which Google Cloud\nproject to create the API key in.\n\n### Grant permission to enable the API\n\nWhen you need to distinguish between callers of your API, and each caller\nhas their own Google Cloud project, you can grant principals permission to enable the API in\ntheir own Google Cloud project. This way, users of your API can create their own API key for\nuse with your API.\n\nFor example, suppose your team has created an API for internal use by various\nclient programs in your company, and each client program has their own Google Cloud\nproject. To distinguish between callers of your API, the API key for each caller\nmust be created in a different Google Cloud project. You can grant your coworkers\npermission to enable the API in the Google Cloud project that the client program is\nassociated with.\n\nTo let users create their own API key:\n\n1. In the Google Cloud project in which your API is configured, grant each user the [permission to enable your\n API](/endpoints/docs/frameworks/control-api-callers).\n2. Contact the users, and let them know that they can [enable your API](/endpoints/docs/frameworks/enable-api) in their own Google Cloud project and [create an API key](/docs/authentication/api-keys#creating_an_api_key).\n\n### Create a separate Google Cloud project for each caller\n\nWhen you need to distinguish between callers of your API, and not all of the\ncallers have Google Cloud projects, you can create a separate Google Cloud project and\nAPI key for each caller. Before creating the projects, give some thought to the project\nnames so that you can easily identify the caller associated with the project.\n\nFor example, suppose you have external customers of your API, and you\nhave no idea how the client programs that call your API were created. Perhaps\nsome of the clients use Google Cloud services and have a Google Cloud project, and\nperhaps some don't. To distinguish between the callers, you must create a separate\nGoogle Cloud project and API key for each caller.\n\nTo create a separate Google Cloud project and API key for each caller:\n\n1. Create a separate project for each caller.\n2. In each project, [enable your API](/endpoints/docs/frameworks/enable-api) and [create an API key](/docs/authentication/api-keys#creating_an_api_key).\n3. Give the API key to each caller.\n\n### Create an API key for each caller\n\nWhen you don't need to distinguish between callers of your API, but you want\nto add API key restrictions, you can create a separate API key for each caller\nin the same project.\n\nTo create an API key for each caller in the same project:\n\n1. In either the project that your API is configured in, or a project that your [API is enabled in](/endpoints/docs/frameworks/enable-api), create an API key for each customer that has the [API key\n restrictions](/docs/authentication/api-keys#api_key_restrictions) that you need.\n2. Give the API key to each caller.\n\n### Create one API key for all callers\n\nWhen you don't need to distinguish between callers of your API, and you don't need to add API\nrestrictions, but you still want to require an API key\n(to prevent anonymous access, for example), you can create one API key for\nall callers to use.\nTo create one API key for all callers:\n\n1. In either the project that your API is configured in, or a project that your [API is enabled in](/endpoints/docs/frameworks/enable-api), create an API key for all callers that has the [API key restrictions](/docs/authentication/api-keys#api_key_restrictions) that you need.\n2. Give the same API key to every caller.\n\nWhat's next\n-----------\n\n- [Securing an API key](/docs/authentication/api-keys#securing_an_api_key)"]]