【问题标题】:Access REST API via lua script通过 lua 脚本访问 REST API
【发布时间】:2020-03-24 11:48:53
【问题描述】:

有没有办法用纯lua脚本访问rest api

GET / POST 两种方式都需要访问并显示响应

我已经试过了

    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

【问题讨论】:

  • 你使用的是什么 Lua 库?我可以在哪里阅读 .on_get 上的文档?
  • @EgorSkriptunoff ,我完全不了解 lua,所以不知道 .on_get 是否是一个库。有人可以帮忙吗?
  • 如果 REST API 记录在 OpenAPI/Swagger 中,您可能想尝试使用 OpenAPI Generator 来生成 Lua API 客户端:github.com/OpenAPITools/openapi-generator
  • this answer

标签: api post lua get response


【解决方案1】:

在 linux , mac 中我们可以轻松安装 luarocks ,然后我们可以安装 curl 包。这是像 os 一样的 unix 最简单的方法。


-- 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()

在 Windows 中,我遇到了几个问题。无法正确安装 luarocks。然后 luarock install 命令不能正常工作,等等。

首先从官方网站下载lua,然后创建类似(以下网站)的结构

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

然后我下载 lua luadist http://luadist.org/

然后我得到了相同的结构 luadist 提取文件夹和 lua 文件夹。

合并 luadist 文件夹和 lua 文件夹 最后我们可以使用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

如果你正确地执行这些步骤,这将是 1000% 肯定的

【讨论】:

    猜你喜欢
    • 2019-10-23
    • 1970-01-01
    • 2012-11-04
    • 1970-01-01
    • 2014-10-16
    • 2017-08-04
    • 2018-08-01
    • 2022-11-12
    • 1970-01-01
    相关资源
    最近更新 更多