0% found this document useful (0 votes)
32 views19 pages

Group 1 Laboratory#5 NodeMCU IOT - RESTful API Basic and Consuming RESTFUL API

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views19 pages

Group 1 Laboratory#5 NodeMCU IOT - RESTful API Basic and Consuming RESTFUL API

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Course: CPE400 - Embedded Systems Section: CPE 41S1

Name/s: GIAN KYLE APOLINARIO Date Performed: Oct. 4, 2024


RAYMART IRINGAN
TIMOTHY JAMES MANGAHAS
AARON KYLE OCARIZA
JOYCE EISLEY VIERNES
GABRIEL EDMUND G. VIÑAS
Date Submitted: Oct 8, 2024
Instructor: Engr. Mon Arjay Malbog

Laboratory Activity No. 4


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.

2. Intended Learning Outcomes (ILOs):

At the end of the activity student shall able to:


● Explain what RESTful APIs are and their role in IoT applications.
● 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.
● USB cable for programming the NodeMCU.
● Computer with Arduino IDE installed.
● NodeJS installed in your computer
● NPM node module installed in your computer
4. Discussion

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.

Key Features of RESTful APIs:


1. Stateless Communication - Each request from a client to the server must contain all the
information necessary to understand and process the request, meaning the server does not
store client context between requests.
2. Standard HTTP Methods - RESTful APIs use common HTTP methods to interact with
resources:
● GET: Retrieve data from the server.
● POST: Send new data to the server.
● PUT: Update an existing resource on the server.
● DELETE: Remove a resource from the server.
3. Resource-based - RESTful APIs operate on resources, which are typically represented by
URIs (Uniform Resource Identifiers). Resources can be anything that can be named, such as a
user, device, or document.
4. JSON or XML Format - RESTful APIs often use JSON (JavaScript Object Notation) or XML as
data formats for the request and response bodies due to their readability and ease of parsing.
5. Stateless and Cacheable - Responses from the API can be cached to improve performance
and reduce the need for redundant server requests.

Anatomy of REST API


A REST API request is made up of four key components: endpoint, method, headers, and data (or body).
Understanding these elements helps you effectively communicate with web services. Let's dive into each
component:
1. The Endpoint
The endpoint is the URL that specifies where the resource you want to access is located. It usually
follows a specific pattern, such as:

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

4. The Data (or Body)


The data, or body, is used when you need to send information to the server, typically with POST or PUT
requests. This data is usually structured in JSON or XML format.

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.

Example: Creating and Fetching Users


1. GET Request (Retrieve Data)
Suppose you want to retrieve all users from the server.
● Endpoint: https://api.example.com/users
● Method: GET
● Headers: Authorization: Bearer YOUR_ACCESS_TOKEN
This would return a list of users:
[
{
"id": 1,
"name": "Jane Doe",
"email": "[email protected]"
},
{
"id": 2,

3
"name": "John Smith",
"email": "[email protected]"
}
]

2. POST Request (Send Data)


Suppose you want to add a new user.
● Endpoint: https://api.example.com/users
● Method: POST
● Headers:
o Content-Type: application/json
o Authorization: Bearer YOUR_ACCESS_TOKEN
● Body:

