Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
27 views

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

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

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

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Course: Section:

Name/s: Date Performed:


Date Submitted:
Instructor:

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

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
1
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.
● DELETE: Removes 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

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": "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.

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": "jane.doe@example.com"
},
{
"id": 2,

3
"name": "John Smith",
"email": "john.smith@example.com"
}
]

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

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
4
using the NodeMCU to interact with a RESTful API.

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

// 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\":\"eve.holt@reqres.in\",\"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();
5
Serial.println("Response Body: " + response);
} else {
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
}

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.

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:

#include <ESP8266WiFi.h> // Include the Wi-Fi library


#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>

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() {

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;
7
HTTPClient http;

// Begin the HTTP request with the WiFiClient and URL


http.begin(client, "https://dummyjson.com/auth/login");
// Set headers
http.addHeader("Content-Type", "application/json");
// Create JSON payload
String jsonPayload =
"{\"username\":\"kminchelle\",\"password\":\"0lelplR\",\"expiresInMins\":30}";

// Send the POST request with the JSON payload


int httpResponseCode = http.POST(jsonPayload);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println(response); // Print the response

} else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);

}
http.end(); // Close connection
}
delay(5000); // Delay before making the next request
}

Running the Code


● Upload the code to the NodeMCU using Arduino IDE.

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

npm install -g json-server

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

o Navigate to Your Folder:

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

o Create and Add Sample JSON Data:


■ 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":
"john.doe@example.com" },
{ "id": 2, "name": "Jane Smith", "email":
"jane.smith@example.com" },
{ "id": 3, "name": "Alice Johnson",
"email": "alice.johnson@example.com" }
]
}

Save the file after adding the data.

3. Run JSON Server on Windows


■ Open Command Prompt or Terminal and navigate to the MockServer
folder:

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

9
■ 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.

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

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


Scott\",\"email\":\"michael@dundermifflin.com\"}";

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

Supplemental Activity #3:Simple Websbrowser 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.

7. Conclusion:

What conclusion can you make based on the activity?


___________________________________________________________________________________________
___________________________________________________________________________________________
________________________________________________________________________________________
___________________________________________________________________________________________
___________________________________________________________________________________________
________________________________________________________________________________________
___________________________________________________________________________________________
_________________________________________________________________________________________
___________________________________________________________________________________________
_________________________________________________________________________________________

8. Assessment (Rubric for Laboratory Performance):

Rubric for NodeMCU and RESTful API Activity


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

Evaluated by: Date:

__________________
Printed Name and Signature of Faculty Member

12

You might also like