Laboratory#5 NodeMCU IOT - RESTful API Basic and Consuming RESTFUL API
Laboratory#5 NodeMCU IOT - RESTful API Basic and Consuming RESTFUL API
1. Objective(s):
In this laboratory, you will explore the basics of using RESTful APIs with NodeMCU, an open-source
IoT platform. REST (Representational State Transfer) is an architectural style commonly used for
designing networked applications, including IoT systems. RESTful APIs provide a standardized way
for devices and services to communicate by using simple HTTP methods like GET, POST, PUT, and
DELETE.
● Identify and describe the main components of RESTful APIs, including endpoints, HTTP
methods, headers, and bodies.
● Use NodeMCU to make HTTP GET and POST requests to interact with RESTful API
endpoints.
● Develop a simple IoT system using NodeMCU that communicates with a server through
RESTful APIs.
3. Materials
● NodeMCU ESP8266 development board.
A RESTful API (Representational State Transfer Application Programming Interface) is a type of web
service that allows applications to communicate over the internet using standard HTTP methods. It
follows the REST architectural style, which is designed to be lightweight, stateless, and scalable, making
it well-suited for distributed systems like cloud services and IoT applications.
https://api.example.com/users
This endpoint is where you direct your HTTP requests to interact with a particular resource (in this
case, a user resource).
Example
Imagine you want to get all users from a service. The endpoint could look like:
https://api.example.com/users
2. The Method
The method specifies the type of action you want to perform on the resource. The main HTTP
methods used in RESTful APIs are:
● GET: Retrieves information from the server.
Example
2
If you want to create a new user, you would use:
● Endpoint: https://api.example.com/users
● Method: POST
3. The Headers
Headers provide metadata about the request, such as the type of content being sent or authorization
credentials. Common headers include:
● Content-Type: Specifies the format of the data, e.g., application/json.
● Authorization: Provides the authentication details, e.g., a token for secure access.
Example
If you’re sending JSON data, your headers might look like:
Content-Type: application/json
Authorization: Bearer YOUR_ACCESS_TOKEN
Example
If you’re creating a new user, your request body might look like:
{
"name": "Jane Doe",
"email": "jane.doe@example.com"
}
Combined with the endpoint and method, you’d make a POST request to
https://api.example.com/users with the above JSON data in the body to add a new user.
● Method: GET
● Headers: Authorization: Bearer YOUR_ACCESS_TOKEN
This would return a list of users:
[
{
"id": 1,
"name": "Jane Doe",
"email": "jane.doe@example.com"
},
{
"id": 2,
3
"name": "John Smith",
"email": "john.smith@example.com"
}
]
● Method: POST
● Headers:
o Content-Type: application/json
o Authorization: Bearer YOUR_ACCESS_TOKEN
● Body:
{
"name": "Alice Johnson",
"email": "alice.johnson@example.com"
}
The server would respond with a confirmation, indicating that the new user was successfully added,
typically by providing a unique user ID or success message.
4. Procedures
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <ESP8266HTTPClient.h>
// Wi-Fi credentials
const char* ssid = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";
// Server endpoint
const char* serverName = "https://reqres.in/api/login";
void setup() {
// Initialize serial monitor
Serial.begin(115200);
// Connect to Wi-Fi
Serial.print("Connecting to Wi-Fi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("Connected to Wi-Fi");
HTTPClient https;
void loop() {
// Nothing here
}
● Monitor the Serial output to view the data received from the API, including the user’s name and email.
6
Consuming RESTful API with Payload
In this part, we will make an HTTP POST request to a RESTful API endpoint, where we send data in the
request body, also known as the payload. This is particularly useful when we need to update or create
new resources on the server.
The payload in this context refers to data sent with the HTTP request, typically in JSON format.
Below is an example code to send a POST request to a RESTful API with data:
const char* ssid = ""; // The SSID (name) of the Wi-Fi network you want to
connect to
const char* password = "?"; // The password of the Wi-Fi network
void setup() {
int i = 0;
while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
delay(1000);
Serial.print(++i); Serial.print(' ');
}
Serial.println('\n');
Serial.println("Connection established!");
Serial.print("IP address:\t");
Serial.println(WiFi.localIP()); // Send the IP address of the ESP8266 to the
computer
void loop() {
if (WiFi.status() == WL_CONNECTED) {
WiFiClient client;
7
HTTPClient http;
} else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end(); // Close connection
}
delay(5000); // Delay before making the next request
}
● Monitor the Serial output to view the connection from the API.
6. Supplemental Activity
Supplemental Activity #1: Creating a Mock Server and Testing GET Requests with NodeMCU
Task:
1. Set up a mock RESTful server using JSON Server.
2. Create and host mock API endpoints.
3. Use the NodeMCU to consume data from the mock server via a GET request.
Steps:
1. Set Up JSON Server:
o Install JSON Server on your computer. You can do this by running the following
command in your terminal (Node.js must be installed):
8
2. Create a Sample JSON File
o Create a Specific Folder for Your Project:
■ Navigate to a location on your computer where you want to store your
mock server files. For example, you could create a folder called
MockServer on your Desktop.
■ Command to Create the Folder (Optional):
mkdir C:\Users\<YourUsername>\Desktop\MockServer
cd C:\Users\<YourUsername>\Desktop\MockServer
■ Open the db.json file in your preferred text editor (e.g., Notepad, VS
Code) and add the following sample data:
{
"users": [
{ "id": 1, "name": "John Doe", "email":
"john.doe@example.com" },
{ "id": 2, "name": "Jane Smith", "email":
"jane.smith@example.com" },
{ "id": 3, "name": "Alice Johnson",
"email": "alice.johnson@example.com" }
]
}
cd C:\Users\<YourUsername>\Desktop\MockServer
9
■ Run JSON Server. use the following command to run the JSON Server:
http.begin(client, "http://<YOUR_server_IP>:3000/users/1");
where the server_IP is the ip address of the computer where the json_server is
running.
oEnsure that both your NodeMCU and the computer hosting the mock server are on the
same network.
2. Test and Verify:
o Upload the modified code to the NodeMCU.
o Check the Serial Monitor for the data fetched from the mock server. Verify that it
successfully retrieves the user information.
Supplemental Activity #2: Creating a Mock Server and Testing POST Requests with NodeMCU
(with Payload)
Task:
1. Set up a mock RESTful server using JSON Server.
2. Use the NodeMCU to send data to the server via a POST request with a JSON payload.
Steps:
1. Modify JSON Server Configuration for POST Requests:
● Use the same db.json file from Supplemental Activity #1.
● JSON Server will handle POST requests to /users to add new entries to the users list.
2. Modify NodeMCU Code for POST Requests with Payload:
● Use the following endpoint to send data:
http.begin(client, "http://<YOUR_COMPUTER_IP>:3000/users");
10
● Update the payload with sample data:
7. Conclusion:
__________________
Printed Name and Signature of Faculty Member
12