This is an automated email from the ASF dual-hosted git repository.

wenming pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/apisix.git


The following commit(s) were added to refs/heads/master by this push:
     new 26bff9ac0 docs: improve `body-transformer` plugin docs (#11856)
26bff9ac0 is described below

commit 26bff9ac0edde9bcd65ac12b038526c9dd2bde38
Author: Traky Deng <[email protected]>
AuthorDate: Tue Apr 8 09:46:50 2025 +0800

    docs: improve `body-transformer` plugin docs (#11856)
---
 docs/en/latest/plugins/body-transformer.md | 667 +++++++++++++++++++++--------
 docs/zh/latest/config.json                 |   1 +
 docs/zh/latest/plugins/body-transformer.md | 609 ++++++++++++++++++++++++++
 3 files changed, 1103 insertions(+), 174 deletions(-)

diff --git a/docs/en/latest/plugins/body-transformer.md 
b/docs/en/latest/plugins/body-transformer.md
index dc1b78632..7e433bee1 100644
--- a/docs/en/latest/plugins/body-transformer.md
+++ b/docs/en/latest/plugins/body-transformer.md
@@ -6,7 +6,7 @@ keywords:
   - Plugin
   - BODY TRANSFORMER
   - body-transformer
-description: This document contains information about the Apache APISIX 
body-transformer Plugin.
+description: The body-transformer Plugin performs template-based 
transformations to transform the request and/or response bodies from one format 
to another, for example, from JSON to JSON, JSON to HTML, or XML to YAML.
 ---
 
 <!--
@@ -28,34 +28,33 @@ description: This document contains information about the 
Apache APISIX body-tra
 #
 -->
 
-## Description
-
-This plugin is used to transform the request and/or response body from one
-format to another format, e.g. JSON to XML.
+<head>
+  <link rel="canonical" href="https://docs.api7.ai/hub/body-transformer"; />
+</head>
 
-Use cases:
+## Description
 
-- simple SOAP proxy
-- generic template-based transform, e.g. JSON to JSON, JSON to HTML, XML to 
YAML
+The `body-transformer` Plugin performs template-based transformations to 
transform the request and/or response bodies from one format to another, for 
example, from JSON to JSON, JSON to HTML, or XML to YAML.
 
 ## Attributes
 
-| Name      | Type | Required      | Description |
-| ----------- | ----------- | ----------- | ----------- |
-| `request`      | object       | False      | request body transformation 
configuration      |
-| `request.input_format`      | string       | False      | request body 
original format, if not specified, it would be determined from `Content-Type` 
header.      |
-| `request.template`      | string       | True      | request body 
transformation template       |
-| `request.template_is_base64`      | boolean       | False    | Set to true 
if the template is base64 encoded       |
-| `response`      | object       | False      | response body transformation 
configuration      |
-| `response.input_format`      | string       | False      | response body 
original format, if not specified, it would be determined from `Content-Type` 
header.       |
-| `response.template`      | string       | True      | response body 
transformation template       |
-| `response.template_is_base64`      | boolean       | False     | Set to true 
if the template is base64 encoded       |
+| Name          | Type    | Required | Default | Valid values | Description    
                            |
+| ------------- | ------- | -------- | ------- | ------------ | 
------------------------------------------ |
+| `request`      | object       | False      | | | Request body transformation 
configuration.      |
+| `request.input_format`      | string       | False      | | 
[`xml`,`json`,`encoded`,`args`,`plain`,`multipart`] | Request body original 
media type. If unspecified, the value would be determined by the `Content-Type` 
header to apply the corresponding decoder. The `xml` option corresponds to 
`text/xml` media type. The `json` option corresponds to `application/json` 
media type. The `encoded` option corresponds to 
`application/x-www-form-urlencoded` media type. The `args` option correspond 
[...]
+| `request.template`      | string       | True      | | | Request body 
transformation template. The template uses 
[lua-resty-template](https://github.com/bungle/lua-resty-template) syntax. See 
the [template 
syntax](https://github.com/bungle/lua-resty-template#template-syntax) for more 
details. You can also use auxiliary functions `_escape_json()` and 
`_escape_xml()` to escape special characters such as double quotes, `_body` to 
access request body, and `_ctx` to access context variables.    |
+| `request.template_is_base64`      | boolean       | False    | false | | Set 
to true if the template is base64 encoded.      |
+| `response`      | object       | False      | | | Response body 
transformation configuration.     |
+| `response.input_format`      | string       | False      | | [`xml`,`json`] 
| Response body original media type. If unspecified, the value would be 
determined by the `Content-Type` header to apply the corresponding decoder. If 
the media type is neither `xml` nor `json`, the value would be left unset and 
the transformation template will be directly applied.       |
+| `response.template`      | string       | True      | | | Response body 
transformation template.       |
+| `response.template_is_base64`      | boolean       | False     | false | | 
Set to true if the template is base64 encoded.       |
 
-## Enable Plugin
+## Examples
 
-You can enable the Plugin on a specific Route as shown below:
+The examples below demonstrate how you can configure `body-transformer` for 
different scenarios.
 
 :::note
+
 You can fetch the `admin_key` from `config.yaml` and save to an environment 
variable with the following command:
 
 ```bash
@@ -64,227 +63,547 @@ admin_key=$(yq '.deployment.admin.admin_key[0].key' 
conf/config.yaml | sed 's/"/
 
 :::
 
+The transformation template uses 
[lua-resty-template](https://github.com/bungle/lua-resty-template) syntax. See 
the [template 
syntax](https://github.com/bungle/lua-resty-template#template-syntax) to learn 
more.
+
+You can also use auxiliary functions `_escape_json()` and `_escape_xml()` to 
escape special characters such as double quotes, `_body` to access request 
body, and `_ctx` to access context variables.
+
+In all cases, you should ensure that the transformation template is a valid 
JSON string.
+
+### Transform between JSON and XML SOAP
+
+The following example demonstrates how to transform the request body from JSON 
to XML and the response body from XML to JSON when working with a SOAP Upstream 
service.
+
+Start the sample SOAP service:
+
 ```shell
-curl http://127.0.0.1:9180/apisix/admin/routes/test_ws \
-    -H "X-API-KEY: $admin_key" -X PUT -d '
+cd /tmp
+git clone https://github.com/spring-guides/gs-soap-service.git
+cd gs-soap-service/complete
+./mvnw spring-boot:run
+```
+
+Create the request and response transformation templates:
+
+```shell
+req_template=$(cat <<EOF | awk '{gsub(/"/,"\\\"");};1' | awk '{$1=$1};1' | tr 
-d '\r\n'
+<?xml version="1.0"?>
+<soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/";>
+ <soap-env:Body>
+  <ns0:getCountryRequest 
xmlns:ns0="http://spring.io/guides/gs-producing-web-service";>
+   <ns0:name>{{_escape_xml(name)}}</ns0:name>
+  </ns0:getCountryRequest>
+ </soap-env:Body>
+</soap-env:Envelope>
+EOF
+)
+
+rsp_template=$(cat <<EOF | awk '{gsub(/"/,"\\\"");};1' | awk '{$1=$1};1' | tr 
-d '\r\n'
+{% if Envelope.Body.Fault == nil then %}
+{
+  "status":"{{_ctx.var.status}}",
+  "currency":"{{Envelope.Body.getCountryResponse.country.currency}}",
+  "population":{{Envelope.Body.getCountryResponse.country.population}},
+  "capital":"{{Envelope.Body.getCountryResponse.country.capital}}",
+  "name":"{{Envelope.Body.getCountryResponse.country.name}}"
+}
+{% else %}
 {
+  "message":{*_escape_json(Envelope.Body.Fault.faultstring[1])*},
+  "code":"{{Envelope.Body.Fault.faultcode}}"
+  {% if Envelope.Body.Fault.faultactor ~= nil then %}
+  , "actor":"{{Envelope.Body.Fault.faultactor}}"
+  {% end %}
+}
+{% end %}
+EOF
+)
+```
+
+`awk` and `tr` are used above to manipulate the template such that the 
template would be a valid JSON string.
+
+Create a Route with `body-transformer` using the templates created previously. 
In the Plugin, set the request input format as JSON, the response input format 
as XML, and the `Content-Type` header to `text/xml` for the Upstream service to 
respond properly:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "body-transformer-route",
     "methods": ["POST"],
     "uri": "/ws",
     "plugins": {
-        "body-transformer": {
-            "request": {
-                "template": "..."
-            },
-            "response": {
-                "template": "..."
-            }
+      "body-transformer": {
+        "request": {
+          "template": "'"$req_template"'",
+          "input_format": "json"
+        },
+        "response": {
+          "template": "'"$rsp_template"'",
+          "input_format": "xml"
         }
+      },
+      "proxy-rewrite": {
+        "headers": {
+          "set": {
+            "Content-Type": "text/xml"
+          }
+        }
+      }
     },
     "upstream": {
-        "type": "roundrobin",
-        "nodes": {
-            "localhost:8080": 1
-        }
+      "type": "roundrobin",
+      "nodes": {
+        "localhost:8080": 1
+      }
     }
-}'
+  }'
 ```
 
-## Configuration description
+:::tip
 
-The `request` and `response` correspond to configurations of request body and 
response body transformation perspectively.
+If it is cumbersome to adjust complex text files to be valid transformation 
templates, you can use the base64 utility to encode the files, such as the 
following:
 
-Specify one of them, or both of them, to fit your need.
+```json
+"body-transformer": {
+  "request": {
+    "template": "'"$(base64 -w0 /path/to/request_template_file)"'"
+  },
+  "response": {
+    "template": "'"$(base64 -w0 /path/to/response_template_file)"'"
+  }
+}
+```
+
+:::
+
+Send a request with a valid JSON body:
+
+```shell
+curl "http://127.0.0.1:9080/ws"; -X POST -d '{"name": "Spain"}'
+```
 
-`request`/`response`:
+The JSON body sent in the request will be transformed into XML before being 
forwarded to the Upstream SOAP service, and the response body will be 
transformed back from XML to JSON.
 
-* `input_format` specifies the body original format:
-  * `xml` (`text/xml`)
-  * `json` (`application/json`)
-* `template` specifies the 
[template](https://github.com/bungle/lua-resty-template) text used by 
transformation.
+You should see a response similar to the following:
 
-**Notes:**
+```json
+{
+  "status": "200",
+  "currency": "EUR",
+  "population": 46704314,
+  "capital": "Madrid",
+  "name": "Spain"
+}
+```
 
-`{{ ... }}` in lua-resty-template will do html-escape, e.g. space character, 
so if it's not what you wish, use `{* ... *}` instead.
+### Modify Request Body
 
-If you do not specify `input_format` and no `Content-Type` header, or body is 
`nil`, then this plugin will not parse the body before template rendering.
-In any case, you could access body string via `{{ _body }}`.
+The following example demonstrates how to dynamically modify the request body.
 
-This is useful for below use cases:
+Create a Route with `body-transformer`, in which the template appends the word 
`world` to the `name` and adds `10` to the `age` to set them as values to `foo` 
and `bar` respectively:
 
-* you wish to generate body from scratch based on Nginx/APISIX variables, even 
if the original body is `nil`.
-* you wish to parse the body string yourself in the template via other lua 
modules, e.g. parse protobuf.
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "body-transformer-route",
+    "uri": "/anything",
+    "plugins": {
+      "body-transformer": {
+        "request": {
+          "template": "{\"foo\":\"{{name .. \" world\"}}\",\"bar\":{{age+10}}}"
+        }
+      }
+    },
+    "upstream": {
+      "type": "roundrobin",
+      "nodes": {
+        "httpbin.org:80": 1
+      }
+    }
+  }'
+```
 
-For example, parse YAML to JSON yourself:
+Send a request to the Route:
 
+```shell
+curl "http://127.0.0.1:9080/anything"; -X POST \
+  -H "Content-Type: application/json" \
+  -d '{"name":"hello","age":20}' \
+  -i
 ```
-{%
-    local yaml = require("lyaml")
-    local body = yaml.load(_body)
-%}
-{"foobar":"{{body.foobar.foo .. " " .. body.foobar.bar}}"}
+
+You should see a response of the following:
+
+```json
+{
+  "args": {},
+  "data": "{\"foo\":\"hello world\",\"bar\":30}",
+  ...
+  "json": {
+    "bar": 30,
+    "foo": "hello world"
+  },
+  "method": "POST",
+  ...
+}
 ```
 
-You must ensure `template` is a valid JSON string, i.e. you need to take care 
of special characters escape, e.g. double quote.
-If it's cumbersome to escape big text file or complex file, you could use 
encode your template text file in base64 format instead.
+### Generate Request Body Using Variables
 
-For example, you could use `base64` command to encode your template text file:
+The following example demonstrates how to generate request body dynamically 
using the `ctx` context variables.
 
-```bash
-curl http://127.0.0.1:9180/apisix/admin/routes/test_ws \
-    -H "X-API-KEY: $admin_key" -X PUT -d '
-{
-    "methods": ["POST"],
-    "uri": "/ws",
+Create a Route with `body-transformer`, in which the template accesses the 
request argument using the [Nginx 
variable](https://nginx.org/en/docs/http/ngx_http_core_module.html) `arg_name`:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "body-transformer-route",
+    "uri": "/anything",
     "plugins": {
-        "body-transformer": {
-            "request": {
-                "template_is_base64": true,
-                "template": "'"$(base64 -w0 /path/to/my_template_file)"'"
-            }
+      "body-transformer": {
+        "request": {
+          "template": "{\"foo\":\"{{_ctx.var.arg_name .. \" world\"}}\"}"
         }
+      }
     },
     "upstream": {
-        "type": "roundrobin",
-        "nodes": {
-            "localhost:8080": 1
-        }
+      "type": "roundrobin",
+      "nodes": {
+        "httpbin.org:80": 1
+      }
     }
-}'
+  }'
 ```
 
-In `template`, you can use below auxiliary functions to escape string to fit 
specific format:
+Send a request to the Route with `name` argument:
 
-* `_escape_json()`
-* `_escape_xml()`
+```shell
+curl -i "http://127.0.0.1:9080/anything?name=hello";
+```
 
-Note that `_escape_json()` would double quote the value of string type, so 
don't repeat double-quote in the template, e.g. 
`{"foobar":{*_escape_json(name)*}}`.
+You should see a response like this:
 
-And, you can refer to `_ctx` to access nginx request context, e.g. `{{ 
_ctx.var.status }}`.
+```json
+{
+  "args": {
+    "name": "hello"
+  },
+  ...,
+  "json": {
+    "foo": "hello world"
+  },
+...
+}
+```
+
+### Transform Body from YAML to JSON
 
-## Example
+The following example demonstrates how to transform request body from YAML to 
JSON.
 
-Let's take a simple SOAP proxy as example.
+Create the request transformation template:
 
-* from downstream to upstream, it transforms the request body from JSON to XML
-* from upstream to downstream, it transforms the response body from XML to JSON
-  * the response `template` distinguishes the normal response from the fault 
response
+```shell
+req_template=$(cat <<EOF | awk '{gsub(/"/,"\\\"");};1'
+{%
+    local yaml = require("tinyyaml")
+    local body = yaml.parse(_body)
+%}
+{"foobar":"{{body.foobar.foo .. " " .. body.foobar.bar}}"}
+EOF
+)
+```
 
-### Run a test web service server
+Create a Route with `body-transformer` that uses the template:
 
-```bash
-cd /tmp
-git clone https://github.com/spring-guides/gs-soap-service.git
-cd gs-soap-service
-./mvnw spring-boot:run
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "body-transformer-route",
+    "uri": "/anything",
+    "plugins": {
+      "body-transformer": {
+        "request": {
+          "template": "'"$req_template"'"
+        }
+      }
+    },
+    "upstream": {
+      "type": "roundrobin",
+      "nodes": {
+        "httpbin.org:80": 1
+      }
+    }
+  }'
 ```
 
-### Test
+Send a request to the Route with a YAML body:
 
-```bash
-req_template=$(cat <<EOF | awk '{gsub(/"/,"\\\"");};1' | awk '{$1=$1};1' | tr 
-d '\r\n'
-<?xml version="1.0"?>
-<soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/";>
- <soap-env:Body>
-  <ns0:getCountryRequest 
xmlns:ns0="http://spring.io/guides/gs-producing-web-service";>
-   <ns0:name>{{_escape_xml(name)}}</ns0:name>
-  </ns0:getCountryRequest>
- </soap-env:Body>
-</soap-env:Envelope>
-EOF
-)
+```shell
+body='
+foobar:
+  foo: hello
+  bar: world'
+
+curl "http://127.0.0.1:9080/anything"; -X POST \
+  -d "$body" \
+  -H "Content-Type: text/yaml" \
+  -i
+```
 
-rsp_template=$(cat <<EOF | awk '{gsub(/"/,"\\\"");};1' | awk '{$1=$1};1' | tr 
-d '\r\n'
-{% if Envelope.Body.Fault == nil then %}
+You should see a response similar to the following, which verifies that the 
YAML body was appropriately transformed to JSON:
+
+```json
 {
-   "status":"{{_ctx.var.status}}",
-   "currency":"{{Envelope.Body.getCountryResponse.country.currency}}",
-   "population":{{Envelope.Body.getCountryResponse.country.population}},
-   "capital":"{{Envelope.Body.getCountryResponse.country.capital}}",
-   "name":"{{Envelope.Body.getCountryResponse.country.name}}"
+  "args": {},
+  "data": "{\"foobar\":\"hello world\"}",
+  ...
+  "json": {
+    "foobar": "hello world"
+  },
+...
 }
-{% else %}
+```
+
+### Transform Form URL Encoded Body to JSON
+
+The following example demonstrates how to transform `form-urlencoded` body to 
JSON.
+
+Create a Route with `body-transformer` which sets the `input_format` to 
`encoded` and configures a template that appends string `world` to the `name` 
input, add `10` to the `age` input:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "body-transformer-route",
+    "uri": "/anything",
+    "plugins": {
+      "body-transformer": {
+        "request": {
+          "input_format": "encoded",
+          "template": "{\"foo\":\"{{name .. \" world\"}}\",\"bar\":{{age+10}}}"
+        }
+      }
+    },
+    "upstream": {
+      "type": "roundrobin",
+      "nodes": {
+        "httpbin.org:80": 1
+      }
+    }
+  }'
+```
+
+Send a POST request to the Route with an encoded body:
+
+```shell
+curl "http://127.0.0.1:9080/anything"; -X POST \
+  -H "Content-Type: application/x-www-form-urlencoded" \
+  -d 'name=hello&age=20'
+```
+
+You should see a response similar to the following:
+
+```json
 {
-   "message":{*_escape_json(Envelope.Body.Fault.faultstring[1])*},
-   "code":"{{Envelope.Body.Fault.faultcode}}"
-   {% if Envelope.Body.Fault.faultactor ~= nil then %}
-   , "actor":"{{Envelope.Body.Fault.faultactor}}"
-   {% end %}
+  "args": {},
+  "data": "",
+  "files": {},
+  "form": {
+    "{\"foo\":\"hello world\",\"bar\":30}": ""
+  },
+  "headers": {
+    ...
+  },
+  ...
 }
-{% end %}
-EOF
-)
+```
 
-curl http://127.0.0.1:9180/apisix/admin/routes/test_ws \
-    -H "X-API-KEY: $admin_key" -X PUT -d '
-{
-    "methods": ["POST"],
-    "uri": "/ws",
+### Transform GET Request Query Parameter to Body
+
+The following example demonstrates how to transform a GET request query 
parameter to request body. Note that this does not transform the HTTP method. 
To transform the method, see [`proxy-rewrite`](./proxy-rewrite.md).
+
+Create a Route with `body-transformer`, which sets the `input_format` to 
`args` and configures a template that adds a message to the request:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "body-transformer-route",
+    "uri": "/anything",
     "plugins": {
-        "proxy-rewrite": {
-            "headers": {
-                "set": {
-                    "Accept-Encoding": "identity",
-                    "Content-Type": "text/xml"
-                }
-            }
-        },
-        "response-rewrite": {
-            "headers": {
-                "set": {
-                    "Content-Type": "application/json"
-                }
-            }
-        },
-        "body-transformer": {
-            "request": {
-                "template": "'"$req_template"'"
-            },
-            "response": {
-                "template": "'"$rsp_template"'"
-            }
+      "body-transformer": {
+        "request": {
+          "input_format": "args",
+          "template": "{\"message\": \"hello {{name}}\"}"
         }
+      }
     },
     "upstream": {
-        "type": "roundrobin",
-        "nodes": {
-            "localhost:8080": 1
-        }
+      "type": "roundrobin",
+      "nodes": {
+        "httpbin.org:80": 1
+      }
     }
-}'
+  }'
+```
+
+Send a GET request to the Route:
 
-curl -s http://127.0.0.1:9080/ws -H 'content-type: application/json' -X POST 
-d '{"name": "Spain"}' | jq
+```shell
+curl "http://127.0.0.1:9080/anything?name=john";
+```
+
+You should see a response similar to the following:
+
+```json
 {
-  "status": "200",
-  "currency": "EUR",
-  "population": 46704314,
-  "capital": "Madrid",
-  "name": "Spain"
+  "args": {},
+  "data": "{\"message\": \"hello john\"}",
+  "files": {},
+  "form": {},
+  "headers": {
+    ...
+  },
+  "json": {
+    "message": "hello john"
+  },
+  "method": "GET",
+  ...
 }
+```
+
+### Transform Plain Media Type
+
+The following example demonstrates how to transform requests with `plain` 
media type.
+
+Create a Route with `body-transformer`, which sets the `input_format` to 
`plain` and configures a template to remove `not` and a subsequent space from 
the body string:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "body-transformer-route",
+    "uri": "/anything",
+    "plugins": {
+      "body-transformer": {
+        "request": {
+          "input_format": "plain",
+          "template": "{\"message\": \"{* string.gsub(_body, \"not \", \"\") 
*}\"}"
+        }
+      }
+    },
+    "upstream": {
+      "type": "roundrobin",
+      "nodes": {
+        "httpbin.org:80": 1
+      }
+    }
+  }'
+```
+
+Send a POST request to the Route:
+
+```shell
+curl "http://127.0.0.1:9080/anything"; -X POST \
+  -d 'not actually json' \
+  -i
+```
+
+You should see a response similar to the following:
 
-# Fault response
-curl -s http://127.0.0.1:9080/ws -H 'content-type: application/json' -X POST 
-d '{"name": "Spain"}' | jq
+```json
 {
-  "message": "Your name is required.",
-  "code": "SOAP-ENV:Server"
+  "args": {},
+  "data": "",
+  "files": {},
+  "form": {
+    "{\"message\": \"actually json\"}": ""
+  },
+  "headers": {
+    ...
+  },
+  ...
 }
 ```
 
-## Delete Plugin
+### Transform Multipart Media Type
 
-To remove the `body-transformer` Plugin, you can delete the corresponding JSON 
configuration from the Plugin configuration. APISIX will automatically reload 
and you do not have to restart for this to take effect.
+The following example demonstrates how to transform requests with `multipart` 
media type.
+
+Create a request transformation template which adds a `status` to the body 
based on the `age` provided in the request body:
 
 ```shell
-curl http://127.0.0.1:9180/apisix/admin/routes/test_ws \
-    -H "X-API-KEY: $admin_key" -X PUT -d '
-{
-    "methods": ["POST"],
-    "uri": "/ws",
-    "plugins": {},
-    "upstream": {
-        "type": "roundrobin",
-        "nodes": {
-            "localhost:8080": 1
+req_template=$(cat <<EOF | awk '{gsub(/"/,"\\\"");};1'
+{%
+  local core = require 'apisix.core'
+  local cjson = require 'cjson'
+
+  if tonumber(context.age) > 18 then
+      context._multipart:set_simple("status", "adult")
+  else
+      context._multipart:set_simple("status", "minor")
+  end
+
+  local body = context._multipart:tostring()
+%}{* body *}
+EOF
+)
+```
+
+Create a Route with `body-transformer`, which sets the `input_format` to 
`multipart` and uses the previously created request template for transformation:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "body-transformer-route",
+    "uri": "/anything",
+    "plugins": {
+      "body-transformer": {
+        "request": {
+          "input_format": "multipart",
+          "template": "'"$req_template"'"
         }
+      }
+    },
+    "upstream": {
+      "type": "roundrobin",
+      "nodes": {
+        "httpbin.org:80": 1
+      }
     }
-}'
+  }'
+```
+
+Send a multipart POST request to the Route:
+
+```shell
+curl -X POST \
+  -F "name=john" \
+  -F "age=10" \
+  "http://127.0.0.1:9080/anything";
+```
+
+You should see a response similar to the following:
+
+```json
+{
+  "args": {},
+  "data": "",
+  "files": {},
+  "form": {
+    "age": "10",
+    "name": "john",
+    "status": "minor"
+  },
+  "headers": {
+    "Accept": "*/*",
+    "Content-Length": "361",
+    "Content-Type": "multipart/form-data; 
boundary=------------------------qtPjk4c8ZjmGOXNKzhqnOP",
+    ...
+  },
+  ...
+}
 ```
diff --git a/docs/zh/latest/config.json b/docs/zh/latest/config.json
index 84b506f3a..b463a59fd 100644
--- a/docs/zh/latest/config.json
+++ b/docs/zh/latest/config.json
@@ -82,6 +82,7 @@
             "plugins/grpc-web",
             "plugins/fault-injection",
             "plugins/mocking",
+            "plugins/body-transformer",
             "plugins/attach-consumer-label"
           ]
         },
diff --git a/docs/zh/latest/plugins/body-transformer.md 
b/docs/zh/latest/plugins/body-transformer.md
new file mode 100644
index 000000000..701efa410
--- /dev/null
+++ b/docs/zh/latest/plugins/body-transformer.md
@@ -0,0 +1,609 @@
+---
+title: body-transformer
+keywords:
+  - Apache APISIX
+  - API 网关
+  - Plugin
+  - BODY TRANSFORMER
+  - body-transformer
+description: body-transformer 插件执行基于模板的转换,将请求和/或响应主体从一种格式转换为另一种格式,例如从 JSON 到 
JSON、从 JSON 到 HTML 或从 XML 到 YAML。
+---
+
+<!--
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+-->
+
+<head>
+  <link rel="canonical" href="https://docs.api7.ai/hub/body-transformer"; />
+</head>
+
+## 描述
+
+`body-transformer` 插件执行基于模板的转换,将请求和/或响应主体从一种格式转换为另一种格式,例如从 JSON 到 JSON、从 JSON 
到 HTML 或从 XML 到 YAML。
+
+## 属性
+
+| 名称           | 类型                   | 必选项   | 默认值           | 有效值 | 描述       
                                                                                
                                                  |
+|--------------|----------------------|-------|---------------|--------------|--------------------------------------------------------------------------------------------------------------------------------------------|
+| `request` | object | 否 | | | 请求体转换配置。 |
+| `request.input_format` | string | 否 | | 
[`xml`,`json`,`encoded`,`args`,`plain`,`multipart`] | 请求体原始媒体类型。若未指定,则该值将由 
`Content-Type` 标头确定以应用相应的解码器。`xml` 选项对应于 `text/xml` 媒体类型。`json` 选项对应于 
`application/json` 媒体类型。`encoded` 选项对应于 `application/x-www-form-urlencoded` 
媒体类型。`args` 选项对应于 GET 请求。`plain` 选项对应于 `text/plain` 媒体类型。`multipart` 选项对应于 
`multipart/related` 媒体类型。如果媒体类型不是这两种类型,则该值将保留未设置状态并直接应用转换模板。 |
+| `request.template` | string | True | | | 请求体转换模板。模板使用 
[lua-resty-template](https://github.com/bungle/lua-resty-template) 
语法。有关更多详细信息,请参阅 
[模板语法](https://github.com/bungle/lua-resty-template#template-syntax)。您还可以使用辅助函数 
`_escape_json()` 和 `_escape_xml()` 转义双引号等特殊字符,使用 `_body` 访问请求正文,使用 `_ctx` 
访问上下文变量。|
+| `request.template_is_base64` | boolean | 否 | false | | 如果模板是 base64 编码的,则设置为 
true。|
+| `response` | object | 否 | | | 响应体转换配置。|
+| `response.input_format` | string | 否 | | [`xml`,`json`] | 
响应体原始媒体类型。如果未指定,则该值将由 `Content-Type` 标头确定以应用相应的解码器。如果媒体类型既不是 `xml` 也不是 
`json`,则该值将保留未设置状态,并直接应用转换模板。|
+| `response.template` | string | True | | | 响应主体转换模板。|
+| `response.template_is_base64` | boolean | 否 | false | | 如果模板是 base64 
编码的,则设置为 true。|
+
+## 示例
+
+以下示例演示了如何针对不同场景配置 `body-transformer`。
+
+:::note
+
+您可以这样从 `config.yaml` 中获取 `admin_key` 并存入环境变量:
+
+```bash
+admin_key=$(yq '.deployment.admin.admin_key[0].key' conf/config.yaml | sed 
's/"//g')
+```
+
+:::
+
+转换模板使用 [lua-resty-template](https://github.com/bungle/lua-resty-template) 
语法。请参阅 [模板语法](https://github.com/bungle/lua-resty-template#template-syntax) 
了解更多信息。
+
+您还可以使用辅助函数 `_escape_json()` 和 `_escape_xml()` 转义特殊字符(例如双引号)、`_body` 访问请求正文以及 
`_ctx` 访问上下文变量。
+
+在所有情况下,您都应确保转换模板是有效的 JSON 字符串。
+
+### JSON 和 XML SOAP 之间的转换
+
+以下示例演示了在使用 SOAP 上游服务时如何将请求主体从 JSON 转换为 XML,将响应主体从 XML 转换为 JSON。
+
+启动示例 SOAP 服务:
+
+```shell
+cd /tmp
+git clone https://github.com/spring-guides/gs-soap-service.git
+cd gs-soap-service/complete
+./mvnw spring-boot:run
+```
+
+创建请求和响应转换模板:
+
+```shell
+req_template=$(cat <<EOF | awk '{gsub(/"/,"\\\"");};1' | awk '{$1=$1};1' | tr 
-d '\r\n'
+<?xml version="1.0"?>
+<soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/";>
+ <soap-env:Body>
+  <ns0:getCountryRequest 
xmlns:ns0="http://spring.io/guides/gs-producing-web-service";>
+   <ns0:name>{{_escape_xml(name)}}</ns0:name>
+  </ns0:getCountryRequest>
+ </soap-env:Body>
+</soap-env:Envelope>
+EOF
+)
+
+rsp_template=$(cat <<EOF | awk '{gsub(/"/,"\\\"");};1' | awk '{$1=$1};1' | tr 
-d '\r\n'
+{% if Envelope.Body.Fault == nil then %}
+{
+  "status":"{{_ctx.var.status}}",
+  "currency":"{{Envelope.Body.getCountryResponse.country.currency}}",
+  "population":{{Envelope.Body.getCountryResponse.country.population}},
+  "capital":"{{Envelope.Body.getCountryResponse.country.capital}}",
+  "name":"{{Envelope.Body.getCountryResponse.country.name}}"
+}
+{% else %}
+{
+  "message":{*_escape_json(Envelope.Body.Fault.faultstring[1])*},
+  "code":"{{Envelope.Body.Fault.faultcode}}"
+  {% if Envelope.Body.Fault.faultactor ~= nil then %}
+  , "actor":"{{Envelope.Body.Fault.faultactor}}"
+  {% end %}
+}
+{% end %}
+EOF
+)
+```
+
+上面使用了 `awk` 和 `tr` 来操作模板,使模板成为有效的 JSON 字符串。
+
+使用之前创建的模板创建带有 `body-transformer` 的路由。在插件中,将请求输入格式设置为 JSON,将响应输入格式设置为 XML,并将 
`Content-Type` 标头设置为 `text/xml`,以便上游服务正确响应:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "body-transformer-route",
+    "methods": ["POST"],
+    "uri": "/ws",
+    "plugins": {
+      "body-transformer": {
+        "request": {
+          "template": "'"$req_template"'",
+          "input_format": "json"
+        },
+        "response": {
+          "template": "'"$rsp_template"'",
+          "input_format": "xml"
+        }
+      },
+      "proxy-rewrite": {
+        "headers": {
+          "set": {
+            "Content-Type": "text/xml"
+          }
+        }
+      }
+    },
+    "upstream": {
+      "type": "roundrobin",
+      "nodes": {
+        "localhost:8080": 1
+      }
+    }
+  }'
+```
+
+:::tip
+
+如果将复杂的文本文件调整为有效的转换模板很麻烦,则可以使用 base64 实用程序对文件进行编码,例如以下内容:
+
+```json
+"body-transformer": {
+  "request": {
+    "template": "'"$(base64 -w0 /path/to/request_template_file)"'"
+  },
+  "response": {
+    "template": "'"$(base64 -w0 /path/to/response_template_file)"'"
+  }
+}
+```
+
+:::
+
+发送具有有效 JSON 主体的请求:
+
+```shell
+curl "http://127.0.0.1:9080/ws"; -X POST -d '{"name": "Spain"}'
+```
+
+请求中发送的 JSON 主体将在转发到上游 SOAP 服务之前转换为 XML,响应主体将从 XML 转换回 JSON。
+
+您应该会看到类似以下内容的响应:
+
+```json
+{
+  "status": "200",
+  "currency": "EUR",
+  "population": 46704314,
+  "capital": "Madrid",
+  "name": "Spain"
+}
+```
+
+### 修改请求体
+
+以下示例演示了如何动态修改请求体。
+
+使用 `body-transformer` 创建一个路由,其中​​模板将单词 `world` 附加到 `name`,并将 `10` 添加到 
`age`,以将它们分别设置为 `foo` 和 `bar` 的值:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "body-transformer-route",
+    "uri": "/anything",
+    "plugins": {
+      "body-transformer": {
+        "request": {
+          "template": "{\"foo\":\"{{name .. \" world\"}}\",\"bar\":{{age+10}}}"
+        }
+      }
+    },
+    "upstream": {
+      "type": "roundrobin",
+      "nodes": {
+        "httpbin.org:80": 1
+      }
+    }
+  }'
+```
+
+向路线发送请求:
+
+```shell
+curl "http://127.0.0.1:9080/anything"; -X POST \
+  -H "Content-Type: application/json" \
+  -d '{"name":"hello","age":20}' \
+  -i
+```
+
+您应该看到以下响应:
+
+```json
+{
+  "args": {},
+  "data": "{\"foo\":\"hello world\",\"bar\":30}",
+  ...
+  "json": {
+    "bar": 30,
+    "foo": "hello world"
+  },
+  "method": "POST",
+  ...
+}
+```
+
+### 使用变量生成请求主体
+
+以下示例演示如何使用 `ctx` 上下文变量动态生成请求主体。
+
+使用 `body-transformer` 创建路由,其中​​模板使用 [Nginx 
变量](https://nginx.org/en/docs/http/ngx_http_core_module.html) `arg_name` 访问请求参数:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "body-transformer-route",
+    "uri": "/anything",
+    "plugins": {
+      "body-transformer": {
+        "request": {
+          "template": "{\"foo\":\"{{_ctx.var.arg_name .. \" world\"}}\"}"
+        }
+      }
+    },
+    "upstream": {
+      "type": "roundrobin",
+      "nodes": {
+        "httpbin.org:80": 1
+      }
+    }
+  }'
+```
+
+使用 `name` 参数向路由发送请求:
+
+```shell
+curl -i "http://127.0.0.1:9080/anything?name=hello";
+```
+
+您应该看到如下响应:
+
+```json
+{
+  "args": {
+    "name": "hello"
+  },
+  ...,
+  "json": {
+    "foo": "hello world"
+  },
+...
+}
+```
+
+### 将正文从 YAML 转换为 JSON
+
+以下示例演示如何将请求正文从 YAML 转换为 JSON。
+
+创建请求转换模板:
+
+```shell
+req_template=$(cat <<EOF | awk '{gsub(/"/,"\\\"");};1'
+{%
+    local yaml = require("tinyyaml")
+    local body = yaml.parse(_body)
+%}
+{"foobar":"{{body.foobar.foo .. " " .. body.foobar.bar}}"}
+EOF
+)
+```
+
+使用以下模板创建一个带有 `body-transformer` 的路由:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "body-transformer-route",
+    "uri": "/anything",
+    "plugins": {
+      "body-transformer": {
+        "request": {
+          "template": "'"$req_template"'"
+        }
+      }
+    },
+    "upstream": {
+      "type": "roundrobin",
+      "nodes": {
+        "httpbin.org:80": 1
+      }
+    }
+  }'
+```
+
+使用 YAML 主体向路由发送请求:
+
+```shell
+body='
+foobar:
+  foo: hello
+  bar: world'
+
+curl "http://127.0.0.1:9080/anything"; -X POST \
+  -d "$body" \
+  -H "Content-Type: text/yaml" \
+  -i
+```
+
+您应该会看到类似以下内容的响应,这验证了 YAML 主体已适当地转换为 JSON:
+
+```json
+{
+  "args": {},
+  "data": "{\"foobar\":\"hello world\"}",
+  ...
+  "json": {
+    "foobar": "hello world"
+  },
+...
+}
+```
+
+### 将表单 URL 编码主体转换为 JSON
+
+以下示例演示如何将 `form-urlencoded` 主体转换为 JSON。
+
+使用 `body-transformer` 创建路由,将 `input_format` 设置为 `encoded`,并配置一个模板,将字符串 `world` 
附加到 `name` 输入,将 `10` 添加到 `age` 输入:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "body-transformer-route",
+    "uri": "/anything",
+    "plugins": {
+      "body-transformer": {
+        "request": {
+          "input_format": "encoded",
+          "template": "{\"foo\":\"{{name .. \" world\"}}\",\"bar\":{{age+10}}}"
+        }
+      }
+    },
+    "upstream": {
+      "type": "roundrobin",
+      "nodes": {
+        "httpbin.org:80": 1
+      }
+    }
+  }'
+```
+
+向路由发送一个带有编码主体的 POST 请求:
+
+```shell
+curl "http://127.0.0.1:9080/anything"; -X POST \
+  -H "Content-Type: application/x-www-form-urlencoded" \
+  -d 'name=hello&age=20'
+```
+
+您应该会看到类似以下内容的响应:
+
+```json
+{
+  "args": {},
+  "data": "",
+  "files": {},
+  "form": {
+    "{\"foo\":\"hello world\",\"bar\":30}": ""
+  },
+  "headers": {
+    ...
+  },
+  ...
+}
+```
+
+### 将 GET 请求查询参数转换为正文
+
+以下示例演示如何将 GET 请求查询参数转换为请求正文。请注意,这不会转换 HTTP 方法。要转换方法,请参阅 
[`proxy-rewrite`](./proxy-rewrite.md)。
+
+使用 `body-transformer` 创建路由,将 `input_format` 设置为 `args`,并配置一个向请求添加消息的模板:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "body-transformer-route",
+    "uri": "/anything",
+    "plugins": {
+      "body-transformer": {
+        "request": {
+          "input_format": "args",
+          "template": "{\"message\": \"hello {{name}}\"}"
+        }
+      }
+    },
+    "upstream": {
+      "type": "roundrobin",
+      "nodes": {
+        "httpbin.org:80": 1
+      }
+    }
+  }'
+```
+
+向路线发送 GET 请求:
+
+```shell
+curl "http://127.0.0.1:9080/anything?name=john";
+```
+
+您应该会看到类似以下内容的响应:
+
+```json
+{
+  "args": {},
+  "data": "{\"message\": \"hello john\"}",
+  "files": {},
+  "form": {},
+  "headers": {
+    ...
+  },
+  "json": {
+    "message": "hello john"
+  },
+  "method": "GET",
+  ...
+}
+```
+
+### 转换纯文本媒体类型
+
+以下示例演示如何转换具有 `plain` 媒体类型的请求。
+
+使用 `body-transformer` 创建路由,将 `input_format` 设置为 `plain`,并配置模板以从正文字符串中删除 `not` 
和后续空格:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "body-transformer-route",
+    "uri": "/anything",
+    "plugins": {
+      "body-transformer": {
+        "request": {
+          "input_format": "plain",
+          "template": "{\"message\": \"{* string.gsub(_body, \"not \", \"\") 
*}\"}"
+        }
+      }
+    },
+    "upstream": {
+      "type": "roundrobin",
+      "nodes": {
+        "httpbin.org:80": 1
+      }
+    }
+  }'
+```
+
+向路由发送 POST 请求:
+
+```shell
+curl "http://127.0.0.1:9080/anything"; -X POST \
+  -d 'not actually json' \
+  -i
+```
+
+您应该会看到类似以下内容的响应:
+
+```json
+{
+  "args": {},
+  "data": "",
+  "files": {},
+  "form": {
+    "{\"message\": \"actually json\"}": ""
+  },
+  "headers": {
+    ...
+  },
+  ...
+}
+```
+
+### 转换多部分媒体类型
+
+以下示例演示如何转换具有 `multipart` 媒体类型的请求。
+
+创建一个请求转换模板,该模板根据请求正文中提供的 `age` 向正文添加 `status`:
+
+```shell
+req_template=$(cat <<EOF | awk '{gsub(/"/,"\\\"");};1'
+{%
+  local core = require 'apisix.core'
+  local cjson = require 'cjson'
+
+  if tonumber(context.age) > 18 then
+      context._multipart:set_simple("status", "adult")
+  else
+      context._multipart:set_simple("status", "minor")
+  end
+
+  local body = context._multipart:tostring()
+%}{* body *}
+EOF
+)
+```
+
+创建一个带有 `body-transformer` 的路由,将 `input_format` 设置为 
`multipart`,并使用之前创建的请求模板进行转换:
+
+```shell
+curl "http://127.0.0.1:9180/apisix/admin/routes"; -X PUT \
+  -H "X-API-KEY: ${admin_key}" \
+  -d '{
+    "id": "body-transformer-route",
+    "uri": "/anything",
+    "plugins": {
+      "body-transformer": {
+        "request": {
+          "input_format": "multipart",
+          "template": "'"$req_template"'"
+        }
+      }
+    },
+    "upstream": {
+      "type": "roundrobin",
+      "nodes": {
+        "httpbin.org:80": 1
+      }
+    }
+  }'
+```
+
+向路由发送多部分 POST 请求:
+
+```shell
+curl -X POST \
+  -F "name=john" \
+  -F "age=10" \
+  "http://127.0.0.1:9080/anything";
+```
+
+您应该会看到类似以下内容的响应:
+
+```json
+{
+  "args": {},
+  "data": "",
+  "files": {},
+  "form": {
+    "age": "10",
+    "name": "john",
+    "status": "minor"
+  },
+  "headers": {
+    "Accept": "*/*",
+    "Content-Length": "361",
+    "Content-Type": "multipart/form-data; 
boundary=------------------------qtPjk4c8ZjmGOXNKzhqnOP",
+    ...
+  },
+  ...
+}
+```


Reply via email to