Im rusty - http put code to text/json service


#1

Guys, Xively personal is being deprecated (4 years and they just shut it off with two weeks notice). anyhow, I’m trying to migrate my electric imp code to thingspeak…

I need to post an htttp request to the thingspeak api -
(from https://uk.mathworks.com/help/thingspeak/update-channel-feed.html#update_feed_text)
Text
Example POST:
POST https://api.thingspeak.com/update
api_key=XXXXXXXXXXXXXXXX
field1=73

The response is the entry ID of the update, for example: 18.
If the update fails, the response is 0.

My Squirrel code is this (key obfuscated) :slight_smile:slight_smile:
//Now do Again with ThingSpeak service
local Thingspeak_url = “https://api.thingspeak.com/update”;
//Dont need this except for debugging.
server.log(Thingspeak_url);
server.log(body); //print body for testing
server.log("pUT String: " + Thingspeak_url + “&api_key=SNYNAC5234T06W&field8=” + body)
local req = http.put(Thingspeak_url, { “Content-Type” : “text/xml” } ,“api_key=SNYNAC5Q9ZHJY06W field8=” + body); //add headers
local res = req.sendsync(); //send request
if(res.statuscode != 200) {
server.log("error sending message: “+res.body);
}else device.send(“status”, (res.statuscode + " Feed 2 OK”));


#2

I’m doing a very similar thing and it works. The only difference I think is sending the API Key in a header. My code is this:
local thingSpeakUrl = “http://api.thingspeak.com/update”;

function httpPostToThingSpeak(reading) {
local headers = {
“Content-Type” : “application/x-www-form-urlencoded”,
“X-THINGSPEAKAPIKEY” : “<api_key>”
};

// build the params to go on the URL
local data = “field1=” + reading.temp +
"&field2=" + reading.humid +
"&field3=" + reading.pressure +
"&field4=" + reading.lux +
"&field5=" + (reading.temp * 9/5 + 32);
local fullUrl = thingSpeakUrl+"?"+data;
server.log(fullUrl);

local request = http.get(fullUrl, headers);
request.sendasync(processResponse);


#3

Thankx Merlin13 - perfect ! it is now posting to my Xively and ThingSpeak in real time… next on to migrate the four years worth of data from Xively ! :frowning: