Edit request/response

In this page we will demonstrate basic operations that you can achieve in functions.

Accessing request data (incoming webhook/API request)

Lua functions use r object that provide access to request data (headers, query, method and body) and can then update any HTTP request details.

Available data to access:

Read request body

An example of accessing request body and decoding it:

-- import json package
local json = require("json")

-- request body is in r.RequestBody, use it as any other string:
local body, err = json.decode(r.RequestBody)
if err then error(err) end

Reading request headers

To access specific header, use:

local my_header = r.RequestHeader["Your-Header-Name"]

Reading request URL query

To read request URL query (for example /v1/api?hub.mode=subscribe&hub.challenge=1903260781&hub.verify_token=my-token") you have two options:

  1. r.RequestQuery["hub.challenge"] which will return 1903260781 for this example.

  2. r.RequestRawQuery which will return full raw query hub.mode=subscribe&hub.challenge=1903260781&hub.verify_token=my-token"

Modify request data

Available methods to update request:

An example how to update request object:

-- set body
r:SetRequestBody("new body")
-- set method
-- set raw query
-- set extra path
-- set header
r:SetRequestHeader("Content-Type", "application/json")
-- delete header

Modify response

Note: customized responses only applicable if function is attached to the Input and not bucket’s Output.

Available methods to set customized response:

Getting configuration values

Configuration values in Lua functions allow sharing the code without sharing sensitive information or just configuration values that might change between accounts, teams, etc.

To add a new configuration value:

  1. Create a function

  2. Go to function details

  3. Click on a tab “CONFIG VARIABLES”

  4. Specify config variable key and value.

Once you have specified these details, you can start using them in your functions:

-- configuration is accessible from a global "cfg" variable
local project_id = cfg:GetValue("PROJECT_ID")
-- do something with the value

Filtering requests

To filter requests based on body, headers or some external conditions, you can use r:StopForwarding() method. This will set webhook status to rejected and this webhook will not be forwarded:

-- in this example we will check the payload to make the decision
local json = require("json")

-- incoming request body example:
-- {
--   "action": "important",
--   "user": "joe"
-- }

local requestBody, err = json.decode(r.RequestBody)
if err then error(err) end

-- simple comparison of the payload
if requestBody["action"] == "not_important" then 
    -- request is not important, don't forward it
-- Otherwise, continue forwarding or add any additional logic here

Last updated