2

Is there way to access rest api with pure lua script

GET / POST both way need to access and display response

i already tried

    local api = nil
    local function iniit()
    if api == nil then
      -- body
      api = require("http://api.com")
            .create()
            .on_get(function ()
                return {name = "Apple",
                        id = 12345}

            end)
        end
     end
4
  • What Lua library are you using? Where I can read the doc on .on_get? Commented Mar 24, 2020 at 12:07
  • @EgorSkriptunoff , i'm completely noob for lua, so dont know .on_get is a library or not. Anyone can help ? Commented Mar 24, 2020 at 14:03
  • If the REST API is documented in OpenAPI/Swagger, you may want to try using OpenAPI Generator to generate the Lua API client instead: github.com/OpenAPITools/openapi-generator Commented Jul 5, 2020 at 8:16
  • See this answer. Commented Jan 18, 2021 at 23:55

1 Answer 1

1

In linux , mac we can easily install luarocks , and then we can install curl package. It's easiest way to unix like os.


-- HTTP Get
local curl = require('curl')

curl.easy{
  url = 'api.xyz.net?a=data',
  httpheader = {
    "X-Test-Header1: Header-Data1",
    "X-Test-Header2: Header-Data2",
  },
  writefunction = io.stderr -- use io.stderr:write()
}
:perform()
:close()

In windows i faced several problems. Cant install luarocks correctly. then luarock install command not work correctl, etc..

In first dwnload lua from official site, and then create structure like (below web site)

http://fuchen.github.io/dev/2013/08/24/install-luarocks-on-windows/

then i download lua luadist http://luadist.org/

then i got same structure luadist extracted folder and lua folder.

merged luadist folder and lua folder Finaly we can use http.soket

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

local request_body = [[login=user&password=123]]
local response_body = {}

local res, code, response_headers = http.request{
    url = "api.xyz.net?a=data",
    method = "GET", 
    headers = 
      {
          ["Content-Type"] = "application/x-www-form-urlencoded";
          ["Content-Length"] = #request_body;
      },
      source = ltn12.source.string(request_body),
      sink = ltn12.sink.table(response_body),
}

print(res)
print(code)

if type(response_headers) == "table" then
  for k, v in pairs(response_headers) do 
    print(k, v)
  end
end

print("Response body:")
if type(response_body) == "table" then
  print(table.concat(response_body))
else
  print("Not a table:", type(response_body))
end

IF YOU DO THESE STEPS CORRECTLY , THIS WILL BE WORK 1000% SURE

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.