When we speak about microservice framework we can’t speak about REST server.
RESTful (representational state transfer) API (application programming interface) DLs (description languages) are formal languages designed to provide a structured description of a RESTful web API that is useful both to a human and for automated machine processing. API Description Languages are sometimes called interface description languages (IDLs). The structured description might be used to generate documentation for human programmers; such documentation may be easier to read than free-form documentation, since all documentation generated by the same tool follows the same formatting conventions. Additionally, the description language is usually precise enough to allow automated generation of various software artifacts, like libraries, to access the API from various programming languages, which takes the burden of manually creating them off the programmers. (Cit. Wiki)
This simple software architecture is very popular for various reason, and It’s quite simple to implement with our microcontroller like esp32 or esp8266.
Initialization
We can use standard ESP library
#include <ESP8266WebServer.h>
Than we must configure the port and instatiate the server:
#define HTTP_REST_PORT 8080
ESP8266WebServer httpRestServer(HTTP_REST_PORT);
On setup we are going to add all the routing (in the next section we explain better) and begin the server:
restServerRouting();
httpRestServer.begin();
And in the loop function we add the handle:
httpRestServer.handleClient();
Routing
RESTful architecture provide a standard set of verbs:
REST verbs
GET | Retrieve the URIs of the member resources of the collection resource in the response body. |
POST | Create a member resource in the collection resource using the instructions in the request body. The URI of the created member resource is automatically assigned and returned in the response Location header field. |
PUT | Replace all the representations of the member resources of the collection resource with the representation in the request body, or create the collection resource if it does not exist. |
PATCH | Update all the representations of the member resources of the collection resource using the instructions in the request body, or may create the collection resource if it does not exist. |
DELETE | Delete all the representations of the member resources of the collection resource. |
When change verbs the only think that really change is the data transfer, the behaivor is coded by you.
void getHelloWord() {
server.send(200, "text/json", "{\"name\": \"Hello world\"}");
}
void restServerRouting() {
server.on("/", HTTP_GET, []() {
server.send(200, F("text/html"),
F("Welcome to the REST Web Server"));
});
server.on(F("/helloWorld"), HTTP_GET, getHelloWord);
}
Here 2 GET operation, the first have as endpoint /
and return every time a text/html
mime type with “Welcome to the REST Web Server” content.
But what mean?
Using GET verb is only the type of request and REST server use that to mange the request.
The mimetype is used from browser to understand the type of result content and how It must be processed the result, in this case text/html is parsed by the browser like html text and show It on page.
The content is the result of request.
For esp32 you must only change this include
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
to
#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>
Here a subset of commons mime types:
Mimetype
Here the complete code:
/*
* Simple hello world Json REST response
* by Mischianti Renzo <https://mischianti.org>
*
* https://mischianti.org/
*
*/
#include "Arduino.h"
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
const char* ssid = "<your-ssid>";
const char* password = "<your-passwd>";
ESP8266WebServer server(80);
// Serving Hello world
void getHelloWord() {
server.send(200, "text/json", "{\"name\": \"Hello world\"}");
}
// Define routing
void restServerRouting() {
server.on("/", HTTP_GET, []() {
server.send(200, F("text/html"),
F("Welcome to the REST Web Server"));
});
server.on(F("/helloWorld"), HTTP_GET, getHelloWord);
}
// Manage not found URL
void handleNotFound() {
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
void setup(void) {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// Activate mDNS this is used to be able to connect to the server
// with local DNS hostmane esp8266.local
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
// Set server routing
restServerRouting();
// Set not found response
server.onNotFound(handleNotFound);
// Start server
server.begin();
Serial.println("HTTP server started");
}
void loop(void) {
server.handleClient();
}
Afther upload your sketch (Here the guide WeMos D1 mini (esp8266), specs and IDE configuration – Part 1) you must identify the ip or the local name.
You can grab the IP from serial output.
Connected to ...
IP address: 192.168.1.122
MDNS responder started
HTTP server started
Than you can put on your browser directly the Get REST url http://192.168.1.122/helloWorld to get Welcome message. The browser process all call as GET, so this end-point works good.
You can try to call your device with the name http://esp8266.local, this is the mDNS name.
mDNS
In computer networking, the multicast DNS (mDNS) protocol resolves hostnames to IP addresses within small networks that do not include a local name server. It is a zero-configuration service, using essentially the same programming interfaces, packet formats and operating semantics as the unicast Domain Name System (DNS). Although Stuart Cheshire designed mDNS as a stand-alone protocol, it can work in concert with standard DNS servers.
To work need Bonjour Print Services for Windows or Avahi for Linux.
When call the REST endpoint helloWorld, if you click F12
key on your browser and go to Networking and select the call you can see that It’s processed as text/json format.
Thanks
- REST server on esp8266 and esp32: introduction
- REST server on esp8266 and esp32: GET and JSON formatter
- REST server on esp8266 and esp32: POST, PUT, PATCH, DELETE
- REST server on esp8266 and esp32: CORS request, OPTION and GET
- REST server on esp8266 and esp32: CORS request, OPTION and POST