A wrapper to simplify HTTP requests
Making a simple GET request:
-- make sure you call HTTP.update()
-- in your playdate.update handler
HTTP.fetch("http://example.com", function(res, err)
if not err and res.ok then
print(res.body)
end
end)A more complex example, sending a POST request with additional data:
HTTP.fetch("https://example.com/login", {
method = "POST",
headers = { ["Content-Type"] = "application/json" },
body = json.encode({ username = "crankles", password = "*****" })
}, function(res)
local token = res.headers["Authorization"]
-- ...
end)- Add
import "fetch.lua"somewhere in yourmain.luafile - Call
HTTP.update()in yourplaydate.updatehandler - Use
HTTP.fetch()from anywhere in your code!
Schedules a basic GET request to the provided URL.
urlis a string containing the full URL, includinghttp://orhttps://onCompleteis a function that is called when the request is completedreason(optional) is a string that the system shows in the network access popup
Called when the request is completed.
responseis a table containing the following fields:oka boolean indicating that the request completed successfully (a2xxstatus code)statusa number containing the status codestatusTexta string containing the status messagebodya string containing the contents of the responseheadersa table containing the response headers
erris a string containing the error message ifresponseisnil
A note on error handling, or, why you need to deal with both err and response.ok:
erris set when something went wrong with the connection or request itself, for example when the user did not grant network permissions, or the request timed out.response.okistruewhen the server responded with a200status code. If it'sfalse, the server did reply, but returned an error to you, for example a404 Not Foundor500 Server Error.