Codea icon Network

Reference › Fetching web data and images with HTTP

HTTP

http top ↑

Module

Use http.request to fetch data without stopping drawing. Start a request in setup() or in response to an action, rather than on every frame. Store its result in the callback and draw that state in draw(). A response can arrive later or fail, so show a loading state and handle both outcomes.

function setup()
    message = "Loading…"
    http.request("https://codea.io", function(data, status, headers)
        if status >= 200 and status < 300 then
            message = "Received response: " .. status
        else
            message = "Server returned " .. status
        end
    end, function(errorMessage)
        message = "Request failed: " .. errorMessage
    end)
end

function draw()
    background(30)
    fill(255)
    text(message, WIDTH / 2, HEIGHT / 2)
end

http.request(url, success, failure, options)

Function

Syntax

http.request(url, success, failure, options)

Starts an asynchronous HTTP request. success(data, status, headers) receives a string for ordinary response bodies, or an image when the body decodes as an image. status is the numeric HTTP status; headers is a table. HTTP errors such as 404 still call success: check the status yourself.

failure(message, response, status) handles transport errors. The first argument is a string; additional response data may be unavailable. Always supply a failure callback when providing options.

Options are method (default "GET"), headers (string keys and values), data (request body string), and useragent (User-Agent string). For JSON, encode the body with json.encode and set the Content-Type header to application/json. Decode string responses with json.decode and handle its error return.

Parameters

url string.

Absolute URL to request, normally using HTTPS.

success function.

Callback receiving body, HTTP status, and response headers.

failure function, optional.

Optional callback receiving the error message and available response details.

options table, optional.

Optional request method, headers, body, and user agent.