SlideShare a Scribd company logo
APIs for your Hardware
Electric Imp
Matt Haines
Community Manager
@beardedinventor
What are we doing tonight
● HTTP Handler Deep Dive
● APIs that change hardware states
● APIs that read hardware states
The Circuit
HTTP Handlers
● The HTTP Handler is the code that executes
when your agent receives an incoming http
request
● Register your handler with:
http.onrequest(HTTPHandler)

● http://electricimp.com/docs/api/httphandler/
Basic Handler
function HTTPHandler(req, resp) {
// ALWAYS WRAP YOUR HANDLERS IN A TRY/CATCH
try {
// "200: OK" is standard return message
resp.send(200, "OK");
} catch (ex) {
// Send 500 response if error occured
resp.send(500, format("Agent Error: %s", ex));
}
}
The Request table
method - The method (GET, PUT, POST, etc)
path - The HTTP path minus the agentURL
query - Table containing the query parameters
body - The body of the request
headers - Table containing the request
headers
Let’s make an API
function HTTPHandler(req, resp) {
try {
// "200: OK" is standard return message
logRequest(req);
resp.send(200, "OK");
} catch (ex) {
// Send 500 response if error occured
resp.send(500, format("Agent Error: %s", ex));
}
}
function logRequest(req) {
server.log(format("Method: %s", req.method));
server.log(format("Path: %s", req.path));
server.log(format("Body: %s", req.body));
server.log("Query Parameters:");
foreach(k,v in req.query) {
server.log(format("%s: %s", k, v));
}
server.log("Headers:");
foreach(k,v in req.headers) {
server.log(format("%s: %s", k, v));
}
}
Let’s make some requests
// basic request
curl "agenturl"
// set the method
curl -X POST "agenturl"
// set a path and some query parameters
curl -X POST "agenturl/api?led1=1&led2=test"
// set a header
curl -X PUT -H "apikey:123" "agenturl"
// send some data in the body
curl -X PUT -H "apikey:123" "agenturl" --data "{ "foo": "bar" }"
So what..
● Use this information to build powerful APIs:
○
○
○
○

path - what resource we’re interacting with
method - what we’re doing with the resource
body/query - data we need
headers - authentication, etc

● Example:
// Get the state of the LED
curl -X GET "agenturl/led"
// Set the state of the LED
curl -X GET -H "apikey: 123" "agenturl/led" --data "{ "state": 1 }”
APIs to Set Hardware
● When we get a request
○
○
○
○
○

Check the verb
Check the path
Validate the data
Send the data to the device
Send a response

● When the device gets a message
○ Do something with it
Simple Device Code
// configure hardware
led <- hardware.pin9;
led.configure(DIGITAL_OUT);
// set LED from server
agent.on("setLed", function(state) {
led.write(state);
});
Let’s make an API
// here's the important bit
local path = req.path.tolower();
if (req.method == "POST") {
if (path == "/led" || path == "/led/") {
if (req.body != null && req.body.len() > 0) {
local data = http.jsondecode(req.body);
if ("state" in data) {
device.send("setLed", data.state.
tointeger());
resp.send(200, "OK");
}
}
resp.send(406, "Not Acceptable - Missing 'state'");
}
}
Let's make some requests
// wrong url
curl -X POST "agenturl"
// proper url, but no data
curl -X POST "agenturl/led"
// proper url, and proper data
curl -X POST "agenturl/led" --data "{ "state": 0 }"
What about reading data
● Two ways to query data from the device:
○ Send data from device to agent whenever state
changes (or at regular intervals)
○ Make a round trip from agent → device → agent

