Skip to content

Http

Talks to web services: sends a request to a URL, and waits for the response.

A spell only reaches the hosts that the owner of the server has listed in config/wizards-of-lua/net.luaconf. That file is empty at first, so nothing can be reached, and spell code can't change it. A change to it applies to the next request, without a restart.

hosts = {
  "api.example.org",    -- this name, at any port
  "*.example.net",      -- every name below this one, but not example.net itself
}

"*" alone allows every host, including the server's own computer and its local network.

To read or send data as JSON, see Json.

Example: Fetch data from a web service

local response, reason = Http:request({ url = "https://api.example.org/time" })
if response and response.status == 200 then
  local data = assert(Json:decode(response.body))
  print(data.time)
else
  print("No answer: " .. tostring(reason or response.status))
end

Example: Send data to a web service

local response, reason = Http:request({
  url = "https://api.example.org/scores",
  method = "POST",
  headers = { ["Content-Type"] = "application/json" },
  body = Json:encode({ player = spell.owner.name, score = 100 }),
})

Methods

request(options: HttpRequestOptions) → response: HttpResponse?, reason: NetReason?

Sends a request, and waits until the response arrives or the timeout has passed. Call it on the class: Http:request(options).

Any response counts, a 404 or a 500 too: check its status. A redirect is a response too, as it may lead to a host that isn't listed: its target is in headers.location. nil means that no response arrived, and the reason says why.

A response may have up to 16 MB. A larger one ends the request.

Because it waits, this function can't be called in an event interceptor. If the spell ends while it waits, the request is cancelled.

A wrong option raises an error. Error messages never show the URL or a header's value, as they can hold a password.

Example: Values in the query

query encodes the values, here ["fabric"] as %5B%22fabric%22%5D.

local response = Http:request({
  url = "https://api.modrinth.com/v2/project/wizards-of-lua/version",
  query = { loaders = '["' .. WizardsOfLua.loader .. '"]' },
})

Example: Send a form

Http:request({
  url = "https://api.example.org/scores",
  form = { player = spell.owner.name, score = 100 },
})

Example: Upload a file from the world folder

local file = assert(io.open("screenshots/base.png", "rb"))
local data = file:read("a")
file:close()
Http:request({
  url = "https://api.example.org/upload",
  form = {
    comment = "My base",
    file = { filename = "base.png", contentType = "image/png", body = data },
  },
})

Parameters

Returns

  • response: HttpResponse? — The response, or nil if none arrived.
  • reason: NetReason? — Why no response arrived.