All Products
Search
Document Center

API Gateway:Use parameters and conditional expressions

Last Updated:Mar 19, 2024

This topic describes how to use parameters and conditional expressions in API Gateway plug-ins.

1. Overview

API Gateway plug-ins allow you to obtain parameter values from requests, responses, or system context and use custom conditional expressions to judge the parameter values. This topic describes how to define parameters and how to write conditional expressions.

2. Parameter definitions

2.1 Definition method

Before you use a conditional expression, you must explicitly define all the parameters that are required in this conditional expression in the parameters field. Example:

---
parameters:
  method: "Method"
  appId: "System:CaAppId"
  action: "Query:action"
  userId: "Token:UserId"

The parameters specified in the parameters field are key-value pairs of the STRING type.

  • key indicates the name of a variable to be used in a conditional expression. The name must be unique and must conform to the following rule: [a-zA-Z_][a-zA-Z0-9]+.

  • value indicates the location of a parameter. It is specified in the {location} or {location}:{name} format.

    • location indicates the location of a parameter. For more information, see the following table.

    • name indicates the name of a parameter. The name is used to locate the parameter at a specific location. For example, Query:q1 indicates the first value of the parameter that is named q1 in the query string.

2.2 Parameter locations

Before you use a conditional expression, you must define the parameters that are required in this conditional expression. The following table describes parameters at specific locations that the plug-ins of API Gateway can use.

Location

Scope

Description

Method

Requests

The HTTP request method, in uppercase. Examples:

GET and POST.

Path

Requests

The full path of the HTTP request. Example:

/path/to/query

StatusCode

Responses

The HTTP response code in a backend response. Examples:

200 , 400

ErrorCode

Responses

The error code of a system error response in API Gateway. For more information, see Error codes.

Header

Requests or responses

Use Header:{Name} to obtain

the first value of the header whose name is {Name}.

Query

Requests

Use Query:{Name} to obtain the first value of the parameter whose name is {Name} in the query string.

Form

Requests

Use Form:{Name} to obtain the first value of the parameter whose name is {Name} in the request form.

Host

Requests

Use Host:{Name} to obtain the template parameters of the matched wildcard domain names.

Parameter

Requests

Use Parameter:{Name} to obtain the first value of the custom API parameter whose name is {Name}.

BodyJsonField

Responses*

Use BodyJsonField:{JPath} to obtain the value of the parameters in the JSON-formatted body of an API request or a backend response. JPath is a JSONPath expression.

System

Requests or responses

Use System:{Name} to obtain the value of the system parameter whose name is {Name}.

Token

Requests or responses

For JSON Web Token (JWT) authentication plug-ins, use Token:{Name} to obtain the value of the parameter whose name is {Name} in a token.

XFF

Requests

Use XFF:{index} to obtain an IP address in the X-Forwarded-For header. The value of index is the position of an IP address in a sequence of IP addresses in the header. The value starts from 0 and allows negative integers. For example, the value of X-Forwarded-For is IP1,IP2,IP3, then an index value of 0 indicates IP1 and an index value of -1 indicates IP3.

Usage notes of parameter locations

  • Parameter-based access control plug-ins, throttling plug-ins, and back-end routing plug-ins work when requests are received. For those plug-ins, parameters in the following locations in requests are applicable: Method, Path, Header, Query, Form, Parameter, System, Token, and XFF.

  • Error mapping plug-ins work when responses are received. For those plug-ins, parameters in the following locations in responses are applicable: StatusCode, ErrorCode, Header, BodyJsonField, System, and Token.

  • Only locations are required in the Method, Path, StatusCode, ErrorCode, and XFF locations. Names are not required in those locations.

  • If you use parameters at the Header location in a plug-in at the request phase, headers that are in the requests from the client are read. If you use these parameters at the response phase, headers from backend responses are read.

  • Parameters at the Parameter location are available only for plug-ins at the request phase. A frontend parameter, instead of a backend parameter, is used to search for the parameter with the same name in the API definition. If no parameter with the same name exists, a null value is returned.

  • Parameters at the Host location are available only when you obtain the parameters of wildcard domain names. For more information, see Bind a custom domain name to allow API calls. To obtain the system parameters of full domain names, use System:CaDomain.

  • A complete request path is returned from Path. If you require a parameter at the Path location, use the corresponding parameter at the Parameter location.

  • Parameters at the BodyJsonField location are available only for the error code mapping plug-in. Obtain the parameters in the JSON-formatted body of a backend response in JSONPath mode. For more information, see 2.4. Usage notes of JSONPath.

  • If a JWT authentication plug-in is used for authentication, use Token:{CliamName} to obtain the value of the parameter specified by {CliamName} in a token. For more information, see JWT authentication.

