Using LUA to send a POST request with JSON data

It took me a while to figure this out, so I thought I would share for anyone who’s interested. The following code is an example of how to send a POST request with JSON data using LUA. It contains, URL parameters, JSON data and a custom header.

local http = require("socket.http")
local ltn12 = require("ltn12")

-- The Request Bin test URL: http://requestb.in/12j0kaq1
function sendRequest()
local path = "http://requestb.in/12j0kaq1?param_1=one&param_2=two&param_3=three"
  local payload = [[ {"key":"My Key","name":"My Name","description":"The description","state":1} ]]
  local response_body = { }

  local res, code, response_headers, status = http.request
  {
    url = path,
    method = "POST",
    headers =
    {
      ["Authorization"] = "Maybe you need an Authorization header?", 
      ["Content-Type"] = "application/json",
      ["Content-Length"] = payload:len()
    },
    source = ltn12.source.string(payload),
    sink = ltn12.sink.table(response_body)
  }
  luup.task('Response: = ' .. table.concat(response_body) .. ' code = ' .. code .. '   status = ' .. status,1,'Sample POST request with JSON data',-1)
end

You should see an alert at the top of the page that looks like this:

Sample POST request with JSON data : Response: = ok code = 200 status = HTTP/1.1 200 OK

You can view the results here: RequestBin — A modern request bin to collect, inspect and debug HTTP requests and webhooks - Pipedream

(just in case the bin has been removed, I’ve attached the results)

thanks very much for posting this… i am trying to do something similar for my Dynamic DNS plugin