Lua scripting in KrakenD

Here are some notes on how to get on with Lua scripting for KrakenD

Imagine you have a backend that returns a JSON like this

So we route

KrakendDService A
GET /public/api/get-indv/45 GET /api/indv/45

The most basic KrakendD config would be something like this

In fact you could remove the ‘output_encoding’ and ‘encoding’, cause those are ‘json’ by default but gives clarity to the example.

Remove unwanted fields from the JSON

Let’s say that we do not want to expose the field “databaseId” Then we can apply a Lua script in KrakenD that solves this for us The configuration in krakendD can look something like this

The Lua code we place in a file on the same directory as the krakenD config

And the Lua function could look something like this

Dump some request info and the Data-object to the KrakenD log

Let’s place the lua script to dump some info on the ‘proxy’ level, the config could look something like this

The Lua code

Set or Modify the body when it is Content-Type : text

Note that KrakenD needs to be told how to interpret the data, and above the encoding was set explicitly to ‘json’ here we will set it to ‘string’ (i.e. text). The KrakenD config could look something like this

The Lua code below

Note that when we would like to modify the body and the data-object key will be ‘content’.

Set the http header Content-Type from Lua script

Imagine that the encoding/output_encoding was set to ‘string’ then the return data from krakenD will set the Content-Type to ‘text/plain; charset=utf-8’

If you would for some reason get a string and would like to set the Content-Type to ‘application/json; charset=utf-8’

You can do this from a Lua script like this

Bless you !
-Tobias

Leave a Reply

Your email address will not be published. Required fields are marked *