2.3 Usage notes of JSONPath

You can use JSONPath expressions to obtain parameters at the BodyJsonField location only for the error code mapping plug-in. The parameters are in the JSON-formatted body returned in a backend response. For more information about JSONPath expressions, see JSONPath.

  • Example: Use code:"BodyJsonField:$.result_code" to obtain the value of the result_code parameter in the following body. The parsing result of the body is code: ok.

{ "result_code": "ok", "message": ... }

2.4 System parameters

Parameter

Parameters

Valid value or sample value

CaClientIp

The IP address of the client from which the request is sent.

Example: 37.78.XX.XX or fe80::1849:59fd:993c:fcff

CaDomain

The full domain name that is specified after the Host header in a request.

Example:

example.aliyundoc.com

CaAppId

The ID of the application that sends the request.

Example:

49382332

CaAppKey*

The key of the application that sends the request.

Example:

12983883923

CaRequestId

The unique request ID that API Gateway generates.

Example:

CCE4DEE6-26EF-46CB-B5EB-327A9FE20ED1

CaApiName

The API name.

Example:

TestAPI

CaHttpSchema

The protocol that is used to send the request.

Valid values: http, https, and ws

CaClientUa

The UserAgent header of the client.

Pass the value that is uploaded by the client.

CaCloudMarketInstanceId

The ID of an instance on Alibaba Cloud Marketplace.

Alibaba Cloud Marketplace

CaMarketExpriencePlan

Specifies whether to activate an experience plan on Alibaba Cloud Marketplace.

If you want to activate an experience plan, set the parameter to true.

If you do not want to activate an experience plan, set the parameter to false.

3. Conditional expressions

You can use conditional expressions to judge parameter values based on conditions in scenarios such as plug-ins.

3.1 Syntax

  • Conditional expressions are similar to SQL statements. Example: $A > 100 and '$B = 'B'.

  • An expression is in the following format: {Parameter} {Operator} {Parameter}. In the preceding example, you can specify a variable or a constant for $A > 100.

  • A variable starts with $ and references a parameter defined in the context. For example, q1:"Query:q1" is defined in parameters. You can use the variable $q1 in your expression. The value of this variable is the value of the q1 query parameter in the request.

  • A constant can be a string, a number, or a boolean value. For example, the constant can be "Hello", 'foo', 100, -1, 0.1, or true. For more information, see 3.2 Value types and judgment rules.

  • The following operators are supported:

  • = and ==: equal to.

  • <> and !=: not equal to.

  • >, >=, <, and <=: comparison.

  • like and !like: check whether a specific string matches a specified pattern. The percent sign % is used as a wildcard in the judgment. Example: $Query like 'Prefix%'.

  • in_cidr and !in_cidr: check whether an IP address is in a CIDR block. Example: $ClientIp in_cidr '47.89.XX.XX/24'.

  • You can use null to check whether a parameter is empty. Example: $A == null or $A != null.

  • You can use the operators and, or, and xor to combine different expressions in a right-to-left order by default.

  • You can use parentheses ( and ) to specify the priority of conditional expressions.

  • You can use !( and ) to perform the logical negation operation on an enclosed expression. For example, the result of !(1=1) is false.

  • The following built-in functions are used for judgment in special scenarios:

    • Random(): generates a parameter of the floating-point number type. The parameter value ranges from 0 to 1. This parameter is used in scenarios where random input is required, such as blue-green release.

    • Timestamp(): returns a UNIX timestamp. The UNIX timestamp is the number of milliseconds that have elapsed since 00:00:00 Thursday, 1 January 1970.

    • TimeOfDay(): returns the number of milliseconds that have elapsed since 00:00 of the current day in GMT.

