Configure a parameter mapping template

更新时间:
复制 MD 格式

API Gateway lets you automatically modify request and response data by configuring parameter mapping templates. This topic describes the configuration syntax and provides notes for using parameter mapping templates.

Sample templates

Note

The backend SOFAREST protocol now supports attaching parameter mappings.

  • Request template

    # Request body
    
    {
     "x" : {"name": "jack"},
      "y" : {
       "z" : ["a", "b", "c"]
      }
    }
    # Define parameters
    params:
      temp: $.Req.Header.temp
      body1: $.Req.Body.x
      body2: $.Req.Body.y
      bodyArray: $.Req.Body.y.z[0]
      body: $.Req.Body
    
    # Expression that returns a value for mapping
    expression: $.temp
    
    # Mapping rules
    mappings:
      # At least one mapping rule is required
      ## If the expression returns "hello", which means the value of the header temp is "hello"
      hello: // If the value is a numeric string, enclose it in double quotation marks, for example, "123"
        # Execute the following mapping logic
        ## bodyOverride template (optional)
        bodyOverride: '[{"name": "{{ $.temp }}"}, {"temp": {{ $.body1}}}]'
        ## Request header settings. The delete operation is executed before the add operation. (optional)
        header:
          disableNormalizing: true
          addKeyValue:
            ah: $.temp
          deleteKey:
            - temp
        ## Request cookie settings. The delete operation is executed before the add operation. (optional)
        cookie:
          addKeyValue:
            ac: $.temp
          deleteKey:
            - cookiekey
        ## Request query settings. The delete operation is executed before the add operation. (optional)
        query:
          addKeyValue:
            aq: $.temp
          deleteKey:
            - querykey
      Chinese:
        # Execute the following mapping logic
        ## bodyOverride template (optional)
        bodyOverride: |
          [
           {"name": {{ $.body1 }}},
            {"temp": {{ $.body2}}},
            {"array":{{$.bodyArray}}},
            {"body": {{$.body}}}
          ]
    
    # Default mapping rule
    default:
      bodyOverride: '{"name": "{{ $.temp }}"}'
      header:
        addKeyValue:
          ah: $.temp
        deleteKey:
          - temp
      cookie:
        addKeyValue:
          ac: $.temp
        deleteKey:
          - cookiekey
      query:
        addKeyValue:
          aq: $.temp
        deleteKey:
          - querykey
  • Response template

    # response body
    
    {
     "x" : {"name": "jack"},
      "y" : {
       "z" : ["a", "b", "c"]
      }
    }
    # Define parameters
    params:
        temp: $.Resp.Header.temp
        bodyx: $.Resp.Body.x
        bodyy: $.Resp.Body.y
        bodyArray: $.Resp.Body.y.z[0]
        body: $.Resp.Body
    
    # An expression that returns a value to be used for mapping.
      expression: $.temp
    
    # Mapping rules
      mappings:
    # At least one mapping rule is required.
    ## If the expression returns "hello", the value of the header "temp" is "hello".
        hello:
    # Execute the following mapping logic.
    ## Body override template (Optional)
          bodyOverride:|
    [{"name":"{{ $.temp }}"},{"temp":{{ $.body1}}}]
    ## Response header settings. The delete operation is executed before the add operation. (Optional)
          header:
            addKeyValue:
              ah: $.temp
            deleteKey:
    - temp
        world:
    # Execute the following mapping logic.
    ## Body override template (Optional)
          bodyOverride:|
    "xx"
    
    # Default mapping rule
    default:
        bodyOverride:|
    {"name":{{ $.temp }}}

As shown in the preceding examples, the template syntax consists of the following main objects:

  • params: Fetches parameters from the request or response. For more information, see params: Fetch parameters.

  • expression: An expression that returns a value. For more information, see expression: Expression.

    • If the expression is a conditional expression, it returns true or false.

    • If the expression is a string concatenation, it returns a string.

  • mappings: Configures different mapping rules based on the value returned by the expression. For more information, see mappings: Mapping rules.

  • default: (Optional) Stores a default mapping rule.

Note

In the default parameter mapping, the response headers that the client receives are in upper camel case format. You can add the disableNormalizing parameter and set its value to true. This prevents the response headers from being transformed and allows them to be passed through to the frontend in lowercase format.

params: Fetch parameters

