1

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?

Seniru Pasan
  • 753
  • 1
  • 7
  • 13
  • in your code there are syntax errors: function not closed, headers table not closed, string 'Content-type' must be 'Content-Type'. Can you post minimal code which you tested and not works – Darius Mar 10 '20 at 11:15
  • Error is generated for **http response** and not request. Http response generates unknown status code for example: 0 or -1. List of valid status codes you can check in /workspace/wtal-bot/deps/http-codec.lua or https://github.com/luvit/lit/blob/master/deps/http-codec.lua – Darius Mar 10 '20 at 11:26
  • @Darius I editted my code a bit and now I got the above response. Now the question is how to do the POST request correctly – Seniru Pasan Mar 11 '20 at 09:28

1 Answers1

3

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)()
Darius
  • 1,060
  • 2
  • 6
  • 17