跳到主要内容

body-transformer

body-transformer 插件使用模板在不同数据格式之间转换请求体和响应体。你可以单独转换请求或响应,也可以在同一请求流程中同时转换两者。

示例​

仅使用 mocking 的示例会在不联系上游的情况下生成响应。这些示例的 ADC 和 Gateway API 配置仍包含常规后端,但 mocking 会在请求到达后端前响应。其他转换示例依赖实际的上游响应。

以下示例演示了如何在不同场景下配置 body-transformer。

转换模板使用 lua-resty-template 语法。有关详细信息,请参阅模板语法。

你还可以使用辅助函数 _escape_json() 和 _escape_xml() 来转义双引号等特殊字符,使用 _body 访问请求体,使用 _ctx 访问上下文变量。

使用基于 JSON 的配置时,请将转换模板编码为有效的 JSON 字符串。

在 JSON 和 XML SOAP 之间转换​

以下示例演示如何将 JSON 请求转换为 SOAP 信封,并将 SOAP 响应转换回 JSON。示例使用 WireMock 提供确定性的 SOAP 响应,无需依赖持续变化的应用仓库。

启动 SOAP 上游​

对于 Admin API 和 ADC 示例,使用 Docker 配置 WireMock 固定响应;对于 Ingress Controller 示例,将其部署到 Kubernetes。

为 WireMock 的映射和响应体创建目录:

mkdir -p body-transformer-wiremock/mappings body-transformer-wiremock/__files

创建请求映射:

cat > body-transformer-wiremock/mappings/country.json <<'EOF'
{
"request": {
"method": "POST",
"urlPath": "/services",
"bodyPatterns": [
{
"matchesXPath": "//*[local-name()='getCountryRequest']/*[local-name()='name' and text()='Spain']"
}
]
},
"response": {
"status": 200,
"headers": {
"Content-Type": "text/xml; charset=utf-8"
},
"bodyFileName": "country-response.xml"
}
}
EOF

创建映射返回的 SOAP 响应体:

cat > body-transformer-wiremock/__files/country-response.xml <<'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<ns2:getCountryResponse xmlns:ns2="https://spring.io/guides/gs-producing-web-service">
<ns2:country>
<ns2:name>Spain</ns2:name>
<ns2:population>46704314</ns2:population>
<ns2:capital>Madrid</ns2:capital>
<ns2:currency>EUR</ns2:currency>
</ns2:country>
</ns2:getCountryResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
EOF

将 GATEWAY_CONTAINER 设置为正在运行的 APISIX 或 API7 网关(API7 Gateway)容器名称,然后将网关和 WireMock 加入专用网络:

export GATEWAY_CONTAINER=replace-with-gateway-container-name

docker network create gateway-body-transformer-net
docker network connect gateway-body-transformer-net "$GATEWAY_CONTAINER"

docker run -d \
--name body-transformer-soap \
--network gateway-body-transformer-net \
-v "$PWD/body-transformer-wiremock:/home/wiremock:ro" \
wiremock/wiremock:3.13.2

配置路由​

创建请求和响应转换模板:

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="https://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 的路由:

curl "http://127.0.0.1:9180/apisix/admin/routes/body-transformer-soap" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d @- <<EOF
{
"methods": ["POST"],
"uri": "/services",
"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": {
"body-transformer-soap:8080": 1
}
}
}
EOF

❶ 将请求输入格式设置为 JSON,以便插件在内部应用 JSON 解码器。

❷ 将响应输入格式设置为 XML,以便插件在内部应用 XML 解码器。

❸ 将 Content-Type 头设置为 text/xml,以便上游服务正确响应。

❹ Admin API 和 ADC 示例使用 WireMock 容器地址;Ingress Controller 示例使用 Kubernetes Service 地址。

提示

对于较大的模板,请将每个文件编码为可移植的单行 base64 值:

request_template=$(base64 < request-template.txt | tr -d '\n')
response_template=$(base64 < response-template.txt | tr -d '\n')

将各个 template 字段设置为对应的编码值,并将 template_is_base64 设置为 true。

验证​

发送带有有效 JSON 体的请求:

curl "http://127.0.0.1:9080/services" -X POST -d '{"name": "Spain"}'

插件先将 JSON 请求转换为 XML,再将其转发到 SOAP 上游;随后将 XML 响应转换回 JSON。

你应该看到类似于以下的响应:

{
"status": "200",
"currency": "EUR",
"population": 46704314,
"capital": "Madrid",
"name": "Spain"
}

