Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Arquitetura do gateway de API
A API Gateway é um sistema de gerenciamento de APIs que fornece gerenciamento, monitoramento e autenticação para suas APIs. Os componentes que compõem o gateway de API incluem
Gateway de API: para gerenciar todos os aspectos de uma API implantadas
Service Control: para aplicar regras de gerenciamento de APIs;
Service Management: para gerenciar as configurações da API
CLI gcloud: para implantar e gerenciar APIs
Google Cloud console: para criação de registros, monitoramento e compartilhamento.
Arquitetura
Confira abaixo um diagrama de alto nível dos principais componentes envolvidos no gateway de API:
Neste diagrama:
O provedor da API é responsável pela criação e implantação de uma API no gateway de API. Cada API é definida por um arquivo escrito como uma especificação OpenAPI 2.0.
A especificação OpenAPI define o URL público do endpoint REST da API, o serviço de back-end acessado pela API e outras características da API, como opções de autenticação, formato de dados e resposta.
O cliente da API faz uma solicitação REST para uma API hospedada no gateway de API para acessar serviços de back-end. Um cliente de API pode ser qualquer app capaz de fazer uma chamada REST, como um navegador, um app para dispositivos móveis ou um app da Web.
O cliente da API só precisa saber o URL da API, o verbo "request" (como GET, PUT, POST, DELETE), todos os requisitos de autenticação e o formato de quaisquer dados enviados ou recebidos da API.
O cliente da API não precisa saber nada sobre a implementação de back-end. Na verdade, uma única API hospedada no gateway de API pode ser configurada para acessar back-ends diferentes com base nas informações transmitidas na solicitação.
Componentes do gateway de API
API Gateway
A API Gateway oferece uma solução de pagamento por uso totalmente gerenciada para hospedar suas APIs Forneça acesso seguro aos serviços de back-end por meio de uma API REST bem definida, consistente em todos os seus serviços, independentemente da implementação.
A API Gateway é integrada ao Google Cloud para que você possa usar as mesmas ferramentas de desenvolvimento, monitoramento, geração de registros e rastreamento que usa com qualquer outro produto do Google Cloud .
Se você estiver se conectando a um serviço de back-end hospedado fora do Google Cloud, ainda poderá aproveitar todos os serviços do Google Cloud , incluindo os serviços de autenticação e autorização usados para controlar o acesso às suas APIs.
API Service Control
A API Service Control aplica regras de gerenciamento de API no ambiente de execução, como autenticação de chave de API, monitoramento e geração de registros. Ele fornece os seguintes métodos:
Verificação: confere as chaves de autenticação e de API e indica se uma chamada é permitida.
Relatório: notifica os sistemas de registro para geração de registros e monitoramento.
Service Management API
Use a especificação OpenAPI para definir a API. Em seguida, use a CLI gcloud para fazer upload da especificação OpenAPI para o Service Management, que cria a configuração da API. No Service Management, você também realiza outras tarefas relacionadas à configuração. Por exemplo, compartilhar a API com outros desenvolvedores, ativá-la ou desativá-la em diferentes projetos e gerar chaves de API.
CLI da gcloud
A CLI gcloud fornece a ferramenta de linha de comando gcloud, que pode ser usada para fazer chamadas para vários serviços do Google Cloud . Use a Google Cloud CLI para fazer upload da especificação OpenAPI, que cria a configuração da API, e depois implante a configuração da API no gateway de API.
Console do Cloud
O Google Cloud console é a interface gráfica do usuário para o Google Cloud console. Use o console Google Cloud para expor os dados de monitoramento e geração de registros gravados pelo Service Control, configurar a autenticação e a autorização e permitir que os desenvolvedores gerem chaves de API para chamar a API.
Como processar uma solicitação de AP
Em uma configuração de proxy de API, há dois tipos de endpoints:
Endpoint da API: define o endpoint disponível ao público que os clientes usam para consumir suas APIs.
Endpoint de back-end: define o endpoint usado pela API para se conectar ao seu serviço de back-end. As configurações de segurança, como o acesso HTTP ou HTTPS, são definidas pela implementação do serviço de back-end.
As solicitações para o endpoint da API são transmitidas para o endpoint de back-end, incluindo todos os dados transmitidos como parte da solicitação. As respostas do serviço de back-end, incluindo todos os dados retornados pelo serviço, são transmitidas para o cliente.
Roteamento de solicitações
Quando uma solicitação é recebida:
O gateway de API cria um token de trace para o Cloud Trace.
O gateway de API corresponde ao caminho das solicitações recebidas com a API de destino. Após encontrar uma rota correspondente, a API Gateway executa todas as etapas de autenticação para a API especificada.
Se for necessária a validação do JWT, o ESP validará a autenticação usando a chave pública apropriada do signatário e confirmará o campo de público no JWT. Se for necessária uma chave de API, o ESP chamará a API Service Control para validar a chave.
O Service Control procura a chave para validá-la e garante que o projeto associado a ela tenha ativado a API. Se a chave for inválida ou o projeto não tiver ativado a API, a chamada será recusada e registrada por meio da API Service Control.
Se o Service Control validar a chave, a solicitação será encaminhada para o back-end com todos os cabeçalhos originais e o de validação do JWT, se apropriado.
Quando chega uma resposta do back-end, o ESP a retorna para o autor da chamada e envia as informações de duração finais para o Trace. Os pontos de chamada são registrados pela API Service Control, que grava métricas e as registra nos destinos apropriados.
[[["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-08 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)"]]