Calling Spark Function from Lua [Solved]

I can’t figure out how to call a Spark Function from Lua. I can easily execute the command from cURL, but when I use Lua’s Socket method, I always get a “301 Moved Permanently” error, and the URLs are correct. Below is my best attempt, but it still gets the 301 error. Anyone else using Lua?

local socket = require(“socket”)
local url = require(“socket.url”)
local http = require(“socket.http”)
local ltn12 = require(“ltn12”)

http.TIMEOUT = 5

postBody = “access_token=[My Access Token]”


– Execute the resulting URL, and collect the results as a Table

local resultTable = {}
local status, statusMsg = http.request{
url = “https://api.spark.io/v1/devices/[My Device ID]/[My Function]”,
sink = ltn12.sink.table(resultTable),
method = “POST”,
redirect = 1,
headers = {
[“Accept”] = “/”,
[“Content-Length”] = string.len(postBody),
[“Content-Type”] = “application/x-www-form-urlencoded”},
source = ltn12.source.string(postBody),
}

I got it working in Lua for Windows. I had to add in the Luasec library… https://github.com/brunoos/luasec/wiki

local socket = require(“socket”)
local https = require(“ssl.https”)
local ltn12 = require(“ltn12”)

https.TIMEOUT = 5

local body, code, headers, status = https.request(“https://api.spark.io/v1/devices/[My Device]/[My Function]”, “access_token=[My Access Token]”)
print(status)

2 Likes

Cool, glad you figured it out! :slight_smile:

Thanks,
David