Search code examples
restpostlualuvit

How to do a POST request using Luvit


I'm using Luvit for one of my projects which uses some online APIs to make the things simpler. One such API asks me to do a POST request to their endpoint to deal with the data. I looked at their official documentation, and even some unofficial ones, but ended up finding nothing. I even tried some of the following and nothing seems to be working

local http = require("coro-http")

coroutine.wrap(function()
    local head, body = http.request("POST", JSON_STORE_CLIENT, {{"Content-Type", "application/json"}}, "test")
    print(head)
    print(body)
end)()
--[[
table: 0x7f5f4a732148
<!DOCTYPE html>
<html lang="en">
...
basically tells its a bad request
</html>
]]

Can somebody help me in doing REST operations with luvit, especially POST, correctly?


Solution

  • Your http.request works as expected and it returns response table (not only headers) and body string.

    You posting Content-Type: application/json but sending invalid data. Body must be valid JSON object:

    local http = require("coro-http")
    local json = require("json")
    
    coroutine.wrap(function()
        local data = {param1 = "string1", data = {key = "value"}}
        local res, body = http.request("POST", JSON_STORE_CLIENT,
          {{"Content-Type", "application/json"}},
          json.stringify(data))
          -- or static string [[{"param1": "string1", "data": {"key": "value"}}]]
        print(res.code)
        print(body)
    end)()