The params object fetches parameters from a request or response in k:v format. The key is a custom parameter name, and the value is a parameter expression in the format $.Type.Location.key.

  • Type: Can be Req or Resp, which represent request and response, respectively.

  • Location: Can be Header, Query, Cookie, or Body.

    • Resp supports only Header and Body.

    • The Body must be in JSON format.

Examples

  • Example 1: Fetch a parameter from the request header

    Request header: temp = headervalue
    
    Definition: temp = $.Req.Header.temp
    
    Result: ==> temp = headervalue
  • Example 2: Fetch a parameter from the request cookie

    Request cookie: temp = cookievalue
    
    Definition: temp = $.Req.Cookie.temp
    
    Result: ==> temp = cookievalue
  • Example 3: Fetch a parameter from the request body

    Request body: {"hello": {"world": ["1","2","3"]}}
    
    Definition: temp = $.Req.Body.hello.world[0]
    
    Result: ==> temp = 1
  • Example 4: Fetch a parameter from the response body

    Response body: {"hello": {"world": ["1","2","3"]}}
    
    Definition: temp = $.Resp.Body.hello.world[0]
    
    Result: ==> temp = 1

expression: Expression

The expression returns a value. The expression can reference variables defined in params using the format $.name.

  • Example 1

    Request body: {"hello": {"world": ["1","2","3"]}}
    
    Definition: temp = $.Req.Body.hello.world[0]
    
    Expression: $.temp == 1
    
    Result: true
  • Example 2

    Request cookie: temp = cookievalue
    
    Definition: temp = $.Req.Cookie.temp
    
    Expression: $.temp
    
    Result: cookievalue

mappings: Mapping rules

Mapping rules support overwriting the body and modifying the header, query, and cookie. For a response, you can modify only the body and header.

Overwrite the body

bodyOverride overwrites the body. Its value is a standard Go template. You can reference variables defined in params using $.name. The following is an example:

Request body: {"hello": {"world": ["1","2","3"]}}

Definition: temp = $.Req.Body.hello.world[0]

bodyOverride: '{"name": "{{ $.temp }}"}'

Result: {"name":"1"}

Because bodyOverride is a string template, it must be enclosed in single quotation marks. The following is an example:

# Must be on a single line. Line breaks are not allowed.
bodyOverride: '{"name": "{{ $.name }}" }'

If the bodyOverride value is too long for a single line, you can use the following format for multi-line input. The following is an example:

# Add a pipe character (|) after bodyOverride to enable multi-line input.
# Indent the new lines with two spaces to comply with standard YAML syntax.
bodyOverride: |
    [
        {"name": {{ $.body1 }}},
        {"temp": {{ $.body2}}},
        {"array":{{$.bodyArray}}},
        {"body": {{$.body}}}
    ]

The content of bodyOverride is a JSON template. You must ensure that the rendered result is a valid JSON string.

  • If the referenced parameter variable is a string, enclose it in double quotation marks (""), such as {"name": "{{ $.string }}" }.

  • If the referenced parameter variable is another type, do not enclose it in double quotation marks (""), such as {"name": {{ $.object }} }.

Therefore, you must confirm the parameter type when you configure the template. The following are examples:

Assume param.str = "jack"
Define bodyOverride: '{"name": "{{ $.str }}" }'
Rendered result: {"name": "jack"}

Valid JSON

------------

Assume param.str = "jack"
Define bodyOverride: '{"name": {{ $.str }} }'
Rendered result: {"name": jack}

Invalid JSON


------------

Assume param.obj = {"firstName":"tom"}
Define bodyOverride: '{"name": {{ $.obj }} }'
Rendered result: {"name": {"firstName":"tom"}}

Valid JSON
------------

Assume param.obj = {"firstName":"tom"}
Define bodyOverride: '{"name": "{{ $.obj }}" }'
Rendered result: {"name": "{\"firstName\":\"tom\"}"}

Valid JSON, but not the expected result

Modify the query, header, and cookie

You can define addKeyValue and deleteKey operations for all three keys.

  • addKeyValue: A key-value structure. It adds the corresponding key-value pair to the specified location. You can reference variables defined in params using $.name.

  • deleteKey: A list. It deletes all defined keys from the specified location.

The delete operation is executed before the add operation. The following is an example:

Request cookie: temp = cookievalue

Definition: temp = $.Req.Cookie.temp

Mapping: cookie:
		addKeyValue:
			newkey: $.temp
		delete:
			-	temp

Result: cookie: newkey = cookievalue