HTTP

HTTP is not creatable, there's only one instance of it. It can only be accessed through its globally exposed variable.

HTTP allows you to send HTTP requests. This feature is only available in the Server functions.
If you want to send a request from the Client, you first need to send an Event to the Server. The server will take care of the HTTP request and send back information to the Client.

Functions

nil Get ( string url, table headers optional, function callback )

Sends a GET HTTP request to the specified url. The request is asynchronous.
The callback is called after receiving a response from the server.

local url = "https://mybestapi.com/api/users" -- replace with the URL you want to request

HTTP:Get(url, function(res)
  if res.StatusCode ~= 200 then
    print("Error " .. res.StatusCode)
    return
  end
  -- body is [{"id": 289733, "name": "Mike", "age": 15}]
  users,err = JSON:Decode(res.Body)
  local user = users[1]
  print(user.id, user.name, user.age)
  -- prints 289734 Mike 15.0
end)
nil Post ( string url, table headers optional, table body, function callback )
nil Post ( string url, table headers optional, string body, function callback )
nil Post ( string url, table headers optional, Data body, function callback )

Sends a POST HTTP request to the specified url. The request is asynchronous.
If body is a table, it is JSON encoded before being sent. Otherwise it is sent as a string or raw Data.
The callback is called after receiving a response from the server.

local url = "https://mybestapi.com/api/users" -- replace with the URL you want to request
local headers = {}
headers["Content-Type"] = "application/json"
headers["Authorization"] = "Bearer 298H3298H329839823" -- if the API requires authentication

local body = {}
body.name = "Bob"
body.age = 28

HTTP:Post(url, headers, body, function(res)
  if res.StatusCode ~= 200 then
    print("Error " .. res.StatusCode)
    return
  end
  -- body is {"id": 289734, "name": "Bob", "age": 28}
  user,err = JSON:Decode(res.Body)
  print(user.id, user.name, user.age)
  -- prints 289734 Bob 28.0
end)