Skip to content

HTTP

Functions

Return Type Name Description
response http.fetch(string url, options? options, body = '' }) Performs an HTTP request
nil http.fetch_async(string url, table options, function callback(response)) Performs an HTTP request asynchronously

Types

options

Property Name Description
string method The HTTP method
table headers The HTTP headers

response

Property Name Description
bool success Whether the request succeeded
number status The HTTP status code
table headers The HTTP headers

Methods

Return Type Name Description
string body() Binary format response data
string text() Text format response data
table json() JSON format response data

Examples

-- Fetching a json object
local result = http.fetch('https://jsonplaceholder.typicode.com/todos/1', {})
if result.success then
  print(result:json().userId) -- 1
end

-- Fetching geo information async
http.fetch_async('http://ip-api.com/json/1.1.1.1', {}, function(response)
  if response.success then
    local resp = response:json()
    print(resp.city) -- "South Brisbane". Alternatively resp['city']
  end
end)

-- Fetching custom data from a localhost page
http.fetch_async('http://localhost/test', {
  method = 'POST',
  headers = {
    [ 'User-Agent' ] = 'Mozilla/5.0',
    [ 'Content-Type' ] = 'application/json'
  },
  body = 'admin' -- alternatively, an instance of nlohmann_json or binary data
}, function(response)
  print(response.status_code)
  print(response:json():dump(4))
end)