Group 1 Laboratory#5 NodeMCU IOT - RESTful API Basic and Consuming RESTFUL API
Group 1 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.
1
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.
● POST: Adds new information to the server.
● PUT: Updates existing information.
2
● DELETE: Removes information from the server.
Example
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": "[email protected]"
}
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.
3
"name": "John Smith",
"email": "[email protected]"
}
]
{
"name": "Alice Johnson",
"email": "[email protected]"
}
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 <ESP8266HTTPClient.h>
4
#include <ArduinoJson.h>
const char* ssid = "TIPIANS"; // 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() {
Serial.begin(115200); // Start the Serial communication to send messages to the
computer
delay(10);
Serial.println('\n');
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");
void loop()
{
if (WiFi.status() == WL_CONNECTED)
{
WiFiClient client;
HTTPClient http; //Object of class HTTPClient
http.begin(client, "http://jsonplaceholder.typicode.com/users/1");
int httpCode = http.GET();
if (httpCode > 0)
{
DynamicJsonDocument jsonBuffer(370); // Adjust the buffer size according to your JSON
response size
DeserializationError error = deserializeJson(jsonBuffer, http.getString());
if (!error)
{
int id = jsonBuffer["id"];
const char* name = jsonBuffer["name"];
const char* username = jsonBuffer["username"];
const char* email = jsonBuffer["email"];
5
Serial.print("Name:");
Serial.println(name);
Serial.print("Username:");
Serial.println(username);
Serial.print("Email:");
Serial.println(email);
}
else
{
Serial.println("Failed to parse JSON");
}
}
http.end(); //Close connection
}
delay(60000);
}
Screenshot:
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:
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <ESP8266HTTPClient.h>
// Wi-Fi credentials
const char* ssid = "YOUR_WIFI_SSID";
6
const char* password = "YOUR_WIFI_PASSWORD";
// Server endpoint
const char* serverName = n";
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;
7
Serial.println("Error in sending POST: " + String(httpResponseCode));
void loop() {
// Nothing here
}
8
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):
mkdir C:\Users\<YourUsername>\Desktop\MockServer
cd C:\Users\<YourUsername>\Desktop\MockServer
9
■ In the MockServer folder, create a file named db.json.
■ You can do this using a text editor or by running the following command
in the terminal:
■ 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":
"[email protected]" },
{ "id": 2, "name": "Jane Smith", "email":
"[email protected]" },
{ "id": 3, "name": "Alice Johnson", "email":
"[email protected]" }
]
}
10
3. Run JSON Server on Windows
■ Open Command Prompt or Terminal and navigate to the MockServer folder:
cd C:\Users\<YourUsername>\Desktop\MockServer
■ Run JSON Server. use the following command to run the JSON Server:
11
■
12
Working on NodeMCU to consume the Restful API.
http.begin(client, "http://10.2.4.203:3000/users/1");
where the server_IP is the ip address of the computer where the json_server is
running.
o Ensure 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.
13
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://10.2.4.203:3000/users");
● Access http://localhost:3000/users in a browser or use a tool like Postman to verify that the
new user was added successfully to the db.json file.
14
Supplemental Activity #3:Simple Web browser to Mock API Server
1. Copy the code on Supplemental Activity #2.
2. Modify it such that you will have a web application that contains the following fields:
a. username
b. password
c. name
d. address
e. contact number
3. Add a button to save the content of the form
4. Develop a code that will connect the web app to the NODEMCU and update the mock server.
Web App Testing:
15
16
Postman Testing:
17
VIDEO DEMO.mp4
7. Conclusion:
18
the POST which sends data to the server. The payload was used in this scenario to update and
create contents of the server. We performed the GET request by retrieving the names of the
userdata using the local ip address which needs to be connected to both the NodeMCU and
desktop. We were also able to send data by using the POST request which allowed us to add
new entries to the users. From this two commands , we used Postman to test and verify the
local host and the db.json file. We created a simple web browser to display the user’s
username, password, name, address and contact number.
__________________
Printed Name and Signature of Faculty Member
19