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:
|
Path | Requests | The full path of the HTTP request. Example:
|
StatusCode | Responses | The HTTP response code in a backend response. Examples:
|
ErrorCode | Responses | The error code of a system error response in API Gateway. For more information, see Error codes. |
Header | Requests or responses | Use the first value of the header whose name is |
Query | Requests | Use |
Form | Requests | Use |
Host | Requests | Use |
Parameter | Requests | Use |
BodyJsonField | Responses* | Use |
System | Requests or responses | Use |
Token | Requests or responses | For JSON Web Token (JWT) authentication plug-ins, use |
XFF | Requests | Use |
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
, andXFF
.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
, andToken
.Only locations are required in the
Method
,Path
,StatusCode
,ErrorCode
, andXFF
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. Afrontend parameter
, instead of abackend parameter
, is used to search for the parameter with the same name in the API definition. If no parameter with the same name exists, anull
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, useSystem:CaDomain
.A complete request path is returned from
Path
. If you require a parameter at thePath
location, use the corresponding parameter at theParameter
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 atoken
. 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 theresult_code
parameter in the following body. The parsing result of the body iscode: 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: |
CaDomain | The full domain name that is specified after the Host header in a request. | Example:
|
CaAppId | The ID of the application that sends the request. | Example:
|
CaAppKey* | The key of the application that sends the request. | Example:
|
CaRequestId | The unique request ID that API Gateway generates. | Example:
|
CaApiName | The API name. | Example:
|
CaHttpSchema | The protocol that is used to send the request. | Valid values: |
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 If you do not want to activate an experience plan, set the parameter to |
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 avariable
or aconstant
for$A > 100
.A
variable
starts with$
and references a parameter defined in the context. For example,q1:"Query:q1"
is defined inparameters
. You can use the variable$q1
in your expression. The value of this variable is the value of theq1
query parameter in the request.A
constant
can be astring
, anumber
, or aboolean value
. For example, the constant can be"Hello"
,'foo'
,100
,-1
,0.1
, ortrue
. 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
, andxor
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)
isfalse
.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 aUNIX 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
andfalse
.
For the operator types
equal to
,not equal to
, andcomparison
, 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 thanfalse
. 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
, andcomparison
, 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 theNUMBER
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 theBOOLEAN
type. If the value type before the operator can be changed to BOOLEAN and the value is not case-sensitive, useBOOLEAN
values, includingtrue
andfalse
, for judgment. Otherwise, except for the judgment result of!=
, all the other judgment results arefalse
. 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 nottrue
orfalse
, only the result for!=
istrue
.'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 alwaysfalse
.
The
null
value is used to check whether a parameter is empty. For the operator typesequal to
,not equal to
, andcomparison
, 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 tonull
, the result of'' == null
isfalse
, and the result of'' == ''
istrue
.For the
comparison
operator type, if the value on either side of the operator isnull
, the result isfalse
.
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
orBOOLEAN
, change the type toSTRING
and perform the judgment.If the value before an operator is
null
, the result isfalse
.
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
orBOOLEAN
or the value is empty, the result isfalse
.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 theresult_code
parameter whose value is notok
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.