Skip to content

http Module

The http module allows sending HTTP requests with customizable configurations, including method, headers, body, and URL.

To import it, use the following declaration:

local http = require("http")
-- replace "http" with the module name defined in the configuration file

Configuration

The http module requires specific configuration to function. This configuration is defined in the agent's configuration file.

Here is an example showing all possible options:

iot:
  modules:
    http: # http module
      - name: http1 # module name
        url: "http://example.com" # request URL
        method: "GET" # request method
        headers: # request headers
          Content-Type: "application/json"
        body: "" # request body

You can also define only the name and use the Lua function http.requestCustom(url, method[, body[, headers]]) to send a custom HTTP request.

Configuration Details

  • name: Module name. It must be unique and must not contain spaces or special characters.
  • url: The request URL. Must be in the format http://example.com.
  • method: HTTP method. Can be GET, POST, PUT, DELETE, etc.
  • headers: Request headers. A Lua table containing key-value pairs of HTTP headers (e.g., {["Content-Type"] = "application/json"}).
  • body: The body of the request. A string that will be sent in the HTTP request body. Defaults to an empty string.

Lua Functions

http.request()

Sends an HTTP request using the predefined configuration from the HttpSocket instance.

  • Parameters: None. This function uses the configuration defined in the HttpSocket instance.

  • Return:

  • The response body as a string, or an error message in case of failure.
local http = require("http")
local response, err = http.request()
if err then
    print("Error during HTTP request: " .. err)
else
    print("Response: " .. response)
end

http.requestCustom(url, method[, body[, headers]])

Sends a custom HTTP request using the specified parameters.

  • Parameters:
  • url (string): The URL to which the request is sent.
  • method (string): The HTTP method to use (GET, POST, etc.).
  • body (string, optional): The request body. Defaults to an empty string.
  • headers (table, optional): A Lua table containing HTTP headers as key-value pairs (e.g., {["Content-Type"] = "application/json"}).

  • Return:

  • The response body as a string, or an error message in case of failure.
local http = require("http")
local url = "http://example.com"
local method = "POST"
local body = '{"key": "value"}'
local headers = {["Content-Type"] = "application/json"}

local response, err = http.requestCustom(url, method, body, headers)
if err then
    print("Error during custom HTTP request: " .. err)
else
    print("Response: " .. response)
end

Associated Lua Fields

  • http.name: Returns the name of the http module instance.
  • http.type: Returns the module type (here, http).