您可以使用 API 金鑰,限制特定 API 方法或 API 中所有方法的存取權。本頁面說明如何限制只有具 API 金鑰的用戶端可存取 API,並示範 API 金鑰的建立方式。
如果您將 API 設定為必須要有 API 金鑰才能存取,除非要求已具備您在專案中產生的金鑰,或是具備開發人員在其他專案中產生的金鑰 (必須已獲您授予 API 使用權限),否則針對受保護的方法、類別或 API 提出的要求都會遭到拒絕。系統不會記錄建立該 API 金鑰的專案,也不會在要求標頭新增該專案。不過,您可以如篩選特定的消費者專案一節所述,在「Endpoints Services」(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。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["難以理解","hardToUnderstand","thumb-down"],["資訊或程式碼範例有誤","incorrectInformationOrSampleCode","thumb-down"],["缺少我需要的資訊/範例","missingTheInformationSamplesINeed","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間: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)"]]