In this article, we will build a basic web app using ExpressJS and learn how to perform CRUD (create, read, update, delete) operations.
By the end of this article, you should be able to :
Read information from a server
Post information to the server
Update posted information
Delete information from the server
Use Postman as an HTTP client
Prerequisite
Before starting this article, you should be familiar with the following:
Introduction
There are two parts to a web application: the front end and the back end. The front end represents what users see in the browser. The backend (also known as server-side) is everything that happens "under the hood".
Backend components include servers and databases. Servers control how users access files and databases are organized collections of data.
When building a web app, the preferred method is to use a framework to speed up development. ExpressJS is a web framework that enables backend developers quickly build robust web applications.
It enables developers to set up a server, connect it to a database, and provide an API to allow front-end developers to build the client side of the web application.
APIs enable you to develop all kinds of web applications having all possible CRUD (create, retrieve, update, delete) operations.
We perform these CRUD ( Create, Read, Update, Delete) operations whenever the client (eg. web browser) sends HTTP requests with varying HTTP methods ( GET
, POST
, PUT
etc.) to the server.
In this article, we will learn how to perform CRUD operations without building a separate front-end app to handle the requests.
The Approach
Generally, server-side apps wait for HTTP
requests from the web browser (or other clients). On receiving the request, the application determines the action to take based on the URL pattern and perhaps any information contained in the POST
data or GET
data.
The app may read or write information to the database or execute required tasks based on the requests. The application then returns a response to the client.
Typically, we need a front-end app to help send HTTP requests to the server, hence most developers are aligned to building the front-end of the web app as well.
Instead of building the front end, we can use a tool called Postman to send the request, receive the request, and post data to the server.
In this tutorial focuses on using Postman as an HTTP client to initiate requests and perform CRUD operations on the server.
Generally, CRUD operations are performed on top of a Database Management System (a tool that stores databases) like MySQL, MongoDB, PostgreSQL, etc. However, for this tutorial, we will not use a DBMS yet, we will define an array of items in a data.js
file (to serve as our database) and use it for the CRUD tasks.
Now, let's learn how to create a web server
Creating a basic Express app
The code below creates an Express app and listens for a connection to the app
const express = require("express"); //require express
const app = express(); //create the app
app.get("/", (req, res) => {
res.send(`Hello World`);
}); // send a response to the client
app.listen(8000, () => {
console.log("App has started and running ");
}); // listen for connection to the app
Understanding the Express Code
The below explain the code snippet above:
The
require()
module import the express module to enable us to create an Express appCalling the
express()
function returns anobject
typically namedapp
. This object has methods for routing HTTP requests, setting up middleware, rendering HTML views, and registering a template engine.The
app.get()
specifies a route definition withpath
andcallback function
passed asarguments
The
callback
will be invoked whenever a client initiates aHTTP GET
requestThe
callback
accepts arequest
andresponse
objects as arguments.The
response
object has asend
method (i.eres.send()
) that enables us to return a response to the client. In this scenario, it returns the stringHello World
.Lastly, the
app.listen()
listens for a connection to the server.
Whenever the server is run, we can go to localhost:8000
using the web browser to view the returned response.
Understanding the CRUD Principle
Web apps keep track of data. These data could be customer data, login account details, payment details, health data, etc. The data is typically organized into a database
CRUD is an acronym for (Create, Read, Update, and Delete). It represents the operations used in web apps that have an underlying database to perform specific operations on the database from the front-end
The
Create
allows users to create a new record in the databaseThe
Read
allows users to search and retrieve specific information from the databaseThe
Update
is used to modify existing data in the databaseThe
Delete
allows users to delete specified data in the database
Consider a scenario where you have been tasked to build a web app that displays the product catalog for an eCommerce store.
The application would have a front-end admin functionality enabling the logged-in user to do the following:
Add a new product to the catalog
Delete an out-of-stock product from the catalog
Modify the details of a specified product
Request for the details of a product
Each product
is an object
with the following details
"product":{
id: <Integer>,
name: <String>,
price: <Number>,
desc: <String>,
image: <String>
}
In building this app, the admin needs to send requests to the server in order to perform the CRUD operations:
Create
: add a new product to the catalogRead
: view all products in the catalogUpdate
: modify the details of a single productDelete
: remove a product from the catalog
An introduction to Postman
Because we would not be developing any frontend for this project, that means we don't have access to a web browser to send HTTP requests, we need a client that will enable us to post, update, delete, and read data from our backend.
Postman is a REST
client that enables us to send requests, inspect responses and perform other HTTP
methods (GET
,POST
, PUT
, PATCH
, DELETE
, etc). It can be likened to a browser that doesn't render HTML
.
We will use it to initiate requests to the Express app and ultimately perform the CRUD
operations.
Project Structure
Below is a guide on how your project folder should look like
-
We created a
crud_app
directory-
app.js
represents theExpress
app -
data.js
will contain all the data required to perform the crud operations. -
package.json
is the initialized file containing all the dependencies.
-
The data.js
file contains the products
arrays that will be exported to be used in the app.js
The content of the data.js
file is as below, it is an array of product items
//data.js
//sample products
const products = [
{
id: 1,
name: "albany sofa",
image:
"https://dl.airtable.com/.attachments/6ac7f7b55d505057317534722e5a9f03/9183491e/product-3.jpg",
price: 39.95,
desc: `I'm baby direct trade farm-to-table hell of, YOLO readymade raw denim venmo whatever organic gluten-free kitsch schlitz irony af flexitarian.`,
},
{
id: 2,
name: "entertainment center",
image:
"https://dl.airtable.com/.attachments/da5e17fd71f50578d525dd5f596e407e/d5e88ac8/product-2.jpg",
price: 29.98,
desc: `I'm baby direct trade farm-to-table hell of, YOLO readymade raw denim venmo whatever organic gluten-free kitsch schlitz irony af flexitarian.`,
},
{
id: 3,
name: "albany sectional",
image:
"https://dl.airtable.com/.attachments/05ecddf7ac8d581ecc3f7922415e7907/a4242abc/product-1.jpeg",
price: 10.99,
desc: `I'm baby direct trade farm-to-table hell of, YOLO readymade raw denim venmo whatever organic gluten-free kitsch schlitz irony af flexitarian.`,
},
{
id: 4,
name: "leather sofa",
image:
"https://dl.airtable.com/.attachments/3245c726ee77d73702ba8c3310639727/f000842b/product-5.jpg",
price: 9.99,
desc: `I'm baby direct trade farm-to-table hell of, YOLO readymade raw denim venmo whatever organic gluten-free kitsch schlitz irony af flexitarian.`,
},
];
module.exports = products ;
Relationship between frontend and backend.
Frontend and backend communicate with each other - via HTTP requests.
The backend is the code that runs on the server and receives requests from the client. Whenever the client sends requests to retrieve or modify resources, the server receives the request and contains the logic to send the appropriate data back to the client.
The backend also includes the database, which will continuously store all of the data for the application. CRUD operations are performed on the database at the backend
Understanding the back-end logic
At the backend, develops write logic on how to respond to requests based on the HTTP
request method (GET
, POST
, etc) and the URI
originating from the HTTP client
What is routing?
Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, PUT, etc).
With routing, you are matching incoming request paths (eg. https://localhost/api/products) from the web client(eg. web browser) to a resource in the database.
Each route can have one or more handler functions, which are executed when the route is matched.
In other words, the application “listens” for requests from the client that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function ( handler function)
At the back-end, we define routing using methods of the Express app
object that matches the HTTP methods; for example, app.get()
to handle GET requests and app.post
to handle POST requests.
The syntax for route definition is as below:
app.method(path, handler)
Where:
app
is an instance ofexpress
.method
represents the HTTP request method usedpath
: represents a path on the server where we can access a resourcehandler
: It is a function that executes specified tasks whenever the route is matched.
Defining the logic for retrieving resources
Let us examine how to READ
data from a server when a route matches.
We will first define a route to allow the client to request information from the server.
Because we want to retrieve a resource, we will use the GET
method, we will also define the URI (path) the client needs to enter, and lastly the function that will be executed when the route matches
The code is as below:
//route to read data
app.get("/api/products", (req, res) => {
//code to be executed
const newProduct = products.map((product) => {
const { id, name, price } = product;
return {
id,
name,
price,
};
});
res.json(newProduct);
});
GET
is the defaultHTTP
method a web browser uses to fetch data from a server. Hence on our server, we used theapp.get()
method to indicate that a request from the client to the app will use theHTTP GET
methodThe
api/products
represents thepath
the client will enter in theURL
in order to read information from our server.Once the
http
method and thepath
specified by the client matches theroute
defined on our server, we execute thecallback
function.Note that by default, anytime you enter the
URL
in the web browser to access a resource from a server, you are using theGET
method.
The code snippet below indicates the logic we define in the callback function
The details of the logic are as below:
Use the
array.map()
method to iterate over eachproduct
itemAccess the
id
,name
andprice
for each itemReturn a
newProduct
object with the following values theid
,name
andprice
Finally, use the
res.json ()
method to send the appropriate response to the client
Note: The products
array is from the data.js
file and is included in our app using the snippet below:
//import the products array into the app.js
const { products } = require("./data");
Retrieving a resource from the server using Postman.
As mentioned, Postman will act as a web browser to enable us to initiate requests to the server without the need for a front-end application.
Because we want to access information from the server, we will use the HTTP GET
method to send the request.
The steps to accomplish that are as below:
Enter the request URL in the field provided
Set the
http
method at the default selection (i.eGET
)Click on the
send
button to initiate a request to the serverWhenever the server receives the request, it executes the callback function, and sends the response to Postman
The requested data will display in the "Body" tab of Postman
See the screenshot below:
Defining the logic for Inserting data
In this section, we will learn how to insert or post data to our server. Sending data to the server is commonly referred to as Create in the CRUD acronym
The syntax to send data to our Express app is as below:
app.post(path, handler)
At the backend, we define the logic to handle Post
requests when the route entered by the client matches that on the server.
To post data to our Express app, we utilize express.json()
middleware. It parses incoming requests and converts the request body to JSON
The express.json()
middleware returns an object
, this object will contain the data we are posting to our server.
We define this middleware in our app as below:
//app.js
//parse json
app.use(express.json());
The logic for posting data to the server is as below:
app.post("/api/products/new", (req, res) => {
//accessed the data using the req.body
res.send({ success: true, data: [...products, req.body] });
});
We used the
app.post
method routes theHTTP
POST
request to the specified path and with the specified callback function.The
api/products/new
specify thepath
the client will enter to post data. For instance, if the domain is www.example.com, then the full path to enter in the address bar will be www.example.com/api/products/newWhenever the request is initiated, the form data can be accessed using the
req.body
methodThe res.send() function basically sends the HTTP response. The body parameter can be a String or a Buffer object or an object or an Array.
The
res.send()
method sends the HTTP response. The body parameter can be aString
,Object
or anArray
.In our scenario, we sent anobject
withsuccess
andperson
keys.We assign
true
to thesuccess
to indicate a positive response.The value of the
data
key is an array. We copied all the existing products into that array and included the submitted data using thereq.body
method.
Now that we defined our backend logic, let's make a POST
request to http://localhost:8000/api/products/new using Postman.
Sending data to the server using Postman
Postman defaults to a GET
method that does not contain the request body. To submit data, we need to change the request method to POST
.
The action is highlighted in blue in the screenshot below:
Follow the steps below to send data
Set the
http
method toPOST
In the Enter request URL field, enter the URL to send the request to
-
Enter the request body. This is the data we want to send to the server
- Click on the "Body" tab
- Click on the "raw" radio button, this will display a field to enter the required data
- Click on the "Text" tab and select "JSON" from the dropdown menu
-
In the provided text area, enter the information to send. The body content can be any valid
JSON
object. For instance:
{ "FirstName": "Peter", "LastName" : "Piper", "UserName" : "ppiper", "Email" : "ppiper@example.com" }
-
In our scenario, each data is an
object
with the followingkey-value
pairs-
id
,name
,image
,price
anddesc
hence we enter it like below:
{ "id": 5, "name":"TV set", "image": "http:dl.airtable...", "desc": "Smart TV" }
-
Click on the "Send" button to initiate a request
Viewing the response on Postman
Postman has a response section for viewing responses sent by the server.
See the screenshot of the section below:
The screenshot of the response returned by the server is as below:
Examining the response will indicate a new data has been added to our dataset.
See the code below:
//entire response from Postman
{
"success": true,
"data": [
{
"id": 1,
"name": "albany sofa",
"image": "https://dl.airtable.com/.attachments/6ac7f7b55d505057317534722e5a9f03/9183491e/product-3.jpg",
"price": 39.95,
"desc": "I'm baby direct trade farm-to-table hell of, YOLO readymade raw denim venmo whatever organic gluten-free kitsch schlitz irony af flexitarian."
},
{
"id": 2,
"name": "entertainment center",
"image": "https://dl.airtable.com/.attachments/da5e17fd71f50578d525dd5f596e407e/d5e88ac8/product-2.jpg",
"price": 29.98,
"desc": "I'm baby direct trade farm-to-table hell of, YOLO readymade raw denim venmo whatever organic gluten-free kitsch schlitz irony af flexitarian."
},
{
"id": 3,
"name": "albany sectional",
"image": "https://dl.airtable.com/.attachments/05ecddf7ac8d581ecc3f7922415e7907/a4242abc/product-1.jpeg",
"price": 10.99,
"desc": "I'm baby direct trade farm-to-table hell of, YOLO readymade raw denim venmo whatever organic gluten-free kitsch schlitz irony af flexitarian."
},
{
"id": 4,
"name": "leather sofa",
"image": "https://dl.airtable.com/.attachments/3245c726ee77d73702ba8c3310639727/f000842b/product-5.jpg",
"price": 9.99,
"desc": "I'm baby direct trade farm-to-table hell of, YOLO readymade raw denim venmo whatever organic gluten-free kitsch schlitz irony af flexitarian."
},
{
"id": 5,
"name": "TV set",
"image": "http:dl.airtable...",
"desc": "Smart TV"
}
]
}
Defining the logic for Updating data
We have covered how to CREATE
, and READ
data. In this section, we will Update
the data on the server.
The syntax for updating data is as below:
app.put(path, handler)
Use the
PUT
method to update or modify a resource on the serverThe
path
indicates the route to the resource. Because we will be updating specific data, we need to provide theid
of the item to update. In our scenario, we will define the path asapi/products/:id
.
The logic is defined below:
app.put("/api/products/:id", (req, res) => {
//get the id of the item to update
const { id } = req.params;
//get the value in the request body
const { name } = req.body;
//updating the item
const updatedProducts = products.map((product) => {
if (product.id === Number(id)) {
product.name = name;
}
return product;
});
res.send({ success: true, data: [...updatedProducts] });
});
The
app.put()
method routes theHTTP
PUT
request to the specified path and with the specified callback function.The
api/products/:id
represents the path.The
:id
is a placeholder, it allows for dynamic routing based on whatever parameter was added to theapi/products
pathThe
req.params
is an object that gets populated with the value from the parameter.-
Using gain access to the parameter using
const {id} = req.params
The
req.body
enable us to access whatever is in the request's bodyWe used the
.map()
method to iterate over each item in the array. If the id of the item equals that receives from thereq.params
, we update the name of the item with the value received from thereq.body
and return the itemWe used the
res.send()
method to send a response to the client
Updating data using Postman
To update data, we change the HTTP
request method to PUT
Follow these steps to update information
Set the
http
method toPUT
In the Enter request URL field, enter the URL to send the request.
In this scenario, because we want to update the first data with an id of 1, the URL will be: localhost:8000/api/products/1
-
Enter the request body. This is the data we want to send to the server to modify with an id of 1
- Click on the "Body" tab
- Click on the "raw" radio button, this will display a field to enter the required data
- Click on the "Text" tab and select "JSON" from the dropdown menu
- In the provided text area, enter the information to send.
- In this example, we will modify the name of the first item in our array to the below:
{
"name":"House"
}
Click on the Send button to initiate the request
Defining the logic for deleting data from the server
We have covered how to Create, Read and Update data from our server.
Finally, let's examine how to delete data from our app.
The syntax for deleting data is as below
app.delete(path, handler)
Deleting data follows a similar approach as posting data.
We specify the id of the item to delete and use the filter()
method to filter out all the items with an id key that does not match the specified id.
Lastly, we return the response as JSON
to the client
The code is below:
// deleting the item
app.delete("/api/products/:id", (req, res) => {
const { id } = req.params;
const filteredProducts = products.filter(
(product) => product.id !== Number(id)
);
return res.json({ success: true, data: filteredProducts });
});
Deleting data from the server using Postman
Follow these steps to delete a resource from the server
Set the
http
method toDELETE
In the Enter request URL field, enter the URL to send the request.
In this scenario, because we want to delete the first data with an id of 1, the URL will be: localhost:8000/api/products/1
Click on the Send button to initiate the request
View the response in the Body. You will notice the item with an
id
of1
has been excluded, and we now have three items
The screenshot is below
Click here for the complete code
Summary
CRUD is an acronym for (Create, Read, Update, and Delete). It represents the operations used in web apps that have an underlying database to perform specific operations on the database from the front-end
At the backend, develops write logic on how to respond to requests based on the
HTTP
request method (GET
,POST
, etc) and theURI
originating from the HTTP client-
Postman is a
REST
client that enables us to send requests, inspect responses and perform otherHTTP
methods (GET
,POST
,PUT
,PATCH
,DELETE
, etc). It can be likened to a browser that doesn't renderHTML
.We used it to initiate requests to the Express app and ultimately perform the
CRUD
operations.
This article is the day 8 post on the 30-day challenge I am undertaking to learn backend development. Please feel free, to drop some insights, comment, or share the post to your networks
Top comments (0)