Node.js #Day5: Rest APIs and CRUD with Express.js
In the fifth installment of our Node.js series, we delve into the world of REST APIs and CRUD operations using Express.js. Understanding these concepts is fundamental to building robust web applications. So, let’s embark on this journey to demystify REST, CRUD, and their significance in web development.
Introduction to REST
What is REST?
REST API stands for Representational State Transfer Application Programming Interface.
REST, or Representational State Transfer, is an architectural style for designing networked applications. It relies on HTTP requests to post, read, update, and delete data, making it a cornerstone of modern web services.
Why is it called REST?
The term “REST” was coined by Roy Fielding in his doctoral dissertation in 2000. It reflects the fundamental principles of REST, which include stateless communication, client-server architecture, and a uniform interface.
History behind REST standard
The history of REST dates back to Roy Fielding’s Ph.D. dissertation, where he introduced the REST architectural style in 2000. Fielding was one of the principal authors of the HTTP specification (versions 1.0 and 1.1) and played a significant role in shaping the modern web.
Principles, properties, and constraints of REST
- Uniform interface. This means we always use HTTP verbs (GET, PUT, POST, DELETE). We always use URIs as our resources. And we always get an HTTP response with a status and a body.
- Stateless. This means each request is self-descriptive, and has enough context for the server to process that message.
- Client-server. There has to be clear boundaries between roles of the two two systems. One server, operationally, has to function as the server that is being called, and the other has to function as the one making the requests.
- Cacheable. Unless denoted, a client can cache any representation. This is possible thanks to the statelessness — every representation is self-descriptive.
REST emerged as a formal architectural style to address challenges in distributed computing. Fielding’s dissertation outlined the constraints and principles of REST, emphasizing simplicity, scalability, and a uniform interface. This laid the foundation for REST’s widespread adoption in web architecture.
Understanding CRUD Operations
What is CRUD?
CRUD stands for Create, Read, Update, and Delete. These operations represent the four basic functions that can be performed on data in most database systems. They are essential for manipulating resources in a RESTful API.
How are CRUD and REST different?
While REST is an architectural style, CRUD represents specific actions to be performed on data. RESTful APIs use HTTP methods to map CRUD operations to standard HTTP verbs like GET, POST, PUT, and DELETE.
Creating a RESTful API with Express.js
To demonstrate REST principles and CRUD operations, we’ll use Express.js, a popular Node.js framework. Let’s start by setting up our development environment and defining the structure of our RESTful API.
Handling HTTP GET Requests
In this section, we’ll delve into the code that handles HTTP GET requests.
const items = ['item1', 'item2', 'item3'];
app.get('/items', (req, res) => {
res.json(items);
});
Explanation:
const items = ['item1', 'item2', 'item3'];
: At the beginning of this code, an array nameditems
is defined. This array contains some sample items, which you might imagine as data you want to serve via your API.app.get('/items', ...
: This code defines a new route that listens for HTTP GET requests with the URL path '/items'. When a client sends a GET request to this endpoint, the code inside the callback function is executed.(req, res) => { ... }
: Just like before, this part is a callback function. It takes two parameters:req
(the request object) andres
(the response object).res.json(items);
: When a GET request is made to '/items', this line of code responds to the client by sending theitems
array as a JSON response. The.json()
method serializes the JavaScript array into JSON format, making it suitable for transferring data over the web.
This example demonstrates how to handle GET requests and send JSON data as a response.
Handling HTTP POST Requests
Next, let’s explain how to handle HTTP POST requests:
app.post('/items', (req, res) => {
const newItem = req.body.item;
items.push(newItem);
res.json(items);
});
Explanation:
app.post('/items', ...
: This code defines a route for handling HTTP POST requests to the '/items' URL. It expects clients to send data to this endpoint to create a new item.(req, res) => { ... }
: The callback function receives thereq
(request) andres
(response) objects.const newItem = req.body.item;
: In this line, we extract the 'item' property from the request body. When clients send POST requests, they often include data in the request body. Here, we assume that the client sends an object with an 'item' property in the request body.items.push(newItem);
: The extracted 'newItem' is then pushed into the 'items' array, effectively adding a new item to the collection.res.json(items);
: Finally, the updated 'items' array is sent back as a JSON response to the client, confirming that the new item has been added.
This code illustrates how to handle POST requests to create new data resources in your API.
Handling HTTP PUT Requests
Now, let’s explore how to handle HTTP PUT requests:
app.put('/items/:id', (req, res) => {
const itemId = req.params.id;
const updatedItem = req.body.item;
// Update the item with the provided ID
items[itemId] = updatedItem;
res.json(items);
});
Explanation:
app.put('/items/:id', ...
: This code defines a route for handling HTTP PUT requests to '/items/:id'. The ':id' part is a URL parameter, which allows you to specify the ID of the item you want to update.(req, res) => { ... }
: As usual, this is the callback function that executes when the route is triggered. It takes thereq
(request) andres
(response) objects.const itemId = req.params.id;
: Here, we retrieve the value of the ':id' parameter from the URL usingreq.params.id
. This value represents the unique identifier of the item you want to update.const updatedItem = req.body.item;
: Similarly to the POST request example, we extract the 'item' property from the request body. This is assumed to contain the updated data for the item.items[itemId] = updatedItem;
: The code then updates the item in the 'items' array with the provided ID (itemId
) with the new data (updatedItem
).res.json(items);
: Finally, it sends the updated 'items' array as a JSON response to confirm that the item has been successfully updated.
This code illustrates how to handle PUT requests to modify existing data resources.
Handling HTTP DELETE Requests
Now, let’s dive into the code for handling HTTP DELETE requests:
app.delete('/items/:id', (req, res) => {
const itemId = req.params.id;
// Remove the item with the provided ID
items.splice(itemId, 1);
res.json(items);
});
Explanation:
app.delete('/items/:id', ...
: This code defines a route for handling HTTP DELETE requests to '/items/:id'. As before, ':id' represents the unique identifier of the item to delete.(req, res) => { ... }
: The callback function receives thereq
(request) andres
(response) objects.const itemId = req.params.id;
: It retrieves the ':id' parameter from the URL, identifying the item to be deleted.items.splice(itemId, 1);
: The code uses thesplice
method to remove the item from the 'items' array based on its index (itemId
). The second argument '1' specifies that we want to remove one item at that index.res.json(items);
: Finally, it sends the updated 'items' array as a JSON response to confirm that the item has been successfully deleted.
Full Code:
8. Best Practices for REST APIs
To build robust and scalable RESTful APIs, it’s crucial to follow best practices. These include versioning your API, handling errors gracefully, and implementing proper security measures. Always consider the unique needs of your application.
Stay Connected for Quick Updates!
Thank you for exploring our guide on Node.js and Express.js. To stay updated with the latest developments, tutorials, and insightful content, be sure to follow us on LinkedIn and Twitter.
LinkedIn: Sandeep Singh
Twitter: sandeepdev_me
By following us on these platforms, you’ll be the first to know about new articles, tutorials, and valuable resources to enhance your skills as a developer. Don’t miss out on the opportunity to stay connected with our community!
Conclusion
In this Node.js #Day5 tutorial, we’ve explored REST APIs and CRUD operations using Express.js. We’ve learned what REST is, why it’s called REST, the difference between CRUD and REST, and how to implement each CRUD operation with code examples and detailed explanations. Now, you have the knowledge to create powerful APIs for your web applications.