修改请求体​

以下示例演示了如何动态修改请求体。

创建一个带有 body-transformer 的路由:

curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
-H "X-API-KEY: ${ADMIN_API_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
}
}
}'

❶ 设置一个模板,将 "world" 追加到 name,并将 10 加到 age,然后将它们分别设置为 "foo" 和 "bar" 的值。

发送请求到路由:

curl "http://127.0.0.1:9080/anything" -X POST \
-H "Content-Type: application/json" \
-d '{"name":"hello","age":20}' \
-i

你应该看到以下响应:

{
"args": {},
"data": "{\"foo\":\"hello world\",\"bar\":30}",
...
"json": {
"bar": 30,
"foo": "hello world"
},
"method": "POST",
...
}

使用变量生成请求体​

以下示例演示了如何使用 ctx 上下文变量动态生成请求体。

创建一个带有 body-transformer 的路由:

curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
-H "X-API-KEY: ${ADMIN_API_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
}
}
}'

❶ 设置一个模板,使用 NGINX 变量 arg_name 访问请求参数。

发送带有 name 参数的请求到路由:

curl -i "http://127.0.0.1:9080/anything?name=hello"

你应该看到像这样的响应:

{
"args": {
"name": "hello"
},
...,
"json": {
"foo": "hello world"
},
...
}

将请求体从 YAML 转换为 JSON​

以下示例演示了如何将请求体从 YAML 转换为 JSON。

创建请求转换模板:

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 的路由:

curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
--data-binary @- <<EOF
{
"id": "body-transformer-route",
"uri": "/anything",
"plugins": {
"body-transformer": {
"request": {
"template": "$req_template"
}
}
},
"upstream": {
"type": "roundrobin",
"nodes": {
"httpbin.org:80": 1
}
}
}
EOF

发送带有 YAML 体的请求到路由:

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:

{
"args": {},
"data": "{\"foobar\":\"hello world\"}",
...
"json": {
"foobar": "hello world"
},
...
}

将表单 URL 编码请求体转换为 JSON​

以下示例演示了如何将 form-urlencoded 体转换为 JSON。

创建一个带有 body-transformer 的路由如下:

curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
-H "X-API-KEY: ${ADMIN_API_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
}
}
}'

❶ 将 input_format 设置为 encoded。

❷ 设置一个模板,将字符串 world 追加到 name 输入,将 10 加到 age 输入,并形成一个新的 JSON 对象。

发送一个带有 encoded 体的 POST 请求到路由:

curl "http://127.0.0.1:9080/anything" -X POST \
-H "Content-Type: application/x-www-form-urlencoded" \
-d 'name=hello&age=20'

你应该看到类似于以下的响应:

{
"args": {},
"data": "",
"files": {},
"form": {
"{\"foo\":\"hello world\",\"bar\":30}": ""
},
"headers": {
...
},
...
}

将 GET 请求查询参数转换为请求体​

以下示例演示了如何将 GET 请求查询参数转换为请求体。请注意,这不会转换 HTTP 方法。要转换方法,请参阅 proxy-rewrite。

创建一个带有 body-transformer 的路由如下:

curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
-H "X-API-KEY: ${ADMIN_API_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
}
}
}'

❶ 将 input_format 设置为 args。

❷ 设置一个向请求添加消息的模板。

发送 GET 请求到路由:

curl "http://127.0.0.1:9080/anything?name=john"

你应该看到类似于以下的响应:

{
"args": {},
"data": "{\"message\": \"hello john\"}",
"files": {},
"form": {},
"headers": {
...
},
"json": {
"message": "hello john"
},
"method": "GET",
...
}

转换纯文本媒体类型​

以下示例演示了如何转换带有 plain 媒体类型的请求。

创建一个带有 body-transformer 的路由如下:

curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
-H "X-API-KEY: ${ADMIN_API_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
}
}
}'

❶ 将 input_format 设置为 plain。

❷ 设置一个模板,从体字符串中删除 not 和随后的空格。

发送一个 POST 请求到路由:

curl "http://127.0.0.1:9080/anything" -X POST \
-d 'not actually json' \
-i

你应该看到类似于以下的响应:

{
"args": {},
"data": "",
"files": {},
"form": {
"{\"message\": \"actually json\"}": ""
},
"headers": {
...
},
...
}

转换 Multipart 媒体类型​

以下示例演示了如何转换带有 multipart 媒体类型的请求。

