Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Como usar chaves de API
Esta página descreve como usar chaves de API no API Gateway.
Uma chave de API é uma string simples que identifica um projetoGoogle Cloud para fins de cota, faturamento e monitoramento. Um
desenvolvedor gera uma chave de API em um projeto no console do Google Cloud e
a incorpora em todas as chamadas para a API como um parâmetro de consulta ou em um cabeçalho de solicitação.
Se você especificar um requisito de chave de API na configuração da API,
o API Gateway vai usar a chave de API para procurar o projeto Google Cloud associado. O API Gateway rejeitará solicitações, a menos que
a chave de API tenha sido gerada no projeto Google Cloud ou em outros
Google Cloud em que a API foi ativada.
Para criar uma chave de API ou conferir as chaves já disponíveis no Google Cloud projeto, acesse a página APIs e serviços > Credenciais.
Para usar recursos do API Gateway, como
cotas, é possível transmitir uma chave
de API para que o API Gateway possa identificar o projeto Google Cloud
ao qual o aplicativo cliente está associado.
Sobre a autenticação de chave de API para o gateway de API
Se você estiver usando uma chave de API para autenticação, primeiro ative o suporte à chave de API no seu serviço.
Digite este comando:
gcloud services enable MANAGED_SERVICE_NAME
O MANAGED_SERVICE_NAME especifica o nome do serviço gerenciado criado quando você implantou a API. Esse nome está na coluna "Serviço gerenciado" da API na página de destino das APIs no console. Outra opção é encontrar esse nome na propriedade Managed service ao usar o comando gcloud api-gateway apis describe.
As chaves de API são irrestritas por padrão. As chaves irrestritas não são seguras porque
podem ser usadas por qualquer pessoa e de qualquer lugar. Recomendamos que você adicione restrições de API sempre que possível.
Essas restrições especificam quais APIs podem ser chamadas com a chave de API. Todas as chaves de API usadas por aplicativos de produção devem ter restrições de API.
Para adicionar restrições de API:
Encontre o título da API, conforme indicado na configuração da API. No exemplo abaixo, o título da API é My Example Config:
# openapi.yamlswagger:'2.0'info:title:My Example Configdescription:Sample API on API Gatewayversion:1.0.0...
No console do Google Cloud, acesse a página APIs e serviços > Credenciais.
Selecione o nome da chave de API que você quer usar.
Na seção Restrições de API da página de detalhes da chave de API, clique em Restringir chave.
Selecione a API que sua chave de API vai usar para acessar na lista suspensa de APIs disponíveis. Por exemplo, se
usar a configuração de exemplo acima, selecione My Example Config.
Clique em Salvar.
Sua restrição vai entrar em vigor em alguns instantes.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-09-03 UTC."],[[["\u003cp\u003eAPI keys are simple strings used to identify a Google Cloud project for quota, billing, and monitoring in API Gateway.\u003c/p\u003e\n"],["\u003cp\u003eAPI Gateway requires API keys generated within your Google Cloud project, or projects where your API is enabled, to authorize requests.\u003c/p\u003e\n"],["\u003cp\u003eWhile useful for features like quotas, API keys are vulnerable to man-in-the-middle attacks and should not be the sole form of authentication for sensitive data.\u003c/p\u003e\n"],["\u003cp\u003eEnabling API key support for a service requires using the \u003ccode\u003egcloud services enable MANAGED_SERVICE_NAME\u003c/code\u003e command, specifying the managed service's name.\u003c/p\u003e\n"],["\u003cp\u003eFor security, API keys should be restricted to specific APIs through the Google Cloud console's \u003cstrong\u003eAPIs & Services > Credentials\u003c/strong\u003e page, ensuring they are not used by unauthorized parties.\u003c/p\u003e\n"]]],[],null,["# Using API Keys\n==============\n\nThis page describes how to utilize API keys in API Gateway.\n\nAn API key is a simple string that identifies a\nGoogle Cloud project for quota, billing, and monitoring purposes. A\ndeveloper generates an API key in a project in the Google Cloud console and\nembeds that key in every call to your API as a query parameter or in a request header.\n\nIf you specify an API key requirement in your API config,\nAPI Gateway uses the API key to look up the associated Google Cloud project. API Gateway rejects requests unless\nthe API key was generated in your Google Cloud project or within other\nGoogle Cloud projects in which your API has been enabled.\n| **Note:** Unlike credentials that use short-lived tokens or signed requests, API keys function as part of the API request. As a result, API keys are vulnerable to [man-in-the-middle attacks](https://wikipedia.org/wiki/Man-in-the-middle_attack) and may not be as secure as other authentication credentials. You can use API keys in addition to one of the other [supported forms of authentication](/api-gateway/docs/authentication-method), but we do not recommend using *only* API keys when API calls contain sensitive data.\n\nTo create an API key, or view API keys already available within your Google Cloud project, go to the **APIs \\& Services** \\\u003e **Credentials** page.\n\n[Go to Credentials](https://console.cloud.google.com/apis/credentials)\n\n\u003cbr /\u003e\n\n### Use case\n\nTo use API Gateway features such as\n[quotas](/api-gateway/docs/quotas-overview), you can pass in an API\nkey so that API Gateway can identify the Google Cloud project\nthat the client application is associated with.\n\n### About API key authentication for API Gateway\n\nIf you are using an API key for authentication, you must first enable API key support\nfor your service.\n\nEnter the following command: \n\n```\ngcloud services enable MANAGED_SERVICE_NAME\n```\n\n\u003cbr /\u003e\n\nThe \u003cvar translate=\"no\"\u003eMANAGED_SERVICE_NAME\u003c/var\u003e specifies the name of the managed service created when you deployed the API. You can find this name in the Managed Service column for your API on the APIs landing page in the console. Alternatively, you can find this name in the `Managed service` property when using the `gcloud api-gateway apis describe` command.\n\nFor example: \n\n```\ngcloud services enable my-api-a12bcd345e67f89g0h.apigateway.my-project.cloud.goog\n```\n\n### Restricting API keys\n\nAPI keys are unrestricted by default. Unrestricted keys are insecure because\nthey can be used by anyone from anywhere. We recommend that you add *API restrictions* where possible.\nAPI restrictions specify which APIs can be called using the API key. All API keys used by production applications should have API restrictions.\n\nTo add API restrictions:\n\n1. Find the title of the API as noted in your API Config. In the following example, the API title is `My Example Config`:\n\n ```yaml\n # openapi.yaml\n swagger: '2.0'\n info:\n title: My Example Config\n description: Sample API on API Gateway\n version: 1.0.0\n ...\n ```\n2. In the Google Cloud console, go to the **APIs \\& Services** \\\u003e **Credentials** page.\n\n [Go to Credentials](https://console.cloud.google.com/apis/credentials)\n\n \u003cbr /\u003e\n\n3. Select the name of the API key you wish to use for your API.\n\n4. In the **API restrictions** section of the API key detail page, click **Restrict key**.\n\n5. Select the API that your API key will be used to access from the dropdown list of available APIs. For example, if\n using the example config above, select `My Example Config`.\n\n6. Click **Save**.\n\nYour restriction should take effect momentarily."]]