用lua写一个api接口
时间: 2023-12-29 15:55:35 浏览: 37
以下是一个简单的Lua脚本,用来实现一个API接口:
```lua
local http = require("socket.http")
local json = require("json")
-- 定义API地址
local api_url = "http://example.com/api/"
-- 定义API请求函数
function make_api_request(endpoint, params)
local url = api_url .. endpoint
local response_body = {}
local response, status_code, headers = http.request{
url = url,
method = "POST",
headers = {
["Content-Type"] = "application/json",
["Content-Length"] = string.len(params)
},
source = ltn12.source.string(params),
sink = ltn12.sink.table(response_body)
}
if status_code ~= 200 then
return nil, "API request failed with status code: " .. status_code
end
return json.decode(table.concat(response_body)), nil
end
-- 调用API
local params = json.encode({key1 = "value1", key2 = "value2"})
local response, err = make_api_request("example_endpoint", params)
if err then
print("API request failed: " .. err)
else
print("API response: ")
for k, v in pairs(response) do
print(k .. ": " .. v)
end
end
```
该脚本使用Lua的HTTP库和JSON库,定义了一个make_api_request函数来发送API请求,并使用json.decode将响应解析为Lua表。调用API时,需要将请求参数编码为JSON字符串,并提供API端点名称。最后,该脚本打印响应的键值对。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![unitypackage](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)