How To Build Restful Api With Node.js and Express?
-
To build an API, you need to have a basic understanding of Node.js, Express, and some experience with JavaScript, and you are all set to go.
-
For building API, we are going to use Node.js, Express and Nodemon as our dependencies.
» What Is Node.js?
-
It’s an open server environment that runs on various platforms such as Windows, Linux, Mac, etc, Uses JavaScript on the server side.
-
JavaScript does not run on the server, but NodeJS makes it possible. With Node.js JavaScript can be run on the server.
-
Node.js uses asynchronous programming!
-
That means, it does not wait and continues to next request
-
Node.js runs single-threaded, non-blocking I/O model, asynchronous programming, which is very memory efficient.
» What Is Express?
-
Express.js is a popular and widely used web framework for building server-side applications with Node.js.
-
It is known for its simplicity, flexibility, and extensibility, making it a popular choice for building APIs, web applications, and other server-side applications.
-
Express.js provides a set of features and tools that simplify the development of web applications in Node.js.
» What is nodemon?
-
Nodemon is a tool for Node.js that automatically restarts the server whenever changes are made to the codebase.
-
You can install nodemon gobally in your system with command:
npm i -g nodemon
- -g means globally so we can use it in any project.
OR
- You can install nodemon just for specific project with command:
npm install nodemon
- These are just different ways through which we can install nodemon. Do not install Nodemon now, because soon we are going to install it while setting up our environment. This was just an Overview.
» Setting Up the environment.
- Download the latest compatible version for Node.js for Windows or MacOS.
-
After the download, install the software. If you use Windows or MacOS, just click through the installation screens until the installation is completed.
-
After it, just open the terminal and type the command
node --version
npm --version
- This checks the version of Node.js and NPM.
- Create folder with name Building_RestAPI and open in VSCode.
- Now in this folder, Open up the terminal with (Ctrl + `) and type the command.
npm init -y
- npm init will generate package.json file that will hold the dependencies, and will help us create and describe our new project.
- After this, install express and nodemon with command given below and run it in terminal, it will download express and nodemon as our dependencies in package.json file.
npm install express nodemon
-
Express: We use Express with Node.js because it simplifies the process of building web applications in JavaScript. Express provides a set of tools and features that make it easier to handle requests, handle errors, and structure the code of an application.
-
NodeMon: Nodemon is a tool for Node.js that automatically restarts the server whenever changes are made to the codebase.
Congratulations 🎉 You have finally set up your environment.
» Building our first API.
Let’s follow these steps, to build our first API.
STEP 1. In package.json file add another script in scripts
"scripts": {
"start": "nodemon index.js"
},
- This helps execute and run our server.
STEP 2. Create an index.js file in Building_RestAPI folder.
STEP 3. Let’s Import express module and Create an express app:
const express = require("express"); // Import express module
const app = express(); // Create express app
STEP 4. Setting the port.
const port = process.env.PORT || 3000;
STEP 5. We want our app to listen to the Port and start the server:
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Now run the command npm start in terminal to start our sever.
And now you can look at the message which says: Server is running on port 3000.
» Define GET, POST, DELETE routes
Let’s, define our API routes using Express’s routing methods (app.get(), app.post(), app.delete()). For example:
// GET method
app.get("/api/users", (req, res) => {
// Handle GET request and send response
res.send("Get users");
});
// POST method
app.post("/api/users", (req, res) => {
// Handle POST request and send response
res.send("Create user");
});
// DELETE method
app.delete("/api/users/:id", (req, res) => {
// Handle DELETE request and send response
res.send(`Delete user with ID: ${req.params.id}`);
});
The req object represents the incoming request, and the res object represents the outgoing response.
» Testing the API
We can now test our API using tools like Insomnia or Postman. For example:
For GET: Send a GET request to http://localhost:3000/api/users using Insomnia or Postman to see the “Get users” response.
For POST: Send a POST request to http://localhost:3000/api/users using Insomnia or Postman to see the “Create user” response.
For DELETE: Send a DELETE request to http://localhost:3000/api/users/1 (or any other ID) using Insomnia or Postman to see the “Delete user with ID: 1” response.
To test this with me, watch the youtube video embedded above.😉
That’s it! We’ve have finally created a simple RESTful API with GET, POST, and DELETE methods using Node.js and Express. Of course, this is just a basic example, and you can expand and customize your API based on your specific requirements.
I hope this cleared - How to build an API using Node.js and Express. Thank You!!😊