The goal of this coro-http wrapper is simple: to simplify the process of making simple HTTP requests as much as possible. simple-http offers automatic content encoding/decoding, friendlier header declarations and data verification using Schema.
simple-http can be installed from lit using
lit install RiskoZoSlovenska/simple-http
Once installed, it can be required using
local http = require("simple-http")The two examples on the coro-http docs page can be rewritten using simple-http as such:
local page, res = http.request("GET", "https://www.google.com")
if not page then
print("Could not fetch www.google.com successfully: " .. res); return
end
print("Received Google main page HTML: " .. page)local webhookUrl = "https://discord.com/api/webhooks/{ID}/{TOKEN}" -- Your webhook URL here
local success, res = http.request(
"POST", webhookUrl,
{
content = "Hello There!\nThis is an example for a POST request using simple-http!"
},
http.Encoding.json, -- simple-http will automatically encode the payload
nil, -- The Content-Type and Content-Length headers are autofilled
nil,
5000
)
-- Did it send it successfully or error?
if not success then
print("Failed to send webhook: " .. res); return
end
print("Webhook sent successfully!")To illustrate using schemas, the following code could be used to request the definition of "hello" from https://dictionaryapi.dev/ :
local endpoint = "https://api.dictionaryapi.dev/api/v2/entries/en/hello" -- Get the definition of "hello" from
local schema = http.schema
local Record, Array, Optional, String = schema.Record, schema.Array, schema.Optional, schema.String
local RecordArray = function(...) return Array(Record(...)) end
local responseSchema = RecordArray{
word = String,
phonetics = Optional(RecordArray{
text = String,
}),
meanings = RecordArray{
partOfSpeech = String,
definitions = RecordArray{
definition = String,
example = Optional(String),
synonyms = Optional(Array(String)),
antonyms = Optional(Array(String)),
},
},
}
local definition, res = http.request("GET", endpoint, nil, nil, nil, responseSchema)
if not definition then
print("Failed to get definition: " .. res); return
end
print("Definition of \"hello\": " .. definition[1].meanings[1].definitions[1].definition) -- Response is automatically decoded to a Lua tableWhen you require simple-http, you get a table with the following values. You can learn more about each below.
| Parameter | Type | Optional | Description |
|---|---|---|---|
| method | string |
❌ | |
| url | string |
❌ | |
| payload | any |
✔️ | |
| encoding | Encoding |
✔️ | |
| headers | table |
✔️ | |
| schema | Schema |
✔️ | A Schema object to verify the integrity of the data with |
| options | RequestOptions/Timeout |
✔️ |
See coro-http.request's parameters for more info.
Performs an HTTP(S) request. Just like coro-http.request, this function has to be called from a coroutine.
If encoding is specified, attempts to encode the payload and inserts the Content-Type header if it isn't already specified. Otherwise, the payload is simply converted to a string.
The headers parameter accepts both the {{key, value}, ...} and {[key] = value, ...} formats. If both are used, the unordered [key] = value pairs are appended to the list of ordered key-value pairs in no particular order.
When the request returns, if it specifies a Content-Type header with supported encoding, the data will be automatically decoded into a Lua table.
This function never throws an error unless faulty data is passed to it; it always returns a 3-tuple in the format data, res, errInfo. If the request succeeds, data will be the (possibly decoded) body, res will be the Response object returned by the request and errInfo will be nil. Otherwise, if the request fails, data will be nil, res will be an error message and errInfo will be an ErrorInfo object. See the FailReason enumeration and the ErrorInfo structure for details.
Returns: table|string|nil, Response|string, ErrorInfo|nil
Gives more information about the reason a request failed.
| Entry | Type | Description |
|---|---|---|
| type | FailReason |
See the enumeration for details |
| trace | string |
The stack trace of the error |
| body | string|table |
The payload/body that caused an error |
| response | table |
The Response object that caused an error |
Be default, only the type field is guaranteed to be present. Its value indicates what other fields are guaranteed to be present as well:
type value |
trace |
body |
response |
|---|---|---|---|
Unknown |
❌ | ❌ | ❌ |
BadPayload |
✔️ | ✔️ | ❌ |
RequestError |
✔️ | ❌ | ❌ |
BadResponseCode |
❌ | ✔️ | ✔️ |
BadResponseBody |
✔️ | ✔️ | ✔️ |
InvalidResponseBody |
❌ | ✔️ | ✔️ |
The Encoding enum is used to specify the encoding/decoding algorithm used by the request function. The function expects the enum value, not the enum name.
| Enumeration | Value | Functions used |
|---|---|---|
| json | application/json |
json.encode and json.decode |
| url | application/x-www-form-urlencoded |
querystring.stringify and querystring.parse |
The FailReason enum specifies a reason why a request failed.
| Enumeration | Value | Scenario Emitted |
|---|---|---|
| Unknown | 0 |
The reason is unknown (this should never happen) |
| BadPayload | 1 |
The encoder function threw an error while encoding the payload |
| RequestError | 2 |
The coro-http.request function threw an error |
| BadResponseCode | 3 |
The http code of the returned response was 300 or greater |
| BadResponseBody | 4 |
The decoder function threw an error while attempting to decode the response body |
| InvalidResponseBody | 5 |
A schema check was provided and the (possibly decoded) response body failed it |