body-transformer
Use cases:
- simple SOAP proxy
- generic template-based transform, e.g. JSON to JSON, JSON to HTML, XML to YAML
Attributes
You can enable the Plugin on a specific Route as shown below:
Configuration description
The request
and response
correspond to configurations of request body and response body transformation perspectively.
Specify one of them, or both of them, to fit your need.
request
/response
:
input_format
specifies the body original format:xml
(text/xml
)json
(application/json
)
{{ ... }}
in lua-resty-template will do html-escape, e.g. space character, so if it’s not what you wish, use instead.
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 }}
.
This is useful for below use cases:
- 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.
For example, parse YAML to JSON yourself:
{%
local yaml = require("tinyyaml")
local body = yaml.parse(_body)
%}
{"foobar":"{{body.foobar.foo .. " " .. body.foobar.bar}}"}
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.
In template
, you can use below auxiliary functions to escape string to fit specific format:
_escape_json()
_escape_xml()
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)*}}
.
And, you can refer to _ctx
to access nginx request context, e.g. .
Let’s take a simple SOAP proxy as example.
- 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
- the response
cd /tmp
cd gs-soap-service
./mvnw spring-boot:run
Test
Disable Plugin
To disable 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.
curl http://127.0.0.1:9180/apisix/admin/routes/test_ws \
-H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
{
"methods": ["POST"],
"uri": "/ws",
"plugins": {},
"upstream": {
"type": "roundrobin",
"nodes": {
"localhost:8080": 1
}