{
"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

How to consume REST API using NodeMCU


Note: Before starting to code, make sure that your computer is install with nodeJS. and thec computer is
capable of connecting to the same network of that nodemuc or esps8266 or VV.

Step 1: Circuit Setup


1. Connect the NodeMCU to the Computer.
2. Open Arduino IDE and configure the settings. Make sure you select the correct board (NodeMCU) and the
appropriate port.
3. Test your circuit using example code from previous exercises, such as connecting to WiFi or turning an LED
on and off.

Step 2: Setting Up the Code:


1. Install the Arduino_JSON Library
● Go to Sketch > Include Library > Manage Libraries... in the Arduino IDE.
● Search for Arduino_JSON, and install the library by Benoit Blanchon.
2. Consuming a RESTful API with NodeMCU
● In this part, we will use a free and open-source API (http://jsonplaceholder.typicode.com/users/1)
to test the functionality of the NodeMCU, specifically for interacting with RESTful services. The endpoint
provides placeholder user data that we will request and process using the NodeMCU.
3. Code Example to Consume RESTful API Below is an example of how to make an HTTP GET request
using the NodeMCU to interact with a RESTful API.

#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');

WiFi.begin(ssid, password); // Connect to the network


Serial.print("Connecting to ");
Serial.print(ssid); Serial.println(" ...");

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;
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:

Running the Code


● Upload the code to the NodeMCU using Arduino IDE.
● Monitor the Serial output to view the data received from the API, including the user’s name and email.

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:

#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");

// Check if Wi-Fi is connected before making the request


if (WiFi.status() == WL_CONNECTED) {
WiFiClientSecure client;
client.setInsecure(); // Use this for testing only (bypass SSL certificate verification)

HTTPClient https;

// Specify the URL


https.begin(client, serverName);
https.addHeader("Content-Type", "application/json");

// JSON payload for login


String jsonPayload =
"{\"email\":\"[email protected]\",\"password\":\"cityslicka\"}";

Serial.println("Sending POST request...");

// Send the request


int httpResponseCode = https.POST(jsonPayload);

// Handle the response


if (httpResponseCode > 0) {
Serial.println("Response Code: " + String(httpResponseCode));
String response = https.getString();
Serial.println("Response Body: " + response);
} else {

7
Serial.println("Error in sending POST: " + String(httpResponseCode));

// Print additional error information


switch (httpResponseCode) {
case HTTPC_ERROR_CONNECTION_REFUSED:
Serial.println("Connection refused by server");
break;
case HTTPC_ERROR_SEND_HEADER_FAILED:
Serial.println("Failed to send HTTP header");
break;
case HTTPC_ERROR_SEND_PAYLOAD_FAILED:
Serial.println("Failed to send HTTP payload");
break;
case HTTPC_ERROR_NOT_CONNECTED:
Serial.println("Not connected to server");
break;
case HTTPC_ERROR_CONNECTION_LOST:
Serial.println("Connection lost during request");
break;
case HTTPC_ERROR_NO_HTTP_SERVER:
Serial.println("No HTTP server found");
break;
default:
Serial.println("Unknown error occurred");
break;
}
}

// End the HTTP connection


https.end();
} else {
Serial.println("Wi-Fi not connected");
}
}

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):

npm install -g json-server

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

o Navigate to Your Folder:

cd C:\Users\<YourUsername>\Desktop\MockServer

o Create and Add Sample JSON Data:

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:

echo {} > db.json

This creates an empty JSON file that you can edit.)

■ 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]" }
]
}

Save the file after adding the data.

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:

json-server --watch db.json

4. Test JSON Server


o To test that your JSON Server is running correctly, you can do the following:
■ Open a Browser:
■ Go to http://localhost:3000/users. You should see the list of users
from your db.json file.

11

12
Working on NodeMCU to consume the Restful API.

1. Modify NodeMCU Code to Consume Mock API:


o Change the endpoint in the NodeMCU code to match your mock server’s address:

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");

● Update the payload with sample data:

String jsonPayload = "{\"name\":\"Michael


Scott\",\"email\":\"[email protected]\"}";

● Upload the modified code to the NodeMCU.


3. Test and Verify:
● Check the Serial Monitor to confirm the response from the server.

● 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:

What conclusion can you make based on the activity?


From this activity we explored the fundamental functions of RESTful API using node MCU.
We explored the actions that can be performed specifically the GET which retrieves data and

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.

8. Assessment (Rubric for Laboratory Performance):

Rubric for NodeMCU and RESTful API Activity


Criteria Unsatisfactory (1) Satisfactory (2) Exemplary (3) Score
Unable to set up the Successfully set up the Successfully set up the
Setting up the Mock mock server (JSON mock server but with mock server with all
Server Server) or mock server incomplete or incorrect required endpoints and
does not run properly. configuration of endpoints. correct configuration.
Successfully made a GET Successfully made a
Consuming RESTful Unable to make a GET request with minor GET request, retrieving
API with NodeMCU request to retrieve issues/errors (e.g., partial data from the mock
(GET Request) data from the server. retrieval or incorrect server correctly without
endpoint). any errors.
Able to send a POST Successfully sent a
Sending Data with Unable to send a request with data to the POST request with the
NodeMCU (POST POST request with server but with errors in correct payload, and data
Request with Payload) data to the server. payload structure or was added to the mock
incomplete data. server without errors.
Other Comments/Observations:

Evaluated by: Date:

__________________
Printed Name and Signature of Faculty Member

19

You might also like