body-transformer

Description

This plugin is used to transform the request and/or response body from one format to another format, e.g. JSON to XML.

Use cases:

  • simple SOAP proxy
  • generic template-based transform, e.g. JSON to JSON, JSON to HTML, XML to YAML

Attributes

NameTypeRequiredDescription
requestobjectFalserequest body transformation configuration
request.input_formatstringFalserequest body original format, if not specified, it would be determined from Content-Type header.
request.templatestringTruerequest body transformation template
request.template_is_base64booleanFalseSet to true if the template is base64 encoded
responseobjectFalseresponse body transformation configuration
response.input_formatstringFalseresponse body original format, if not specified, it would be determined from Content-Type header.
response.templatestringTrueresponse body transformation template
response.template_is_base64booleanFalseSet to true if the template is base64 encoded

Enable Plugin

You can enable the Plugin on a specific Route as shown below:

  1. curl http://127.0.0.1:9180/apisix/admin/routes/test_ws \
  2. -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
  3. {
  4. "methods": ["POST"],
  5. "uri": "/ws",
  6. "plugins": {
  7. "body-transformer": {
  8. "request": {
  9. "template": "..."
  10. },
  11. "response": {
  12. "template": "..."
  13. }
  14. }
  15. },
  16. "upstream": {
  17. "type": "roundrobin",
  18. "nodes": {
  19. "localhost:8080": 1
  20. }
  21. }
  22. }'

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)
  • template specifies the template text used by transformation.

Notes:

{{ ... }} 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:

  1. {%
  2. local yaml = require("tinyyaml")
  3. local body = yaml.parse(_body)
  4. %}
  5. {"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.

For example, you could use base64 command to encode your template text file:

  1. curl http://127.0.0.1:9180/apisix/admin/routes/test_ws \
  2. -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
  3. {
  4. "methods": ["POST"],
  5. "uri": "/ws",
  6. "plugins": {
  7. "body-transformer": {
  8. "request": {
  9. "template": "'"$(base64 -w0 /path/to/my_template_file)"'"
  10. }
  11. }
  12. },
  13. "upstream": {
  14. "type": "roundrobin",
  15. "nodes": {
  16. "localhost:8080": 1
  17. }
  18. }
  19. }'

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. {{ _ctx.var.status }}.

Example

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

Run a test web service server

  1. cd /tmp
  2. git clone https://github.com/spring-guides/gs-soap-service.git
  3. cd gs-soap-service
  4. ./mvnw spring-boot:run

Test

  1. req_template=$(cat <<EOF | awk '{gsub(/"/,"\\\"");};1' | awk '{$1=$1};1' | tr -d '\r\n'
  2. <?xml version="1.0"?>
  3. <soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
  4. <soap-env:Body>
  5. <ns0:getCountryRequest xmlns:ns0="http://spring.io/guides/gs-producing-web-service">
  6. <ns0:name>{{_escape_xml(name)}}</ns0:name>
  7. </ns0:getCountryRequest>
  8. </soap-env:Body>
  9. </soap-env:Envelope>
  10. EOF
  11. )
  12. rsp_template=$(cat <<EOF | awk '{gsub(/"/,"\\\"");};1' | awk '{$1=$1};1' | tr -d '\r\n'
  13. {% if Envelope.Body.Fault == nil then %}
  14. {
  15. "status":"{{_ctx.var.status}}",
  16. "currency":"{{Envelope.Body.getCountryResponse.country.currency}}",
  17. "population":{{Envelope.Body.getCountryResponse.country.population}},
  18. "capital":"{{Envelope.Body.getCountryResponse.country.capital}}",
  19. "name":"{{Envelope.Body.getCountryResponse.country.name}}"
  20. }
  21. {% else %}
  22. {
  23. "message":{*_escape_json(Envelope.Body.Fault.faultstring[1])*},
  24. "code":"{{Envelope.Body.Fault.faultcode}}"
  25. {% if Envelope.Body.Fault.faultactor ~= nil then %}
  26. , "actor":"{{Envelope.Body.Fault.faultactor}}"
  27. {% end %}
  28. }
  29. {% end %}
  30. EOF
  31. )
  32. curl http://127.0.0.1:9180/apisix/admin/routes/test_ws \
  33. -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
  34. {
  35. "methods": ["POST"],
  36. "uri": "/ws",
  37. "plugins": {
  38. "proxy-rewrite": {
  39. "headers": {
  40. "set": {
  41. "Accept-Encoding": "identity",
  42. "Content-Type": "text/xml"
  43. }
  44. }
  45. },
  46. "response-rewrite": {
  47. "headers": {
  48. "set": {
  49. "Content-Type": "application/json"
  50. }
  51. }
  52. },
  53. "body-transformer": {
  54. "request": {
  55. "template": "'"$req_template"'"
  56. },
  57. "response": {
  58. "template": "'"$rsp_template"'"
  59. }
  60. }
  61. },
  62. "upstream": {
  63. "type": "roundrobin",
  64. "nodes": {
  65. "localhost:8080": 1
  66. }
  67. }
  68. }'
  69. curl -s http://127.0.0.1:9080/ws -H 'content-type: application/json' -X POST -d '{"name": "Spain"}' | jq
  70. {
  71. "status": "200",
  72. "currency": "EUR",
  73. "population": 46704314,
  74. "capital": "Madrid",
  75. "name": "Spain"
  76. }
  77. # Fault response
  78. curl -s http://127.0.0.1:9080/ws -H 'content-type: application/json' -X POST -d '{"name": "Spain"}' | jq
  79. {
  80. "message": "Your name is required.",
  81. "code": "SOAP-ENV:Server"
  82. }

Delete Plugin

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.

  1. curl http://127.0.0.1:9180/apisix/admin/routes/test_ws \
  2. -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
  3. {
  4. "methods": ["POST"],
  5. "uri": "/ws",
  6. "plugins": {},
  7. "upstream": {
  8. "type": "roundrobin",
  9. "nodes": {
  10. "localhost:8080": 1
  11. }
  12. }
  13. }'