● First method is easy, and fast, but no
guarantee data is up to date
● Second method requires a LOT more code,
and adds some time (as we need to make a
round trip to the device)
Sending Data to the Device
// configure hardware
led <- hardware.pin9;
led.configure(DIGITAL_OUT);
function setLed(state) {
led.write(state);
agent.send("ledState", state);
}
agent.on("setLed", setLed);
button <- hardware.pin1;
function buttonStateChange() {
setLed(1-led.read());

// invert state

}
button.configure(DIGITAL_IN_PULLUP, buttonStateChange);
Catch and Store Message in Agent
ledState <- "Unknown";
agent.on("ledState", function(state) {
ledState = state;
}
Let's make an API
// here's the important bit
if (req.method == "GET") {
if (path == "/led" || path == "/led/") {
resp.send(200, http.jsonencode({state = ledState}));
}
}
Let's make some requests
// wrong url
curl -X GET "agenturl"
// proper url
curl -X GET "agenturl/led"
What about security
● All communication is HTTPS
● Agent URLs can't be crawled
● There are 6412 so guessing them is.. hard
●
●
●
●

Security by obscurity
API Keys
Basic Auth
HMAC-SHA Signatures
What's Next
● Write webpages or apps to interact with API
● Try implementing some of the auth methods
● Class to handle/delegate incoming requests
● Long polling
● Serve HTML pages from HTTP Handler

More Related Content

PDF
Neoito — React 101
PDF
Rntb20200805
 
PDF
Angular server-side communication
PDF
React native-firebase startup-mtup
 
PDF
Angular promises and http
PDF
Scala, XML and GAE
PDF
BDD in iOS with Cedar
PDF
Device Simulator with Akka
Neoito — React 101
Rntb20200805
 
Angular server-side communication
React native-firebase startup-mtup
 
Angular promises and http
Scala, XML and GAE
BDD in iOS with Cedar
Device Simulator with Akka

What's hot (11)

PPTX
Microservices - Components
PDF
Synchronize applications with akeneo/batch
PPT
Developing A Real World Logistic Application With Oracle Application - UKOUG ...
PDF
My Top 5 APEX JavaScript API's
PPTX
Durable functions
PDF
Automation in angular js
PPTX
Creating sub zero dashboard plugin for apex with google
KEY
Polyglot parallelism
PPTX
Angular 1.x vs. Angular 2.x
PDF
Monitoring und Metriken im Wunderland
 
PPTX
Java on Windows Azure
Microservices - Components
Synchronize applications with akeneo/batch
Developing A Real World Logistic Application With Oracle Application - UKOUG ...
My Top 5 APEX JavaScript API's
Durable functions
Automation in angular js
Creating sub zero dashboard plugin for apex with google
Polyglot parallelism
Angular 1.x vs. Angular 2.x
Monitoring und Metriken im Wunderland
 
Java on Windows Azure
Ad

Similar to Api workshop (20)

PDF
Live Streaming & Server Sent Events
PPTX
Ajax for dummies, and not only.
PPTX
PHP Continuous Data Processing
PDF
Apollo ecosystem
PDF
Introducere in web
PDF
Google App Engine Developer - Day2
PDF
Cqrs api v2
PPTX
Saving Time And Effort With QuickBase Api - Sergio Haro
PDF
Case study ap log collector
PDF
Uni w pachube 111108
PDF
pio_present
PDF
Rethinking Syncing at AltConf 2019
PDF
Rhebok, High Performance Rack Handler / Rubykaigi 2015
PPTX
Spring Boot and REST API
PPT
J query 01.07.2013.html
PPT
J query 01.07.2013
PDF
Future of Web Apps: Google Gears
PDF
Manage all the things, small and big, with open source LwM2M implementations ...
PDF
21servers And Applets
PPT
Core Php Component Presentation
Live Streaming & Server Sent Events
Ajax for dummies, and not only.
PHP Continuous Data Processing
Apollo ecosystem
Introducere in web
Google App Engine Developer - Day2
Cqrs api v2
Saving Time And Effort With QuickBase Api - Sergio Haro
Case study ap log collector
Uni w pachube 111108
pio_present
Rethinking Syncing at AltConf 2019
Rhebok, High Performance Rack Handler / Rubykaigi 2015
Spring Boot and REST API
J query 01.07.2013.html
J query 01.07.2013
Future of Web Apps: Google Gears
Manage all the things, small and big, with open source LwM2M implementations ...
21servers And Applets
Core Php Component Presentation
Ad

More from Matt Haines (6)

PDF
Best Practices for Design Hardware APIs
PPTX
Robots conf microcontroller and iot survey
PPTX
Your Device Needs an API
PPTX
Hackbright Workshop
PPTX
Electric Imp - Hackathon Intro
PPTX
electric imp Intro
Best Practices for Design Hardware APIs
Robots conf microcontroller and iot survey
Your Device Needs an API
Hackbright Workshop
Electric Imp - Hackathon Intro
electric imp Intro

Recently uploaded (20)

PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Approach and Philosophy of On baking technology
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Modernizing your data center with Dell and AMD
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
KodekX | Application Modernization Development
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Encapsulation theory and applications.pdf
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Empathic Computing: Creating Shared Understanding
Encapsulation_ Review paper, used for researhc scholars
MYSQL Presentation for SQL database connectivity
Diabetes mellitus diagnosis method based random forest with bat algorithm
Approach and Philosophy of On baking technology
NewMind AI Weekly Chronicles - August'25 Week I
“AI and Expert System Decision Support & Business Intelligence Systems”
Modernizing your data center with Dell and AMD
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
KodekX | Application Modernization Development
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Agricultural_Statistics_at_a_Glance_2022_0.pdf
20250228 LYD VKU AI Blended-Learning.pptx
The AUB Centre for AI in Media Proposal.docx
Understanding_Digital_Forensics_Presentation.pptx
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Encapsulation theory and applications.pdf
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Empathic Computing: Creating Shared Understanding

Api workshop

  • 1. APIs for your Hardware Electric Imp Matt Haines Community Manager @beardedinventor
  • 2. What are we doing tonight ● HTTP Handler Deep Dive ● APIs that change hardware states ● APIs that read hardware states
  • 4. HTTP Handlers ● The HTTP Handler is the code that executes when your agent receives an incoming http request ● Register your handler with: http.onrequest(HTTPHandler) ● http://electricimp.com/docs/api/httphandler/
  • 5. Basic Handler function HTTPHandler(req, resp) { // ALWAYS WRAP YOUR HANDLERS IN A TRY/CATCH try { // "200: OK" is standard return message resp.send(200, "OK"); } catch (ex) { // Send 500 response if error occured resp.send(500, format("Agent Error: %s", ex)); } }
  • 6. The Request table method - The method (GET, PUT, POST, etc) path - The HTTP path minus the agentURL query - Table containing the query parameters body - The body of the request headers - Table containing the request headers
  • 7. Let’s make an API function HTTPHandler(req, resp) { try { // "200: OK" is standard return message logRequest(req); resp.send(200, "OK"); } catch (ex) { // Send 500 response if error occured resp.send(500, format("Agent Error: %s", ex)); } }
  • 8. function logRequest(req) { server.log(format("Method: %s", req.method)); server.log(format("Path: %s", req.path)); server.log(format("Body: %s", req.body)); server.log("Query Parameters:"); foreach(k,v in req.query) { server.log(format("%s: %s", k, v)); } server.log("Headers:"); foreach(k,v in req.headers) { server.log(format("%s: %s", k, v)); } }
  • 9. Let’s make some requests // basic request curl "agenturl" // set the method curl -X POST "agenturl" // set a path and some query parameters curl -X POST "agenturl/api?led1=1&led2=test" // set a header curl -X PUT -H "apikey:123" "agenturl" // send some data in the body curl -X PUT -H "apikey:123" "agenturl" --data "{ "foo": "bar" }"
  • 10. So what.. ● Use this information to build powerful APIs: ○ ○ ○ ○ path - what resource we’re interacting with method - what we’re doing with the resource body/query - data we need headers - authentication, etc ● Example: // Get the state of the LED curl -X GET "agenturl/led" // Set the state of the LED curl -X GET -H "apikey: 123" "agenturl/led" --data "{ "state": 1 }”
  • 11. APIs to Set Hardware ● When we get a request ○ ○ ○ ○ ○ Check the verb Check the path Validate the data Send the data to the device Send a response ● When the device gets a message ○ Do something with it
  • 12. Simple Device Code // configure hardware led <- hardware.pin9; led.configure(DIGITAL_OUT); // set LED from server agent.on("setLed", function(state) { led.write(state); });
  • 13. Let’s make an API // here's the important bit local path = req.path.tolower(); if (req.method == "POST") { if (path == "/led" || path == "/led/") { if (req.body != null && req.body.len() > 0) { local data = http.jsondecode(req.body); if ("state" in data) { device.send("setLed", data.state. tointeger()); resp.send(200, "OK"); } } resp.send(406, "Not Acceptable - Missing 'state'"); } }
  • 14. Let's make some requests // wrong url curl -X POST "agenturl" // proper url, but no data curl -X POST "agenturl/led" // proper url, and proper data curl -X POST "agenturl/led" --data "{ "state": 0 }"
  • 15. What about reading data ● Two ways to query data from the device: ○ Send data from device to agent whenever state changes (or at regular intervals) ○ Make a round trip from agent → device → agent ● First method is easy, and fast, but no guarantee data is up to date ● Second method requires a LOT more code, and adds some time (as we need to make a round trip to the device)
  • 16. Sending Data to the Device // configure hardware led <- hardware.pin9; led.configure(DIGITAL_OUT); function setLed(state) { led.write(state); agent.send("ledState", state); } agent.on("setLed", setLed); button <- hardware.pin1; function buttonStateChange() { setLed(1-led.read()); // invert state } button.configure(DIGITAL_IN_PULLUP, buttonStateChange);
  • 17. Catch and Store Message in Agent ledState <- "Unknown"; agent.on("ledState", function(state) { ledState = state; }
  • 18. Let's make an API // here's the important bit if (req.method == "GET") { if (path == "/led" || path == "/led/") { resp.send(200, http.jsonencode({state = ledState})); } }
  • 19. Let's make some requests // wrong url curl -X GET "agenturl" // proper url curl -X GET "agenturl/led"
  • 20. What about security ● All communication is HTTPS ● Agent URLs can't be crawled ● There are 6412 so guessing them is.. hard ● ● ● ● Security by obscurity API Keys Basic Auth HMAC-SHA Signatures
  • 21. What's Next ● Write webpages or apps to interact with API ● Try implementing some of the auth methods ● Class to handle/delegate incoming requests ● Long polling ● Serve HTML pages from HTTP Handler