创建一个请求转换模板,根据请求体中提供的 age 向 body 添加 status:

req_template=$(cat <<EOF | awk '{gsub(/"/,"\\\"");};1'
{%
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 的路由如下:

curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
--data-binary @- <<EOF
{
"id": "body-transformer-route",
"uri": "/anything",
"plugins": {
"body-transformer": {
"request": {
"input_format": "multipart",
"template": "$req_template"
}
}
},
"upstream": {
"type": "roundrobin",
"nodes": {
"httpbin.org:80": 1
}
}
}
EOF

❶ 将 input_format 设置为 multipart。

❷ 设置为之前创建的请求模板。

发送一个 multipart POST 请求到路由:

curl -X POST \
-F "name=john" \
-F "age=10" \
"http://127.0.0.1:9080/anything"

你应该看到类似于以下的响应:

{
"args": {},
"data": "",
"files": {},
"form": {
"age": "10",
"name": "john",
"status": "minor"
},
"headers": {
"Accept": "*/*",
"Content-Length": "361",
"Content-Type": "multipart/form-data; boundary=------------------------qtPjk4c8ZjmGOXNKzhqnOP",
...
},
...
}

基于消费者身份转换响应体​

以下示例演示了如何根据不同的消费者身份自定义响应体转换。该示例展示了如何向不同的消费者返回不同的响应格式,同时过滤敏感字段并重命名属性。

创建响应转换模板,该模板根据消费者身份应用不同的转换:

rsp_template=$(cat <<EOF | awk '{gsub(/"/,"\\\"");};1' | awk '{$1=$1};1' | tr -d '\r\n'
{% local consumer_name = _ctx.consumer and _ctx.consumer.username or "" %}
{% if consumer_name == "consumer-a" then %}
{
"user_id": {* user_id *},
"display_name": {* _escape_json(username) *},
"email": {* _escape_json(email) *}
}
{% elseif consumer_name == "consumer-b" then %}
{
"user_id": {* user_id *},
"email": {* _escape_json(email) *},
"balance": {* balance *}
}
{% else %}
{* _body *}
{% end %}
EOF
)

创建三个配置了 key-auth 的消费者:

curl "http://127.0.0.1:9180/apisix/admin/consumers" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"username": "consumer-a",
"plugins": {
"key-auth": {
"key": "consumer-a"
}
}
}'

curl "http://127.0.0.1:9180/apisix/admin/consumers" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"username": "consumer-b",
"plugins": {
"key-auth": {
"key": "consumer-b"
}
}
}'

curl "http://127.0.0.1:9180/apisix/admin/consumers" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"username": "consumer-c",
"plugins": {
"key-auth": {
"key": "consumer-c"
}
}
}'

创建一个带有 body-transformer、key-auth 和 mocking 插件的路由:

curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
--data-binary @- <<EOF
{
"id": "body-transformer-route",
"uri": "/mock",
"plugins": {
"key-auth": {},
"mocking": {
"response_example": "{\"user_id\":1001,\"username\":\"john_doe\",\"email\":\"john@example.com\",\"phone\":\"+1-555-0123\",\"balance\":1250.50}"
},
"body-transformer": {
"response": {
"input_format": "json",
"template": "$rsp_template"
}
}
}
}
EOF

❶ 配置 mocking 插件返回示例上游响应。

❷ 将响应输入格式设置为 JSON。

❸ 设置根据消费者身份自定义响应的转换模板。

发送带有不同 apikey 头的请求以验证响应转换:

以 consumer-a 身份发送请求:

curl "http://127.0.0.1:9080/mock" -H "apikey: consumer-a"

你应该看到类似于以下的响应,展示了这些转换:

  • username 字段已重命名为 display_name
  • 敏感的 phone 和 balance 字段已被过滤掉
{
"user_id": 1001,
"display_name": "john_doe",
"email": "john@example.com"
}

以 consumer-b 身份发送请求:

curl "http://127.0.0.1:9080/mock" -H "apikey: consumer-b"

你应该看到类似于以下的响应,展示了这些转换:

  • username 和 phone 字段已被过滤掉
  • balance 字段被保留
{
"user_id": 1001,
"email": "john@example.com",
"balance": 1250.50
}

以 consumer-c 身份发送请求:

curl "http://127.0.0.1:9080/mock" -H "apikey: consumer-c"

你应该看到类似于以下的响应,显示原始响应被原样返回:

{
"user_id": 1001,
"username": "john_doe",
"email": "john@example.com",
"phone": "+1-555-0123",
"balance": 1250.50
}