3.2 Value types and judgment rules

  • The following value types are supported in expressions:

    • STRING: The value is a string enclosed in single quotation marks (') or double quotation marks ("). Examples: "Hello" and 'Hello'.

    • NUMBER: The value is an integer or a floating-point number. Examples: 1001, -1, 0.1, and -100.0.

    • BOOLEAN: The value is a boolean value. Examples: true and false.

  • For the operator types equal to, not equal to, and comparison, the following judgment rules apply:

    • STRING type: uses the string order for judgment. Examples:

      • '123' > '10000': The result is true.

      • 'A123' > 'A120': The result is true.

      • '' <'a': The result is true.

    • NUMBER type: uses numerical values for judgment. Examples:

      • 123 > 1000: The result is false.

      • 100.0 == 100: The result is true.

    • BOOLEAN type: For Boolean values, true is greater than false. Examples:

      • true == true: The result is true.

      • false == false: The result is true.

      • true > false: The result is true.

  • For the operator types equal to, not equal to, and comparison, if the value types before and after an operator are different, the following judgment rules apply:

    • STRING NUMBER: For example, the value before an operator is of the STRING type and that after the operator is of the NUMBER type. If the value type before the operator can be changed to NUMBER, use numerical values for judgment. Otherwise, use the string order for judgment. Examples:

      • '100' == 100.0: The result is true.

      • '-100' > 0: The result is false.

    • STRING BOOLEAN: For example, the value before an operator is of the STRING type and that after the operator is of the BOOLEAN type. If the value type before the operator can be changed to BOOLEAN and the value is not case-sensitive, use BOOLEAN values, including true and false, for judgment. Otherwise, except for the judgment result of !=, all the other judgment results are false. Examples:

      • 'True' == true: The result is true.

      • 'False' == false: The result is true.

      • 'bad' == false: The result is false.

      • 'bad' != false: The result is true. If the value before the operator is not true or false, only the result for != is true.

      • 'bad' ! =true. The result is true.

      • '0' > false: The result is false.

      • '0' <= false: The result is false.

    • NUMBER BOOLEAN: If the value before an operator is of the NUMBER type and that after the operator is of the BOOLEAN type, the result is always false.

  • The null value is used to check whether a parameter is empty. For the operator types equal to, not equal to, and comparison, the following judgment rules apply:

    • If the $A variable is empty, the result of $A == null is true, and the result of $A !=null is false.

    • If the empty string '' is not equal to null, the result of '' == null is false, and the result of '' == '' is true.

    • For the comparison operator type, if the value on either side of the operator is null, the result is false.

  • like and !like operators are used to match the prefix, suffix, and inclusion of a string. The following judgment rules apply:

    • In an expression, the value after the operator must be a constant of the STRING type. Example: $Path like '/users/%'.

    • The '%' wildcard character in the value after the operator is used to match the prefix, suffix, or inclusion of a string. Examples:

      • Prefix matching: $Path like '/users/%' and $Path !like '/admin/%'.

      • Suffix matching: $q1 like '%search' and $q1 !like '%.do'.

      • Inclusion relationship matching: $ErrorCode like '%400%' and $ErrorCode !like '%200%'.

    • If the value type before an operator is not NUMBER or BOOLEAN, change the type to STRING and perform the judgment.

    • If the value before an operator is null, the result is false.

  • in_cidr and !in_cidr operators are used to check whether an IP address is in a CIDR block. The following judgment rules apply:

    • The value after an operator must be a constant of the STRING type and must be an IPv4 or IPv6 CIDR block. Examples:

      • $ClientIP in_cidr '10.0.0.0/8'

      • $ClientIP !in_cidr '0:0:0:0:0:FFFF::/96'

    • If the value type before an operator is STRING, the value is considered as an IPv4 CIDR block for judgment.

    • If the value type before an operator is NUMBER or BOOLEAN or the value is empty, the result is false.

    • The System:CaClientIp parameter specifies the IP address of the client. This parameter can be used for judgment.

4. Use cases

  • Check whether the probability is less than 5%:

Random() < 0.05
  • Check whether the requested API is published to the test environment.

parameters:
  stage: "System:CaStage"
$CaStage = 'TEST'
  • Check whether the custom parameter UserName is set to Admin and the source IP address is in 47.47.XX.XX/24.

parameters:
  UserName: "Token:UserName"
  ClientIp: "System:CaClientIp"
$UserName = 'Admin' and $CaClientIp in_cidr '47.47.XX.XX/24'
  • If the result of the following expression is true, the CaAppId parameter is set to 1001, 1098, or 2011, and the protocol that is used by the API request is HTTPS.

parameters:
  CaAppId: "System:CaAppId"
  HttpSchema: "System:CaHttpSchema"
$CaHttpScheme = 'HTTPS' and ($CaAppId = 1001 or $CaAppId = 1098 or $CaAppId = 2011)`
  • If the result of the following expression is true, the JSON-formatted body contains the result_code parameter whose value is not ok when StatusCode in a response is 200.

parameters:
  StatusCode: "StatusCode"
  ResultCode: "BodyJsonField:$.result_code"
$StatusCode = 200 and ($ResultCode <> null and $ResultCode <> 'ok')

5. Limits

  • A maximum of 16 parameters can be specified in a plug-in.

  • A single conditional expression can contain a maximum of 512 characters.

  • The size of a request or response body specified by BodyJsonField cannot exceed 16 KB. Otherwise, the settings do not take effect.