Using REST APIs with Helm

Helm has built-in support for both creating and accessing JSON REST APIs. This replaces the older “WebActive” property of the Root Panel, which is now deprecated.

Accessing REST APIs

To start, add a REST API Device to your panel. You’ll find this in the “Other” section in the Parts Bin. Set the URL property of the device to the base URL of your REST server. Both HTTP and HTTPS are supported.

You can send GET, POST and DELETE commands from Lua scripts. Helm automatically converts between Lua tables and JSON, so no parsing of the result is needed.

Here’s an example of s script making a GET request and displaying the results in HELM components.

-- Get the specified post

local p = H.RESTDevice_1:Get("/posts/" .. H.DROPDOWN_1.Value)

-- JSON return is automatically converted to a Lua table

H.TEXTFIELD_1.Text = p.body
H.LABEL_3.Text = p.title

Query parameters can be added to GET requests by passing a second Lua table:

-- Get the posts from the specified user

local p = H.RESTDevice_1:Get("/posts", {userId = H.DROPDOWN_2.Value})

Here’s a Helm panel that shows these techniques, using the dummy REST server at https://jsonplaceholder.typicode.com/

REST API Servers

As well as consuming REST APIs, Helm can also act as an HTTP REST server. For this, add a REST API Server from the parts bin to your panel. The REST Server can also serve static assets directly from a filesystem, allowing  complex web apps to be run and served directly from a Helm panel.

The key properties of the Server are as follows:

  • Port:  The TCP Port to listen on. Default = 888
  • APIRoot: The root URL for API requests. Default = “/api”
  • WebPath: The filesystem path for accessing static resources like HTML, CSS and Images
  • OnPost/Get/Delete:  Event scripts triggered when a request is receiver
  • Document : contains requested document – Only valid during event scripts
  • Body: document body for POST.  Only valid during event scripts

If a GET request is received that doesn’t match the APIRoot property, the WebPath folder is used to serve the asset if found.

A GET script returns a Lua table which is sent as the JSON body to the client.

if H.RESTSERVER_1.Document == "/text" then
  H.RESTSERVER_1.ErrorStatus = 200
  return {text = H.TEXTFIELD_1.Text,
          when = os.date()
          }
end

Here is a pair of Helm panels which demonstrate server and client. Run both on the same machine, and use the client panel to read/write data on the server panel. You can also use the Postman collection here to test and communicate with the REST Server example panel.

https://www.postman.com/rascular/workspace/rascular-technology/collection/713943-ef5929d7-c610-497c-9402-03fcabb9354f?action=share&creator=713943

Restclientpanel (32 KiB)
Restserver (23 KiB)