Antipadrão: invocar chamadas da API Apigee de um proxy de API
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Esta é a documentação da Apigee e da Apigee híbrida.
Confira a documentação da Apigee Edge.
A Apigee tem um utilitário avançado chamado API da Apigee, que oferece serviços como:
Implantar ou remover proxies de API
Configurar hosts virtuais, keystores e truststores etc.
Criar, excluir e atualizar entidades, como mapas de chave-valor (KVMs), produtos de API, apps
para desenvolvedores, desenvolvedores, chaves de consumidor e assim por diante;
Recuperação de informações sobre essas entidades
Esses serviços podem ser acessados por um componente chamado servidor de gerenciamento na
plataforma Apigee. Eles também podem ser invocados facilmente com a ajuda de chamadas simples da
API.
Às vezes, podemos precisar usar um ou mais desses serviços dos proxies de API no ambiente de execução. Isso ocorre
porque entidades como KVMs, tokens de acesso OAuth, produtos de API, aplicativospara desenvolvedores, desenvolvedores, chaves do consumidor e assim por diante contêm informações úteis na forma de pares de chave-valor, atributos
personalizados ou como parte do perfil.
Por exemplo, é possível armazenar as seguintes informações em KeyValueMap para torná-la mais segura e
acessível no ambiente de execução:
URLs de destino de back-end
Propriedades de ambiente
Credenciais de segurança de sistemas de terceiros ou de back-end
Da mesma forma, pode querer obter a lista de produtos de API ou o endereço de e-mail do desenvolvedor no tempo de execução.
Essas informações estarão disponíveis como parte do perfil dos apps para desenvolvedores.
Todas essas informações podem ser usadas efetivamente no ambiente de execução para permitir comportamento dinâmico em políticas
ou código personalizado na Apigee.
Antipadrão
As APIs da Apigee são preferenciais e úteis para tarefas administrativas e não devem ser usadas para
executar nenhuma lógica de ambiente de execução no fluxo de proxies da API. Isso ocorre pelos seguintes motivos:
O uso das APIs da Apigee para acessar informações sobre entidades como KVMs, tokens
de acesso OAuth ou para qualquer outra finalidade dos proxies de API leva à dependência dos servidores de
gerenciamento.
Os servidores de gerenciamento não fazem parte dos componentes do ambiente de execução da Apigee e, portanto, podem não estar
altamente disponíveis.
Os servidores de gerenciamento também não podem ser provisionados dentro da mesma rede ou data center e
portanto, podem introduzir latências de rede no ambiente de execução.
As entradas nos servidores de gerenciamento são armazenadas em cache por um período maior. Portanto, talvez você
não consiga ver os dados mais recentes imediatamente nos proxies da API se executar gravações e leituras em um
curto período.
Aumento dos saltos de rede no tempo de execução
Na amostra de código abaixo, a chamada da API Apigee é feita com o código JavaScript personalizado para
recuperar as informações da KVM:
Se o servidor de gerenciamento estiver indisponível, haverá falha no código JavaScript que invoca a chamada da
API Apigee. Isso fará com que a solicitação da API falhe.
Impacto
Apresenta dependência adicional nos servidores de gerenciamento durante o ambiente de execução. Qualquer falha nos
servidores de gerenciamento afetará as chamadas de API.
As credenciais do usuário para APIs da Apigee precisam ser armazenadas localmente ou em algum repositório seguro,
como um KVM criptografado.
Implicações de desempenho, relacionadas à invocação do serviço de gerenciamento pela rede.
Pode não exibir os valores atualizados imediatamente devido à expiração mais longa do cache nos servidores de
gerenciamento.
Prática recomendada
Há maneiras mais eficientes de recuperar informações de entidades como KVMs, produtos
de API, aplicativos para desenvolvedores, desenvolvedores, chaves de consumidor e assim por diante no tempo de execução. Veja alguns exemplos:
Use uma política KeyValueMapOperations para acessar informações de KVMs. Este é um código de amostra
que mostra como recuperar informações da KVM:
Para acessar informações sobre produtos de API, apps para desenvolvedores, desenvolvedores, chaves de consumidor e assim por diante
no proxy da API, siga um destes procedimentos:
Se o fluxo do proxy de API tiver uma política VerifyAPIKey, você poderá acessar as informações
usando as variáveis de fluxo preenchidas como parte dessa política. Veja um código de amostra que mostra
como recuperar o nome e as informações created_by de um app para desenvolvedores usando JavaScript:
<!--/antipatterns/examples/2-7.xml-->
print("Application Name ",context.getVariable(""verifyapikey.VerifyAPIKey.app.name"));print("Createdby:", context.getVariable("verifyapikey.VerifyAPIKey.app.created_by"));
Se o fluxo do proxy da API não tiver uma política VerifyAPIKey, você poderá acessar os
perfis de produtos, aplicativos de desenvolvedor e assim por diante usando as políticas AccessEntity e
ExtractVariables:
[[["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\u003eThe Apigee API is designed for administrative tasks and should not be used for runtime logic within API proxies, as it creates dependency on the Management Servers.\u003c/p\u003e\n"],["\u003cp\u003eRelying on Apigee APIs at runtime can cause performance issues and introduce network latencies because Management Servers are not part of the runtime components and may not be in the same network or data center.\u003c/p\u003e\n"],["\u003cp\u003eDirect calls to Management Servers can lead to outdated data being retrieved by API proxies due to longer caching periods, affecting data accuracy.\u003c/p\u003e\n"],["\u003cp\u003eFor accessing information at runtime, it is more effective to use policies like \u003ccode\u003eKeyValueMapOperations\u003c/code\u003e for KVM data or flow variables from the \u003ccode\u003eVerifyAPIKey\u003c/code\u003e policy for API products and developer app information, instead of calling the Apigee API.\u003c/p\u003e\n"],["\u003cp\u003eIf \u003ccode\u003eVerifyAPIKey\u003c/code\u003e policy is not in use, \u003ccode\u003eAccessEntity\u003c/code\u003e and \u003ccode\u003eExtractVariables\u003c/code\u003e policies are preferred for retrieving profiles of entities like developer apps during runtime, ensuring efficient access to needed information.\u003c/p\u003e\n"]]],[],null,["*You're viewing **Apigee** and **Apigee hybrid** documentation.\nView [Apigee Edge](https://docs.apigee.com/api-platform/antipatterns/invoking-management) documentation.*\n\nApigee has a powerful utility called the [Apigee API](/apigee/docs/reference/apis/apigee/rest) which offers services such as:\n\n- Deploying or undeploying API proxies\n- Configuring virtual hosts, keystores and truststores, and so on\n- Creating, deleting and updating entities such as key value maps (KVMs), API products, developer apps, developers, consumer keys, and so on\n- Retrieving information about these entities\n\nThese services are made accessible through a component called *Management Server* in the\nApigee platform. These services can be invoked easily with the help of simple API\ncalls.\n\nSometimes we may need to use one or more of these services from API proxies at runtime. This is\nbecause the entities such as KVMs, OAuth access tokens, API products, developer apps,\ndevelopers, consumer keys, and so on contain useful information in the form of key-value pairs, custom\nattributes or as part of its profile.\n\nFor instance, you can store the following information in a KVM to make it more secure and\naccessible at runtime:\n\n- Back-end target URLs\n- Environment properties\n- Security credentials of backend or third party systems\n\nSimilarly, you may want to get the list of API products or the developer's email address at runtime.\nThis information will be available as part of the developer apps profile.\n\nAll this information can be effectively used at runtime to enable dynamic behaviour in policies\nor custom code within Apigee.\n\nAntipattern\n\nThe Apigee APIs are preferred and useful for administrative tasks and should not be used for\nperforming any runtime logic in API proxies flow. This is because:\n\n- Using Apigee APIs to access information about the entities such as KVMs, OAuth access tokens or for any other purpose from API proxies leads to dependency on Management Servers.\n- Management Servers are not a part of Apigee runtime components and therefore, they may not be highly available.\n- Management Servers also may not be provisioned within the same network or data center and may therefore introduce network latencies at runtime.\n- The entries in the Management Servers are cached for a longer period of time, so you may not be able to see the latest data immediately in the API proxies if you perform writes and reads in a short period of time.\n- Increases network hops at runtime.\n\nIn the code sample below, the Apigee API call is made via the custom JavaScript code to\nretrieve the information from the KVM: \n\n```gdscript\nvar response = httpClient.send('https://apigee.googleapis.com/v1/organizations/$ORG/environments/$ENV/keyvaluemaps')\n```\n\nIf the Management Server is unavailable, then the JavaScript code invoking the Apigee API\ncall fails. This subsequently causes the API request to fail.\n\nImpact\n\n- Introduces additional dependency on Management Servers during runtime. Any failure in Management Servers will affect the API calls.\n- User credentials for Apigee APIs need to be stored either locally or in some secure store such as an encrypted KVM.\n- Performance implications owing to invoking the management service over the network.\n- May not see the updated values immediately due to longer cache expiration in Management Servers.\n\nBest practice\n\nThere are more effective ways of retrieving information from entities such as KVMs, API\nproducts, developer apps, developers, consumer keys, and so on at runtime. Here are a few examples:\n\n- Use a [KeyValueMapOperations policy](/apigee/docs/api-platform/reference/policies/key-value-map-operations-policy) to access information from KVMs. Here's sample code that shows how to retrieve information from the KVM: \n\n ```verilog\n \u003c!-- /antipatterns/examples/2-6.xml --\u003e\n \u003cKeyValueMapOperations mapIdentifier=\"urlMap\" async=\"false\"\n continueOnError=\"false\" enabled=\"true\" name=\"GetURLKVM\"\u003e\n \u003cDisplayName\u003eGetURLKVM\u003c/DisplayName\u003e\n \u003cExpiryTimeInSecs\u003e86400\u003c/ExpiryTimeInSecs\u003e\n \u003cScope\u003eenvironment\u003c/Scope\u003e\n \u003cGet assignTo=\"urlHosti\" index=\"2\"\u003e\n \u003cKey\u003e\n \u003cParameter\u003eurlHost_1\u003c/Parameter\u003e\n \u003c/Key\u003e\n \u003c/Get\u003e\n \u003c/KeyValueMapOperations\u003e\n ```\n- To access information about API products, developer apps, developers, consumer keys, and so on in the API proxy, you can do either of the following:\n - If your API Proxy flow has a [VerifyAPIKey policy](/apigee/docs/api-platform/reference/policies/verify-api-key-policy), then you can access the information using the flow variables populated as part of this policy. Here is sample code that shows how to retrieve the name and created_by information of a Developer App using JavaScript: \n\n ```css+lasso\n \u003c!-- /antipatterns/examples/2-7.xml --\u003e\n print(\"Application Name \", context.getVariable(\"\"verifyapikey. VerifyAPIKey.app.name\"));\n print(\"Created by:\", context.getVariable(\"verifyapikey. VerifyAPIKey.app.created_by\"));\n ```\n - If your API Proxy flow doesn't have a [VerifyAPIKey policy](/apigee/docs/api-platform/reference/policies/verify-api-key-policy), then you can access the profiles of API products, developer apps, and so on using the `AccessEntity` and `ExtractVariables` policies:\n 1. Retrieve the profile of developer app with the [AccessEntity policy](/apigee/docs/api-platform/reference/policies/access-entity-policy): \n\n ```carbon\n \u003c!-- /antipatterns/examples/2-8.xml --\u003e\n \u003c?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?\u003e\n \u003cAccessEntity async=\"false\" continueOnError=\"false\" enabled=\"true\" name=\"GetDeveloperApp\"\u003e\n \u003cDisplayName\u003eGetDeveloperApp\u003c/DisplayName\u003e\n \u003cEntityType value=\"app\"\u003e\u003c/EntityType\u003e\n \u003cEntityIdentifier ref=\"developer.app.name\" type=\"appname\"/\u003e\n \u003cSecondaryIdentifier ref=\"developer.id\" type=\"developerid\"/\u003e\n \u003c/AccessEntity\u003e\n ```\n 2. Extract the `appId` from developer app with the [ExtractVariables policy](/apigee/docs/api-platform/reference/policies/extract-variables-policy): \n\n ```gdscript\n \u003c!-- /antipatterns/examples/2-9.xml --\u003e\n \u003cExtractVariables name=\"Extract-Developer App-Info\"\u003e\n \u003c!--\n The source element points to the variable populated by AccessEntity policy.\n The format is \u003cpolicy-type\u003e.\u003cpolicy-name\u003e\n In this case, the variable contains the whole developer profile.\n --\u003e\n \u003cSource\u003eAccessEntity.GetDeveloperApp\"\u003c/Source\u003e\n \u003cVariablePrefix\u003edeveloperapp\u003c/VariablePrefix\u003e\n \u003cXMLPayload\u003e\n \u003cVariable name=\"appld\" type=\"string\"\u003e\n \u003c!-- You parse elements from the developer profile using XPath. --\u003e\n \u003cXPath\u003e/App/AppId\u003c/XPath\u003e\n \u003c/Variable\u003e\n \u003c/XMLPayload\u003e\n \u003c/ExtractVariables\u003e\n ```\n\nFurther reading\n\n- [KeyValueMapOperations policy](/apigee/docs/api-platform/reference/policies/key-value-map-operations-policy)\n- [VerifyAPIKey policy](/apigee/docs/api-platform/reference/policies/verify-api-key-policy)\n- [AccessEntity policy](/apigee/docs/api-platform/reference/policies/access-entity-policy)"]]