Introduction
In the last article we created a Python script to collect environmental data from a Sense Hat equipped Raspberry PI.
This article will add to that by creating a web service that will display all logged entries. In the next blog post we will add the ability to upload data from PI to the web service.
This web service will be running on the Raspberry PI but of course it could run anywhere as long as it supplies an endpoint to enable consumers to use it.
Building a RESTful API – do’s and do not’s
The web service will use RESTful principles. REST is a set of best practises to use when designing an API. In a nutshell:
- DO return JSON
- DO set the Content-Type header correctly i.e.
application/json
. Note, when using the PATCH method the content type must beapplication/merge-patch+json
- DON’T use verbs e.g. use
/songs
instead oflistSongs/
- DO use plurals e.g.
/api/songs/2019
- DO return error details in the response body
- DO make use of status codes when returning errors
- 400-bad request, 403-forbidden, 404-not found, 401-unauthorised, 500 server error
- For CRUD operation return the following codes
Method | Description | URL | Response code |
---|---|---|---|
GET | retrieve data | api/customers | 200 |
POST | create data | api/customers {“name”:”jon”, “email”:”a@a.com”} | 201 |
PUT | update data | api/customers/1 {“name”:”dave”,”email”:”b@a.com”} | 200 |
DELETE | delete data | api/customers/1 | 204 |
PATCH | update partial data | api/customers/1 {“op”:”replace”,”path”:”/email”,”value”:”a@a.com”}] | 204 |
Defining the endpoints
Our API will have three endpoints. This article is focussed on the first one, to list entries. The other two will be addressed in a later post.
/api/environment/entries
– to list all entries
The resulting JSON will be something like this:
[
{
"id":1,
"date":"2020/06/06 15:34:01",
"temperature":"24.48",
"pressure":"998.32",
"humidity":"44.9"
}
]
/api/environment/
– to create a new entry
/api/environment/meta
– to retrieve metadata such as number of entries, average temperature and last entry that was uploaded
Creating the web service using Express
Let’s get started! Connect your PI to the network either wirelessly or using a cable. I use an Ethernet cable directly plugged it into my laptop.
- Power up your PI!
- SSH into your PI. I used PuTTY
- Navigate to the
collector
directory we created the last blog post. - mkdir server
- cd server
We are going to use Node.js to create our server. Node.js is based on the Chrome V8 Javascript engine but has added modules to deal with IO, HTTP and many more. It is basically a Javascript engine wrapped in a C++ exe. It has a single-threaded handler which hands off requests in an asynchronous manner so it is very suitable to quick high-throughput requests.
Out of the box it is very easy to create a simple REST API. We will be using another node module called express which makes managing routing much easier.
So first things first if you haven’t already done so install node
and npm
on your PI. Here is a noice instructable showing how to do it.
https://www.instructables.com/id/Install-Nodejs-and-Npm-on-Raspberry-Pi/
When you have successfully installed node and npm return to the server
directory we created earlier. Now we can install express which is a lightweight framework for creating REST APIs.npm install express --save
Create a file called index.js
using your editor of choice. I used nano.nano index.js
Paste the following:
// import the express module and create the express app
const express = require('express');
const app = express();
// install middleware that can encode the payload
app.use(express.urlencoded({extended:false}));
// create an array to hold the environmental data
const data = [];
// End points for the web service
//list entries
app.get('/api/environment/entries', (req,res) => {
res.send(data); //Just send at empty array for now
} );
// create a web server, running on your port of choice or 3000
const port = process.env.PORT || 3000;
app.listen(port,() => {
console.log(Listening on port ${port});
} );
This server will respond to HTTP GET requests at the /api/environment/entries
endpoint listening on port 3000.
Start the node servernode index.js
Open your browser and go tohttp://raspberrypi:3000/api/environment/entries
The result will not be very exciting as you will just see an empty array returned in the browser. However, give yourself a pat on the back. You have created your first fledgling web service!
Great wordpress blog here.. It’s hard to find quality writing like yours these days. I really appreciate people like you! take care