Dans un flux conditionnel, les règles ne sont exécutées que si la condition du flux renvoie true (par opposition aux règles associées aux flux PreFlow ou PostFlow, qui sont toujours exécutés). Cette section explique comment créer un flux conditionnel.
À propos des flux conditionnels
Lors du traitement d'une requête et d'une réponse, un seul flux conditionnel est exécuté par segment : le premier flux dont la condition renvoie la valeur true.
Les exemples suivants illustrent certaines manières d'utiliser des flux conditionnels.
Exemple 1
La définition ProxyEndpoint suivante affiche un flux conditionnel qui est exécuté par le ProxyEndpoint sur toutes les requêtes HTTP GET envoyées au proxy d'API :
Notez que la condition fait référence à la request.verbvariable de flux. Une variable de flux est une référence nommée qui contient les informations d'état associées à une transaction d'API traitée par Apigee. Apigee définit de nombreuses variables d'état que vous pouvez référencer.
Exemple 2
Si votre backend de service fournit des rapports et des prévisions météorologiques, votre API peut définir deux flux conditionnels mappés à ces ressources d'API : /reports et /forecasts. Lorsqu'un appel d'API inclut l'une de ces ressources dans l'URL, la condition est évaluée à true et la logique associée au flux conditionnel est exécutée.
Les développeurs d'applications accèdent ensuite à vos ressources en envoyant des requêtes à une URL au format suivant :
http://myAPIs.myCo.com/weather/reports
ou :
http://myAPIs.myCo.com/weather/forecasts
Dans un proxy d'API, vous pouvez définir un flux conditionnel correspondant à une ressource spécifique :
Dans cet exemple, vous référencez la variable de flux proxy.pathsuffix, qui contient le suffixe de l'URL utilisé pour accéder au proxy d'API. Vous pouvez ensuite associer différentes règles au flux conditionnel pour chaque ressource.
Exemple : Créer un flux conditionnel
L'exemple suivant :
Crée un flux conditionnel qui ne s'exécute que lorsque le message de la requête est une requête HTTP GET.
Ajoute une règle au nouveau flux.
Ajouter un flux conditionnel
Nouvel éditeur de proxys
Pour ajouter un flux conditionnel, procédez comme suit :
Sélectionnez l'onglet Développer dans l'éditeur de proxy.
Sélectionnez Points de terminaison du proxy > Par défaut dans le volet de gauche.
Remarque : Vous devrez peut-être développer l'éditeur visuel dans le volet de droite pour afficher tous les éléments.
Pour ce faire, cliquez sur le séparateur et faites-le glisser entre l'éditeur visuel et l'éditeur de texte.
Cliquez sur le bouton + au-dessus du volet Response (Réponse).
Dans la boîte de dialogue Add conditional flow (Ajouter un flux conditionnel), sélectionnez Path et Verb (Chemin d'accès et verbe), puis saisissez dans le champ Path le suffixe de chemin d'accès qui doit se trouver dans le chemin de la requête pour que le flux conditionnel s'exécute. Voir l'exemple 2 ci-dessus
Le flux conditionnel ne s'exécute que si la requête est une requête GET (mais pas pour PUT, POST, etc.).
Le nouveau flux, intitulé Flow-1, apparaît désormais dans le volet Point de terminaison du proxy.
Le code XML du nouveau flux conditionnel s'affiche dans l'éditeur de texte.
Vous pouvez modifier l'élément Condition si vous le souhaitez. Consultez la section Ajouter une logique aux flux.
Associer une règle au flux
Maintenant que vous avez créé le flux conditionnel, vous pouvez lui associer une règle. L'exemple suivant ajoute une règle de quota, qui limite le nombre de messages de requête au flux autorisés par un proxy d'API sur une période donnée :
Dans le volet de gauche, cliquez sur le bouton + à droite de Policies (Règles).
Dans la boîte de dialogue Create policy (Créer une règle), cliquez dans le champ Select policy type (Sélectionner un type de règle) et faites défiler la page jusqu'à Traffic Management (Gestion du trafic), puis sélectionnez Quota.
Cliquez sur Create (Créer) pour créer la règle.
Cliquez sur le bouton + à côté de Flow-1 dans le volet Request (Requête).
Dans la boîte de dialogue Add policy step (Ajouter une étape de règle), cliquez dans le champ Select existing policy (Sélectionner une règle existante), puis sélectionnez Quota-1.
Cliquez sur Ajouter.
Le volet Request (Requête) affiche désormais le flux et la règle associée, Quota-1.
L'éditeur de texte affiche maintenant une étape contenant la règle Quota-1 dans l'élément Flow-1 du fichier XML :
Avec cette configuration, la règle de quota sera appliquée aux requêtes GET.
Les requêtes d'autres types ne contribuent pas au nombre maximal de requêtes dans la règle de quota.
Éditeur de proxy classique
Pour ajouter un flux conditionnel, sélectionnez l'onglet Develop (Développer) dans le compilateur de proxy d'API.
Cliquez sur dans le point de terminaison souhaité.
Le formulaire New Conditional Flow vous permet de nommer le flux et de configurer une condition. Dans l'exemple suivant, vous ajoutez une condition simple qui évalue la syntaxe HTTP du message de requête pour le verbe GET (par opposition à PUT, POST, etc.) d'un URI suivant le chemin d'accès de base.
Une fois que vous avez créé un flux conditionnel, celui-ci peut être utilisé pour joindre une stratégie. Une fois le flux sélectionné, cliquez sur l'icône + Étape dans le schéma de requête ou de réponse pour ajouter une stratégie nouvelle ou existante au flux.
En associant la règle au flux sélectionné, vous configurez le proxy d'API de manière à n'appliquer la règle de quota que pour les requêtes adressées à cette combinaison d'URI et de verbe pour le flux. Par exemple, si vous associez la stratégie au flux learn dans la requête, le fichier XML suivant est généré dans l'éditeur de texte :
Dans cette configuration, si une requête GET arrive sur le proxy d'API avec un format d'URI .../issue/** (/issue/ avec tout ce qui figure dans l'URI après la dernière barre oblique), le quota est appliqué à cet appel d'API.
Étapes suivantes
Les rubriques suivantes fournissent des informations supplémentaires sur la construction des conditions et l'utilisation de variables :
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/04 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/09/04 (UTC)."],[[["\u003cp\u003eConditional flows in Apigee execute policies only if their defined condition evaluates to \u003ccode\u003etrue\u003c/code\u003e, unlike PreFlow or PostFlow policies that always run.\u003c/p\u003e\n"],["\u003cp\u003eOnly one conditional flow per segment is executed during a request and response, specifically the first flow whose condition is met.\u003c/p\u003e\n"],["\u003cp\u003eConditional flows can be based on HTTP verbs like \u003ccode\u003eGET\u003c/code\u003e or URL resources like \u003ccode\u003e/reports\u003c/code\u003e and \u003ccode\u003e/forecasts\u003c/code\u003e, leveraging flow variables such as \u003ccode\u003erequest.verb\u003c/code\u003e and \u003ccode\u003eproxy.pathsuffix\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eAdding a conditional flow can be done in either the New Proxy Editor or the Classic Proxy Editor, allowing for customized execution logic based on specific request characteristics.\u003c/p\u003e\n"],["\u003cp\u003ePolicies, like a Quota policy, can be attached to a conditional flow to enforce certain rules, such as limiting request frequency, for requests matching the flow's condition.\u003c/p\u003e\n"]]],[],null,["# Conditional flows\n\n*This page\napplies to **Apigee** and **Apigee hybrid**.*\n\n\n*View [Apigee Edge](https://docs.apigee.com/api-platform/get-started/what-apigee-edge) documentation.*\n\nIn a conditional flow,\npolicies are executed only if the flow's condition evaluates to\n`true` (as opposed to policies attached to the PreFlow or PostFlow,\nwhich are always executed). This section describes how to create a conditional flow.\n\nAbout conditional flows\n-----------------------\n\nDuring the processing of a request and response, only one conditional flow is executed per\nsegment---the first flow whose condition evaluates to `true`.\nYou can create conditions that include `||`(OR) and `&&`(AND) operators. However, by default, the `||` operator has higher precedence than the `&&` operator. For example, a condition written as ` A && B || C && D` is evaluated as `A && (B || C) && D`. Make sure to parenthesize the expression if you want to change the precedence when using these operators.\n\nThe following examples illustrate some ways to use conditional flows.\n\n### Example 1\n\nThe following ProxyEndpoint definition shows a conditional flow that is executed\nby the ProxyEndpoint on any `HTTP GET` request to the API proxy: \n\n```text\n\u003cProxyEndpoint name=\"default\"\u003e\n \u003cPreFlow\u003e\n \u003cRequest/\u003e\n \u003cResponse/\u003e\n \u003c/PreFlow\u003e\n \u003cFlows\u003e\n \u003cFlow name=\"Flow-1\"\u003e\n \u003cCondition\u003erequest.verb=\"GET\"\u003c/Condition\u003e\n \u003cRequest/\u003e\n \u003cResponse/\u003e\n \u003c/Flow\u003e\n \u003c/Flows\u003e\n \u003cPostFlow\u003e\n \u003cRequest/\u003e\n \u003cResponse/\u003e\n \u003c/PostFlow\u003e\n ...\n\u003c/ProxyEndpoint\u003e\n```\n\nNotice that the condition references the `request.verb`\n[*flow\nvariable*](/apigee/docs/api-platform/fundamentals/introduction-flow-variables). A flow variable is named references that hold state information associated\nwith an API transaction processed by Apigee. Apigee defines many state variables that you can\nreference.\n\n### Example 2\n\nIf your\nservice backend provides weather reports and weather forecasts, your API might define two\nconditional flows that map to those API\nresources: `/reports` and `/forecasts`. When an API call\nincludes one of those resources in the URL, the condition evaluates to true and the logic\nattached to the conditional flow is executed.\n\nApp developers then access your resources by making requests to a URL in the form: \n\n```text\nhttp://myAPIs.myCo.com/weather/reports\n```\n\nor: \n\n```text\nhttp://myAPIs.myCo.com/weather/forecasts\n```\n\nIn an API proxy, you can define a conditional flow that corresponds to a specific\nresource: \n\n```text\n\u003cProxyEndpoint name=\"default\"\u003e\n \u003cPreFlow\u003e\n \u003cRequest/\u003e\n \u003cResponse/\u003e\n \u003c/PreFlow\u003e\n \u003cFlows\u003e\n \u003cFlow name=\"Flow-1\"\u003e\n \u003cCondition\u003e(proxy.pathsuffix MatchesPath \"/reports\")\u003c/Condition\u003e\n \u003cRequest/\u003e\n \u003cResponse/\u003e\n \u003c/Flow\u003e\n \u003cFlow name=\"Flow-2\"\u003e\n \u003cCondition\u003e(proxy.pathsuffix MatchesPath \"/forecasts\")\u003c/Condition\u003e\n \u003cRequest/\u003e\n \u003cResponse/\u003e\n \u003c/Flow\u003e\n \u003c/Flows\u003e\n \u003cPostFlow\u003e\n \u003cRequest/\u003e\n \u003cResponse/\u003e\n \u003c/PostFlow\u003e\n ...\n\u003c/ProxyEndpoint\u003e\n```\n\nIn this example, you reference the `proxy.pathsuffix` flow variable,\nwhich contains the suffix portion of the URL used to access the API proxy. You can then attach\ndifferent policies to the conditional flow for each resource.\n\nExample: Creating a conditional flow\n------------------------------------\n\nThe next example:\n\n- Creates a conditional flow that executes only when the request message is an HTTP `GET`.\n- Adds a policy to the new flow.\n\n### Adding a conditional flow\n\n### Apigee in Cloud console\n\nTo add a conditional flow:\n\n1. Select the **Develop** tab in the Proxy Editor.\n2. Select **Proxy endpoints \\\u003e default** in the left-hand pane.\n\n **Note:** You may need to expand the visual editor in the right-hand pane to see all the\n elements.\n To do so, click and drag the divider between the visual editor and the text editor\n down a little.\n3. Click the **+** button above the **Response** pane.\n\n4. In the **Add conditional flow** dialog, select **Path and verb** , and in the **Path** field, enter the path suffix that you want to be in the request path in order for the conditional flow to execute. See [Example 2](#example-2) above. **Note:** If you don't want to include a path condition, simply enter **/** in the **Path** field, as shown below. This will be matched for any request.\n\n The conditional flow only executes if the request is\n a `GET` request (but not for `PUT`, `POST`, etc.).\n\n The new flow, called `Flow-1`, now appears in the **Proxy Endpoint** pane.\n\n5. The XML code for the new conditional flow is displayed in the text editor.\n\nYou can edit the **Condition** element if you wish. See\n[Adding logic\nto flows](/apigee/docs/api-platform/fundamentals/what-are-flows#addinglogictoflows).\n\n### Attaching a policy to the flow\n\nNow that you have created the conditional flow, you can attach a policy to it. The next example\nadds a Quota policy, which restricts the number of request messages that an API proxy allows over\na period of time, to the flow:\n\n1. In the left-hand pane, click the **+** button to the right of **Policies**.\n2. In the **Create policy** dialog, click in the **Select policy type** field and scroll down to **Traffic Management** and select **Quota**.\n3. Click **Create** to create the policy.\n4. Click the **+** button next to **Flow-1** in the **Request** pane.\n\n5. In the **Add policy step** dialog, click in the **Select existing policy** field and select **Quota-1**.\n6. Click **Add**.\n\nThe **Request** pane now displays the flow and attached policy, **Quota-1**.\n\nThe text editor now displays a step containing the **Quota-1** policy in the\n**Flow-1** element of the XML:\n\nWith this configuration, the Quota policy will be enforced for `GET` requests.\nRequests of other types will not contribute to the maximum number of requests in the Quota policy.\n\n### Classic UI\n\nTo add a conditional flow, select the **Develop** tab in the API proxy builder.\n\nClick in the desired endpoint.\n\nThe **New Conditional Flow** form lets you name the flow and configure a condition. In the\nfollowing example, you add a simple condition that evaluates the HTTP of the request message for\na `GET` verb (as opposed to `PUT`, `POST`, etc.) on any URI after the base path.\n\n(Learn how to construct conditional statements in\n[Conditions with\nflow variables](/apigee/docs/api-platform/fundamentals/flow-variables-and-conditions).)\n\nThe new flow, called `Flow-1`, now appears in the Navigator menu.\n\nNow observe the XML configuration for the ProxyEndpoint. Select **Flow-1** in the\n**Navigator** menu.\n\nYou will see the following configuration. \n\n```scdoc\n\u003cPreFlow name=\"PreFlow\"\u003e\n \u003cRequest/\u003e\n \u003cResponse/\u003e\n\u003c/PreFlow\u003e\n\u003cFlows\u003e\n \u003cFlow name=\"Flow-1\"\u003e\n \u003cRequest/\u003e\n \u003cResponse/\u003e\n \u003cCondition\u003e(proxy.pathsuffix MatchesPath \"/**\") and (request.verb = \"GET\")\u003c/Condition\u003e\n \u003c/Flow\u003e\n\u003c/Flows\u003e\n\u003cPostFlow name=\"PostFlow\"\u003e\n \u003cRequest/\u003e\n \u003cResponse/\u003e\n\u003c/PostFlow\u003e\n```\n\nOnce you have created a conditional flow, it is available for policy attachment. With the flow\nselected, click the **+ Step** icon in the request or response diagram to add a\nnew or existing policy to the flow.\n\nBy attaching the policy to the selected flow, you are configuring the API proxy to enforce the\nQuota policy only for requests made to that flow URI and verb combination. For example, if you\nattach the policy to the **learn** flow in the request, the following XML is\ngenerated in the text editor: \n\n```scdoc\n\u003cProxyEndpoint name=\"default\"\u003e\n...\n \u003cFlow name=\"issue\"\u003e\n \u003cDescription/\u003e\n \u003cRequest\u003e\n \u003cStep\u003e\n \u003cName\u003eQuota-2\u003c/Name\u003e\n \u003c/Step\u003e\n \u003c/Request\u003e\n \u003cResponse/\u003e\n \u003cCondition\u003e(proxy.pathsuffix MatchesPath \"/issue/**\") and (request.verb = \"GET\")\u003c/Condition\u003e\n \u003c/Flow\u003e\n...\n\u003c/ProxyEndpoint\u003e\n```\n\nIn this configuration, if a `GET` request comes in on the API proxy with a URI\npattern of ...**/issue/\\*\\*** (/issue/ with anything in the URI after the last forward\nslash), quota is enforced on that API call.\n\nNext steps\n----------\n\nThe following topics provide more detail about constructing conditions and using\nvariables:\n\n- [Using flow variables](/apigee/docs/api-platform/fundamentals/introduction-flow-variables)\n- [Conditions with flow variables](/apigee/docs/api-platform/fundamentals/flow-variables-and-conditions)"]]