Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Arquitetura do API Gateway
O API Gateway é um sistema de gestão de APIs que oferece gestão, monitorização e autenticação para as suas APIs. Os componentes que constituem o gateway da API incluem:
API Gateway: para gerir todos os aspetos de uma API implementada
Controlo de serviços: para aplicar regras de gestão de APIs
Service Management: para gerir configurações de APIs
CLI gcloud: para implementar e gerir as suas APIs
Google Cloud console: para registo, monitorização e partilha
Arquitetura
Segue-se um diagrama de alto nível dos principais componentes envolvidos no API Gateway:
Neste diagrama:
O fornecedor da API é responsável pela criação e implementação de uma API no API Gateway. Cada API é definida por um ficheiro escrito como uma especificação OpenAPI 2.0.
A especificação OpenAPI define o URL público do ponto final REST para a API, o serviço de back-end acedido pela API e quaisquer outras caraterísticas da API, como a autenticação, o formato de dados e as opções de resposta.
O cliente API faz um pedido REST a uma API alojada no API Gateway para aceder aos serviços de back-end. Um cliente API pode ser qualquer app capaz de fazer uma chamada REST, como um navegador, uma app para dispositivos móveis ou uma app Web.
O cliente da API só precisa de saber o URL da API, o verbo do pedido (como GET, PUT, POST, DELETE),
quaisquer requisitos de autenticação e o formato de quaisquer dados enviados ou recebidos da API.
O cliente da API não precisa de saber nada sobre a implementação de back-end. Na verdade, uma única API alojada no API Gateway pode ser configurada para aceder a diferentes backends com base nas informações transmitidas no pedido.
Componentes do API Gateway
API Gateway
O API Gateway oferece uma solução totalmente gerida e de pagamento por utilização para alojar as suas APIs. O Gateway da API oferece acesso seguro aos seus serviços de back-end através de uma API REST bem definida e consistente em todos os seus serviços, independentemente da implementação do serviço.
O API Gateway está integrado com o Google Cloud para que possa usar as mesmas ferramentas de desenvolvimento, monitorização, registo e rastreio que usa com qualquer outro produto Google Cloud .
Se estiver a estabelecer ligação a um serviço de back-end alojado fora do Google Cloud, pode continuar a tirar partido de todos os Google Cloud serviços, incluindo os serviços de autenticação e autorização usados para controlar o acesso às suas APIs.
Service Control API
A API Service Control aplica regras de gestão de APIs no tempo de execução, como a autenticação de chaves de API, a monitorização e o registo. O Service Control fornece os seguintes métodos:
Verificar: valida a autenticação e as chaves de API, e indica se uma chamada deve ser permitida
Comunicação: notifica os sistemas de registo para registo e monitorização
Service Management API
Usa a especificação OpenAPI para definir a sua API. Em seguida, usa a CLI gcloud para carregar a especificação OpenAPI para a gestão de serviços, o que cria a configuração da API. Outras tarefas relacionadas com a configuração também ocorrem aqui, como partilhar a sua API com outros programadores, ativar ou desativar a API em diferentes projetos e gerar chaves da API.
CLI gcloud
A CLI gcloud fornece a ferramenta de linhas de comando gcloud que pode usar para fazer chamadas a vários Google Cloud serviços. Usa a CLI do Google Cloud para carregar a sua especificação OpenAPI, que cria a configuração da API e, em seguida, para implementar a configuração da API no API Gateway.
Cloud Console
A Google Cloud consola é a interface gráfica do utilizador para a Google Cloud consola. Use a Google Cloud consola para expor os dados de monitorização e registo registados pelo Service Control, para configurar a autenticação e a autorização, e para os programadores gerarem chaves de API para chamar a API.
Processar um pedido de API
Numa configuração de API, existem dois tipos de pontos finais:
Ponto final da API: define o ponto final disponível publicamente que os clientes usam para consumir as suas APIs.
Ponto final de back-end: define o ponto final que a API usa para se ligar ao seu serviço de back-end. As definições de segurança, como o acesso HTTP ou HTTPS, são definidas pela implementação do serviço de back-end.
Os pedidos ao seu ponto final da API são transmitidos ao ponto final de back-end, incluindo todos os dados transmitidos como parte do pedido. As respostas do serviço de back-end, incluindo quaisquer dados devolvidos pelo serviço, são transmitidas de volta ao cliente.
Encaminhamento de pedidos
Quando é recebido um pedido:
O API Gateway cria um token de rastreio para o Cloud Trace.
O API Gateway faz corresponder o caminho dos pedidos recebidos com a API de destino. Depois de encontrar uma rota correspondente, o API Gateway executa os passos de autenticação para a API especificada.
Se a validação JWT for necessária, o API Gateway valida a autenticação através da chave pública adequada para o signatário e valida o campo de público-alvo no JWT. Se for necessária uma chave de API, o API Gateway chama a API Service Control para validar a chave.
O Service Control procura a chave para a validar e garante que o projeto associado à chave ativou a API. Se a chave não for válida ou o projeto não tiver ativado a API, a chamada é rejeitada e registada através da API Service Control.
Se o Service Control validar a chave com êxito, o pedido, juntamente com todos os cabeçalhos originais, mais um cabeçalho de validação JWT, se adequado, é encaminhado para o back-end.
Quando é recebida uma resposta do back-end, o API Gateway devolve a resposta ao autor da chamada e envia as informações de sincronização finais para o Trace. Os pontos de chamada são registados pela API Service Control, que, em seguida, escreve métricas e registos nos respetivos destinos.
[[["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-08-19 UTC."],[[["\u003cp\u003eAPI Gateway is a fully managed system for API management, providing a secure, consistent REST API for backend services and handling authentication, monitoring, and logging.\u003c/p\u003e\n"],["\u003cp\u003eThe API provider defines APIs using OpenAPI specs, and API clients access these APIs without needing to know the backend implementation, while the client is only required to know the URL and the format of the API.\u003c/p\u003e\n"],["\u003cp\u003eService Control API handles API management rules at runtime, including API key validation, logging, and monitoring through methods like Check and Report.\u003c/p\u003e\n"],["\u003cp\u003eService Management API manages API configurations, such as creating the API config, sharing the API, and enabling or disabling the API in projects.\u003c/p\u003e\n"],["\u003cp\u003eWhen an API request is received, API Gateway routes the request to the correct backend service after performing authentication and validation, then returns the backend's response to the client, while also logging the call and sending metrics.\u003c/p\u003e\n"]]],[],null,["# API Gateway Architecture\n========================\n\nAPI Gateway is an API management system that provides management, monitoring, and authentication for your APIs. The components that make up API Gateway include:\n\n- **API Gateway**: for managing all aspects of a deployed API\n- **Service Control**: for applying API management rules\n- **Service Management**: for managing API configurations\n- **gcloud CLI**: for deploying and managing your APIs\n- **Google Cloud console**: for logging, monitoring and sharing\n\nArchitecture\n------------\n\nThe following is a high level diagram of the major components involved in API Gateway:\n\nIn this diagram:\n\n- **The API provider** is responsible for creating and deploying an API on API Gateway. Each API is defined by a file written as an OpenAPI 2.0 spec.\n\n The OpenAPI spec defines the publicly facing URL of the REST endpoint for the API, the backend service accessed by the API, and any other characteristics of the API such as authentication, data format, and response options.\n- **The API client** makes a REST request to an API hosted on API Gateway to access backend services. An API client can be any app capable of making a REST call, such as a browser, mobile app, or web app.\n\n The API client only needs to know the URL of the API, the request verb (such as `GET`, `PUT`, `POST`, `DELETE`),\n any authentication requirements, and the format of any data sent to or received from the API.\n\n The API client does not need to know anything about the backend implementation. In fact, a single API hosted on API Gateway can be configured to access different backends based on information passed in the request.\n\nAPI Gateway components\n----------------------\n\n### API Gateway\n\nAPI Gateway provides a fully managed, pay-per-use solution for hosting your APIs. API Gateway provide secure access to your backend services through a well-defined REST API that is consistent across all of your services, regardless of the service implementation.\n\nAPI Gateway is integrated with Google Cloud so that you can use the same development, monitoring, logging, and trace tools that you use with any other Google Cloud product.\n\nIf you are connecting to a backend service hosted outside of Google Cloud, you can still take advantage of all Google Cloud services, including the authentication and authorization services used to control access to your APIs.\n\n### Service Control API\n\n[Service Control API](https://cloud.google.com/service-control/) applies API management rules at runtime, such as API key authentication, monitoring, and logging. Service Control provides the following methods:\n\n- **Check**: verifies authentication and API keys, and indicates whether a call should be permitted\n- **Report**: notifies the systems of record for logging and monitoring\n\n### Service Management API\n\nYou use the [OpenAPI specification](/endpoints/docs/openapi/openapi-overview) to define your API. You then use the gcloud CLI to upload the OpenAPI spec to Service Management, which creates the API config. Other configuration-related tasks also happen here, such as sharing your API with other developers, enabling or disabling the API in different projects, and generating API keys.\n\n### gcloud CLI\n\nThe [gcloud CLI](https://cloud.google.com/sdk/docs) provides the [gcloud](/sdk/gcloud/reference) command-line tool that you can use to make calls to various Google Cloud services. You use the Google Cloud CLI to upload your OpenAPI spec, which creates the API config, and then to deploy the API config to API Gateway.\n\n### Cloud console\n\n[Google Cloud console](https://console.cloud.google.com/) is the graphical user interface for Google Cloud console. Use the Google Cloud console to expose monitoring and logging data recorded by Service Control, to configure authentication and authorization, and for developers to generate API keys to call the API.\n\nHandling an API request\n-----------------------\n\nIn an API configuration, there are two types of endpoints:\n\n- **API endpoint**: defines the publicly available endpoint that clients use to consume your APIs.\n- **Backend endpoint**: defines the endpoint that the API uses to connect to your backend service. Security settings, such as HTTP or HTTPS access, are defined by the implementation of the backend service.\n\nRequests to your API endpoint are passed to the backend endpoint, including any data passed as part of the request. Responses from the backend service, including any data returned by the service, are passed back to the client.\n\n### Request routing\n\nWhen a request is received:\n\n1. API Gateway creates a trace token for Cloud Trace.\n\n2. API Gateway matches the path of the incoming requests with the target API. After finding a matching route, API Gateway performs any authentication steps for the specified API.\n\n3. If JWT validation is necessary, API Gateway validates the authentication using the appropriate public key for the signer, and validates the audience field in the JWT. If an API key is required, API Gateway calls the Service Control API to validate the key.\n\n4. Service Control looks up the key to validate it, and ensures that the project associated with the key has enabled the API. If the key isn't valid or the project hasn't enabled the API, the call is rejected and it is logged via the Service Control API.\n\n5. If Service Control successfully validates the key, the request along with all original headers, plus a JWT validation header, if appropriate, is forwarded to the backend.\n\n6. When a response is received from the backend, API Gateway returns the response to the caller and sends the final timing information to Trace. The call points are logged by the Service Control API, which then writes metrics and logs to their appropriate destinations.\n\nWhat's next\n-----------\n\n- [API Gateway Deployment Model](/api-gateway/docs/deployment-model)"]]