基于消费者身份转换嵌套响应体​

以下示例演示了如何根据不同的消费者身份自定义响应体转换。该示例展示了如何提取嵌套字段、重组数据结构并扁平化嵌套对象,同时根据消费者身份向不同的消费者提供不同的响应格式。

创建响应转换模板,该模板根据消费者身份提取并重组嵌套的 JSON 字段:

rsp_template=$(cat <<EOF | awk '{gsub(/"/,"\\\"");};1' | awk '{$1=$1};1' | tr -d '\r\n'
{% local consumer_name = _ctx.consumer and _ctx.consumer.username or "" %}
{% if consumer_name == "consumer-a" then %}
{
"user_id": {* id *},
"user_name": {* _escape_json(name) *},
"email": {* _escape_json(profile.email) *},
"location": {
"city": {* _escape_json(profile.address.city) *},
"country": {* _escape_json(profile.address.country) *}
},
"created_at": {* _escape_json(metadata.created_at) *}
}
{% elseif consumer_name == "consumer-b" then %}
{
"id": {* id *},
"name": {* _escape_json(name) *},
"status": {* _escape_json(status) *},
"profile": {
"email": {* _escape_json(profile.email) *},
"address": {
"city": {* _escape_json(profile.address.city) *}
}
}
}
{% else %}
{* _body *}
{% end %}
EOF
)

创建配置了 key-auth 的消费者:

curl "http://127.0.0.1:9180/apisix/admin/consumers" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"username": "consumer-a",
"plugins": {
"key-auth": {
"key": "consumer-a"
}
}
}'

curl "http://127.0.0.1:9180/apisix/admin/consumers" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"username": "consumer-b",
"plugins": {
"key-auth": {
"key": "consumer-b"
}
}
}'

curl "http://127.0.0.1:9180/apisix/admin/consumers" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"username": "consumer-c",
"plugins": {
"key-auth": {
"key": "consumer-c"
}
}
}'

使用嵌套结构模板创建一个带有 body-transformer、key-auth 和 mocking 插件的路由:

curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
--data-binary @- <<EOF
{
"id": "body-transformer-route",
"uri": "/mock",
"plugins": {
"key-auth": {},
"mocking": {
"response_example": "{\"id\":123,\"name\":\"John Doe\",\"status\":\"active\",\"profile\":{\"email\":\"john@example.com\",\"address\":{\"city\":\"New York\",\"country\":\"USA\"}},\"metadata\":{\"created_at\":\"2024-01-01\",\"tags\":[\"vip\",\"premium\"]}}"
},
"body-transformer": {
"response": {
"input_format": "json",
"template": "$rsp_template"
}
}
}
}
EOF

❶ 配置 mocking 插件返回示例嵌套上游响应。

❷ 将响应输入格式设置为 JSON。

❸ 设置根据消费者身份处理嵌套 JSON 结构的转换模板。

以 consumer-a 身份发送请求以验证嵌套结构转换:

curl "http://127.0.0.1:9080/mock" -H "apikey: consumer-a"

你应该看到类似于以下的响应,展示了这些嵌套字段转换:

  • profile.email 已提取到顶层 email
  • profile.address.city 和 profile.address.country 已组合成一个新的 location 对象
  • metadata.created_at 已提取到顶层 created_at
{
"user_id": 123,
"user_name": "John Doe",
"email": "john@example.com",
"location": {
"city": "New York",
"country": "USA"
},
"created_at": "2024-01-01"
}

以 consumer-b 身份发送请求以验证嵌套结构转换:

curl "http://127.0.0.1:9080/mock" -H "apikey: consumer-b"

你应该看到类似于以下的响应,展示了这些转换:

  • 原始 profile 对象结构被保留
  • profile.address.country 和 metadata 字段已被过滤掉
{
"id": 123,
"name": "John Doe",
"status": "active",
"profile": {
"email": "john@example.com",
"address": {
"city": "New York"
}
}
}

以 consumer-c 身份发送请求以验证嵌套结构转换:

curl "http://127.0.0.1:9080/mock" -H "apikey: consumer-c"

你应该看到类似于以下的响应,显示原始嵌套响应被原样返回:

{
"id": 123,
"name": "John Doe",
"status": "active",
"profile": {
"email": "john@example.com",
"address": {
"city": "New York",
"country": "USA"
}
},
"metadata": {
"created_at": "2024-01-01",
"tags": ["vip", "premium"]
}
}