This topic describes how to use parameters and conditional expressions in API Gateway plug-ins.
1. Overview
In plug-ins, you can retrieve parameters from the current request, response, or system context and then use custom conditional expressions to evaluate them. This topic describes how to define parameters and write conditional expressions.
2. Parameter definitions
2.1 Definition method
Before using a conditional expression, you must explicitly define all required parameters in the parameters field. For example:
---
parameters:
method: "Method"
appId: "System:CaAppId"
action: "Query:action"
userId: "Token:UserId"The parameters field contains key-value pairs of the string type. The key and value are defined as follows:
key: The name of a variable to use in a conditional expression. The name must be unique and follow the format[a-zA-Z_][a-zA-Z0-9]+.value: The location of a parameter. Define the location in the{location}or{location}:{name}format. For example:location: The location of a parameter. For more information, see the next section.name: The name of a parameter. Use the name to locate the parameter at a specific location. For example,Query:q1indicates the first value of the parameter 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 Indicates the first value of the |
Query | Requests | Use |
Form | Requests | Use |
Host | Requests | Use |
Parameter | Requests | Use |
BodyJsonField | Responses* | Use |
System | Requests or responses | Use |
Token | Requests or responses | When JWT authentication is used, use |
XFF | Requests | Use the format |
Usage notes of parameter locations
Parameter-based access control plug-ins, traffic shaping plug-ins, and backend routing plug-ins run during the request phase. These plug-ins support only parameters from the following request locations:
Method,Path,Header,Query,Form,Parameter,System,Token, andXFF.Error code mapping plug-ins run during the response phase. These plug-ins support only parameters from the following response locations:
StatusCode,ErrorCode,Header,BodyJsonField,System, andToken.For the
Method,Path,StatusCode,ErrorCode, andXFFlocations, you need to provide only the location. A name is not required.When a parameter at the
Headerlocation is used in a plug-in during the request phase, the plug-in reads the header from the client request. When the parameter is used in a plug-in during the response phase, the plug-in reads the header from the backend response.Parameters at the
Parameterlocation are used only in plug-ins during the request phase. The system searches for a parameter with the same name in the API definition using theparameter name, not thebackend parameter name. If the parameter does not exist,nullis returned.Parameters at the
Hostlocation are supported only for wildcard domain name parameter extraction. For more information, see Use a custom domain name to call an API. To retrieve the full host, use theSystem:CaDomainsystem parameter.The
Pathparameter specifies the full request path. If thePathcontains parameters, define them in theParametersection.Parameters at the
BodyJsonFieldlocation are currently supported only in the error code mapping plug-in. Use aJSONPathexpression to read the value from the JSON response body. For more information, see JSONPath usage notes.Token: If a JWT authentication plug-in is configured, you can useToken:{ClaimName}to read the value defined in the plug-in. For more information, see the documentation for the corresponding plug-in.
2.3 Usage notes of JSONPath
You can use a JSONPath expression at the BodyJsonField location to extract JSON fields from the JSON body of a backend response. This feature is supported only for the error code mapping plug-in. For more information about JSONPath, see the JSONPath documentation.
Example: Use
code:"BodyJsonField:$.result_code"to retrieve the value ofresult_codefrom the following response body. The parsed result iscode:ok.
{ "result_code": "ok", "message": ... }2.4 System parameters
Parameter | Parameters | Valid value or sample value |
CaClientIp | The IP address of the client that sent the request. | For example: |
CaDomain | The full domain name from the Host header of the request. | Example:
|
CaAppId | The ID of the application that sent the request. | Example:
|
CaAppKey* | The key of the application that sent the request. | Example:
|
CaRequestId | The unique request ID generated by API Gateway. | Example:
|
CaApiName | The API name. | Example:
|
CaHttpSchema | The protocol used to call the API. | Valid values: |
CaClientUa | The User-Agent header of the client. | Pass the value that is uploaded by the client. |
CaCloudMarketInstanceId | The ID of the purchase relationship on Alibaba Cloud Marketplace. | Alibaba Cloud Marketplace |
CaMarketExpriencePlan | Specifies whether an Alibaba Cloud Marketplace trial plan is activated. | Activated: Not activated: |
3. Conditional expressions
You can use conditional expressions in plug-ins and other scenarios to perform flexible conditional evaluations.
3.1 Syntax
Conditional expressions are similar to SQL expressions. For example:
$A > 100 and '$B = 'B'.The basic format of an expression is
{parameter} {operator} {parameter}. For example, in$A > 100, the parameters can bevariablesorconstants.A
variablestarts with$and references a parameter defined in the context. For example, if the parameterq1:"Query:q1"is defined inparameters, you can use the variable$q1in the expression. The value of this variable is the value of the query parameter namedq1in the current request.A
constantcan be astring,number, orBoolean type, such as"Hello",'foo',100,-1,0.1, ortrue. For more information, see Parameter types and judgment rules.The following
operatorsare supported:=and==: Equal to.<>and!=: Not equal to.>,>=,<, and<=: Comparison.likeand!like: Similarity check. The%wildcard at the start or end of a string can be used to check for string similarity. For example:$Query like 'Prefix%'.in_cidrand!in_cidr: Check if an IP address is within a specific CIDR block. For example:$ClientIp in_cidr '47.89.XX.XX/24'.Use
nullto check if a parameter is empty. For example:$A == nullor$A != null.Use
and,or, andxorto combine different expressions. The default evaluation order is from right to left.Use parentheses
(and)to specify the priority of conditions.Use
!(and)to perform a NOT operation on the enclosed expression. For example, the result of!(1=1)isfalse.The system has built-in functions for evaluations in special scenarios.
Random(): Generates a floating-point number between0 and 1. This function is used in scenarios that require randomness, such as blue-green deployments.Timestamp(): Returns aUnix timestampin milliseconds.TimeOfDay(): Returns the number of milliseconds that have elapsed since midnight of the current day in theGMTtime zone.
3.2 Value types and judgment rules
The following value types are supported in expressions:
STRING: A string type. You can use single or double quotation marks. For example:"Hello",'Hello'.NUMBER: An integer or floating-point number type. For example:1001,-1,0.1,-100.0.BOOLEAN: A Boolean type. For example:true,false.
For the
equal to,not equal to, andcomparisonoperators, the evaluation rules for different types are as follows:STRING: Uses string order for evaluation. For example:The result of
'123' > '1000'is true.The result of
'A123' > 'A120'is true.The result of
'' < 'a'is true.
NUMBER: Evaluates based on numerical value.The result of
123 > 1000is false.The result of
100.0 == 100is true.
BOOLEAN: The evaluation rule for Boolean values is thattrueis greater thanfalse.The result of
true == trueis true.The result of
false == falseis true.The result of
true > falseis true.
For the
equal to,not equal to, andcomparisonoperators, if the parameter types of the left and right operands are different, the following evaluation rules apply:STRING NUMBER: If the left operand can be converted to theNUMBERtype, the values are compared numerically. Otherwise, they are compared as strings. For example:The result of
'100' = 100.0is true.The result of
'-100' > 0is false.
STRING BOOLEAN: If the left operand can be converted to theBOOLEANtype (case-insensitively equal totrueorfalse), the comparison is based on theBOOLEANtype. Otherwise, except for the!=comparison, the result of all other comparisons isfalse. For example:The result of
'True' = trueis true.The result of
'False' = falseis true.The result of
'bad' = falseis false.The result of
'bad' != falseis true. For a left operand that is nottrueorfalse, only the!=operator returnstrue. All other comparison operators returnfalse.The result of
'bad' != trueis true.The result of
'0' > falseis false.The result of
'0' <= falseis false.
NUMBER BOOLEAN: Always returnsfalse.
The
nullvalue can be used to check if a field is empty. For theequal to,not equal to, andcomparisonoperators, the evaluation rules are as follows:When the parameter
$Ais empty, the result of$A == nullis true, and the result of$A != nullis false.An empty string
''is not equal tonull. The result of'' == nullisfalse, and the result of'' == ''istrue.For the
comparisonoperator, if either operand isnull, the result isfalse.
The
likeand!likeoperators can be used to check for string prefixes, suffixes, and inclusion. The evaluation rules are as follows:The expression only supports a
STRINGconstant as the right operand. For example:$Path like '/users/%'.The
'%'character can be used at the start or end of the right operand to support prefix, suffix, and inclusion checks. For example:Prefix check:
$Path like '/users/%',$Path !like '/admin/%'.Suffix check:
$q1 like '%search',$q1 !like '%.do'.Inclusion check:
$ErrorCode like '%400%',$ErrorCode !like '%200%'.
If the left operand is not a
NUMBERorBOOLEANtype, it is converted to theSTRINGformat before evaluation.If the left operand is
null, the result isfalse.
The
in_cidrand!in_cidrexpressions can be used to check if an IP address is within a CIDR block. The evaluation rules are as follows:The expression only supports a
STRINGconstant that is in IPv4 or IPv6 CIDR format as the right operand. For example:$ClientIP in_cidr '10.0.0.0/8'$ClientIP !in_cidr '0:0:0:0:0:FFFF::/96'
If the left operand is a
STRINGtype, it is evaluated as an IP address.If the left operand is a
NUMBERorBOOLEANtype, or is empty, the result isfalse.The
System:CaClientIpparameter returns the client's IP address and is typically used for this type of evaluation.
4. Use cases
A 5% chance:
Random() < 0.05Check whether the requested API is published to the test environment.
parameters:
stage: "System:CaStage"$CaStage = 'TEST'The custom parameter UserName is Admin and the source IP address is within the
47.47.XX.XX/24CIDR block.
parameters:
UserName: "Token:UserName"
ClientIp: "System:CaClientIp"$UserName = 'Admin' and $CaClientIp in_cidr '47.47.XX.XX/24'The user ID of the current request is 1001, 1098, or 2011, and the request uses the HTTPS protocol.
parameters:
CaAppId: "System:CaAppId"
HttpSchema: "System:CaHttpSchema"$CaHttpScheme = 'HTTPS' and ($CaAppId = 1001 or $CaAppId = 1098 or $CaAppId = 2011)`The response StatusCode is 200, and the
JSONbody contains aresult_codethat is notok.
parameters:
StatusCode: "StatusCode"
ResultCode: "BodyJsonField:$.result_code"$StatusCode = 200 and ($ResultCode <> null and $ResultCode <> 'ok')5. Limits
A single plug-in can have a maximum of 16 parameter definitions.
A single expression cannot exceed 512 characters.
The size of a request or response body for BodyJsonField cannot exceed 16 KB. If the limit is exceeded, the setting does not take effect.