mercoledì 21 febbraio 2018

Simple HTTP REST Server on ESP8266

My follower and my friends know that I am not a fan of Web Server on ESP8266 as this has negative architectural implications. In any case this is not the topic of this post.

In the past few days I have received some requests on how to create a Web Server on ESP8266.

As the typical use for ESP8266 is mostly as IoT device I think it make much more sense to show how to create a simple HTTP REST server on ESP8266 in order to manage some resources.

In this post I show how to manage 1 Led through a RESTful API on ESP8266.

Testing Circuit

The testing circuit is quite simple and is shown below


The code of the REST server is available on my GitHub here


In order to test the REST server I use the curl command from command line (for the one who prefer a graphical interface I suggest the great  postman)


The first command I execute is a HTTP GET of the server's root

The IP address will be certainly different in your case, so please replace it with your own (it is printed on Serial Monitor during ESP boot).

As you can see the string defined on line 118 is provided back by the server.

GET leds

Now time to query the REST server for leds resource through a HTTP GET

As you can see the HTTP code 204 is provided back meaning that the resource is neither available nor is empty.

POST leds

Now let's create the resource by providing a JSON body as part of the HTTP POST request. The JSON contains the following information:

  • id: a unique identifier of the resource
  • gpio: GPIO number on which the resource (led) is connected
  • status: resource's status (0 or LOW)

Now the server replies back with a 201 meaning that the resource has been successfully created.

Now I query again the resource through GET and this time server replies with 200 and with the JSON representation of the resource.

PUT leds

Now that the resource is available it is possible to modify it with a HTTP PUT

Also in this case I need to pass a JSON representation in the body of the request in which I set the status to 1(HIGH).

The server replies with a 200 code meaning that the update is successful and the led is turning on

In the same manner I can updated it with status = 0

and the led turns off

In the sample code I also manage other cases.

As an example if I update (PUT) a resource with id = 2

Server replies with 404 telling me that the resource is not existing 

I let to the reader the implementation of the DELETE method.

That's it folks!!! :)