REST server on esp8266 and esp32: introduction – Part 1

Spread the love

How to create a REST server on esp8266 or esp32: introduction
How to create a REST server on esp8266 or esp32: introduction

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
GETRetrieve the URIs of the member resources of the collection resource in the response body.
POSTCreate 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.
PUTReplace 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.
PATCHUpdate 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.
DELETEDelete 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

  1. REST server on esp8266 and esp32: introduction
  2. REST server on esp8266 and esp32: GET and JSON formatter
  3. REST server on esp8266 and esp32: POST, PUT, PATCH, DELETE
  4. REST server on esp8266 and esp32: CORS request, OPTION and GET
  5. REST server on esp8266 and esp32: CORS request, OPTION and POST

Spread the love

12 Responses

  1. James says:

    Renzo, you seem to have the gift of a natural programmer, reminding me of my friend.

    FWIW, I used to know a guy able to program as easy as breathing. He unknowingly inspired me to learn but I will never come close to his capability, my interest is electronic interface like data collection and system control, his was purely like breathing (suffocate and die if you can’t do it).

    Chow! 😉

  2. Oliver says:

    Hello. Can i actually call my esp32 with this sketch from React with axios? That would be perfect.

    • Hi Oliver,
      sure, this project ABB (ex Power One) Aurora Web Inverter Monitor (WIM): project introduction – 1 is created with WeMos D1 mini as REST, WebSocket and Web server,

      the front-end application is React, Redux (redux-logic as middleware) using axios.
      With webpack I generate a series of GZipped file.

      The tutorial with WebServer, how to manage Token authentication, gzip management ecc. is ready but I can’t share It now, but if you open a topic on Forum I can attach the logic (of redux-logic middleware) where I call the esp8266.

      Bye Renzo

      • Oliver says:

        Hello Renzo. So I can bypass Node.js and can handle it directly with React. Yes, that would be great. Thanks.

        • Hi Oliver,
          Yes, nodejs Is used in the transpiling process and next start a web server that only serve transpiled js to the browser.

          If you create a dist with transpiled objects, esp8266 or esp32 can work like a web server to serve static elements.

          If you use standard create react web app I can give you a webpack config to generate dist.

          Bye Renzo

          • Oliver says:

            Maybe you know a good tutorial, where I can work me in with ESPAsyncWebServer and preferable PlatformIO with visual studio Code. It looks to me, like I can use it similiar like express. But I am unable to find a good source to figure that out.

  3. dgeigerd says:

    Hi,
    i am programming this in the Arduino IDE and i get the Error:
    ‘restServerRouting’ was not declared in this scope
    but i have included all the librarys. Do you know how to fix this?

Leave a Reply

Your email address will not be published. Required fields are marked *