Building A RESTful API With Node.js And Express
Introduction:
In this blog, we will explore how to build a RESTful API using Node.js and Express, two popular tools in the JavaScript ecosystem.
Setting up the Project:
- Create a new directory for your project and navigate into it using the command line.
- Run
npm init
to initialize a new Node.js project. Follow the prompts to set up your project's details. - Install the necessary dependencies by running
npm install express
andnpm install body-parser
.
Creating the Express Server
- Create a new file called
index.js
and open it in your preferred code editor. - Import the required modules by adding the following lines at the top of the file.
const express = require('express'); const bodyParser = require('body-parser');
- Initialize the Express app and configure it to use
body-parser
for parsing JSON requestconst app = express(); app.use(bodyParser.json());
Defining API Routes:
- Define the API routes for your application. For example, let's create a simple endpoint to retrieve a list of users. Add the following code after initializing the Express app:
const users = [ { id: 1, name: 'Abhi Singh }, { id: 2, name: 'TemplateBench' } ]; app.get('/api/users', (req, res) => { res.json(users); });
- You can also create routes for other CRUD operations like creating, updating, and deleting users. Feel free to expand upon this basic example based on your specific needs.
Starting the Server:
- Add the following code at the end of the
index.js
file to start the server on a specified port (e.g., 3000):const port = 3000; app.listen(port, () => { console.log(`Server running on port ${port}`); });
- Save the file and return to the command line. Run
node index.js
to start the server.
Testing the API:
- Open your web browser or an API testing tool like Postman.
- Navigate to
http://localhost:3000/api/users
retrieve the list of users.
Conclusion:
Now, We have created a rest Api in Node and Express. This is a small demo for the rest of the API. We generate more APIs by following these steps.
Thanks
1254