{"id":4189,"date":"2023-11-04T23:14:07","date_gmt":"2023-11-04T23:14:07","guid":{"rendered":"http:\/\/localhost:10003\/building-restful-apis-with-node-js-and-express\/"},"modified":"2023-11-05T05:47:57","modified_gmt":"2023-11-05T05:47:57","slug":"building-restful-apis-with-node-js-and-express","status":"publish","type":"post","link":"http:\/\/localhost:10003\/building-restful-apis-with-node-js-and-express\/","title":{"rendered":"Building RESTful APIs with Node.js and Express"},"content":{"rendered":"
REST (Representational State Transfer) is a popular architectural style used to design web services and APIs. It provides a standardized way of exchanging data between different systems and applications. Node.js and Express are two of the most popular tools used to build RESTful APIs.<\/p>\n
In this tutorial, we will learn how to build a RESTful API with Node.js and Express. We will cover the following topics:<\/p>\n
Before we start building our API, we need to set up a Node.js project. If you don’t have Node.js installed on your computer, you can download it from the official website: https:\/\/nodejs.org<\/a>.<\/p>\n Once Node.js is installed, open your terminal or command prompt and create a new directory for your project:<\/p>\n Next, initialize a new Node.js project using NPM (Node Package Manager):<\/p>\n This will create a default Express is a popular web framework for Node.js that simplifies the process of building web applications and APIs. To install it, run the following command in your project directory:<\/p>\n This will download and install the latest version of Express and add it as a dependency to your Once Express is installed, create a new file called This code creates a new Express app and sets it up to listen on port 3000. Whenever a request is received on this port, the server will log a message to the console.<\/p>\n To test if Express is working correctly, run the following command:<\/p>\n This should start the server and display the message “Server running at http:\/\/localhost:3000” in the console. If you visit this URL in your web browser, you should see an error message because we haven’t added any routes yet.<\/p>\n In order to handle incoming requests to our API, we need to create routes. Routes are mappings between HTTP methods (such as GET, POST, PUT, DELETE) and URL paths. Each route defines a function that will be executed when the corresponding request is received.<\/p>\n To create a route in Express, we use the This defines a route that will handle GET requests to the root URL ( We can create additional routes to handle other HTTP methods and URL paths. For example, to handle POST requests to the This code defines a route that will handle POST requests to the Middleware functions are functions that are executed between the incoming request and the final response. They can be used to perform various tasks, such as logging, authentication, error handling, etc.<\/p>\n To add middleware in Express, we use the For example, to add a simple logger middleware that logs each incoming request to the console, we can add the following code:<\/p>\n This code defines a middleware function that logs the HTTP method, URL, and current date and time for each incoming request.<\/p>\n We can also use third-party middleware libraries, such as These lines of code add the Most web applications and APIs need to store and retrieve data from a database. There are several databases that can be used with Node.js and Express, such as MySQL, PostgreSQL, MongoDB, etc.<\/p>\n For this tutorial, we will use MongoDB, a popular NoSQL database that stores data in a JSON-like format. To connect to MongoDB, we need to install the Then, we can require it in our code and connect to a MongoDB database:<\/p>\n This code connects to a local MongoDB instance running on the default port ( CRUD stands for Create, Read, Update, and Delete, which are the basic operations that can be performed on data in a database.<\/p>\n To implement these operations in our API, we need to create routes that handle HTTP requests for each operation. For example, to create a new user account, we can define a This code extracts the Similar routes can be defined for other CRUD operations, such as Finally, we need to test our API to make sure it works as expected. There are several tools and libraries that can be used for testing APIs, such as Postman, Newman, Mocha, etc.<\/p>\n For this tutorial, we will use Supertest, a library that allows us to send HTTP requests to our Express app and make assertions on the responses.<\/p>\n To install Supertest, run the following command:<\/p>\n Then, create a new file called This code defines a simple test that sends a To run the tests, execute the following command:<\/p>\n This should run the test and display the results in the console.<\/p>\n In this tutorial, we learned how to build a RESTful API with Node.js and Express. We covered several key topics, such as setting up a Node.js project, installing and configuring Express, creating routes and handling requests, adding middleware, connecting to a database, implementing CRUD operations, and testing the API.<\/p>\n By following this tutorial, you should now have a good understanding of how to build and test RESTful APIs using Node.js and Express. Of course, there are many other features and libraries that can be used to enhance your APIs, but these basics should be enough to get you started. Happy coding!<\/p>\n","protected":false},"excerpt":{"rendered":" REST (Representational State Transfer) is a popular architectural style used to design web services and APIs. It provides a standardized way of exchanging data between different systems and applications. Node.js and Express are two of the most popular tools used to build RESTful APIs. In this tutorial, we will learn Continue Reading<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_import_markdown_pro_load_document_selector":0,"_import_markdown_pro_submit_text_textarea":"","footnotes":""},"categories":[1],"tags":[1617,19,1618,36],"yoast_head":"\nmkdir my-api\ncd my-api\n<\/code><\/pre>\n
npm init -y\n<\/code><\/pre>\n
package.json<\/code> file with some basic settings. We can modify this file later to add dependencies and other configurations.<\/p>\n
Installing and configuring Express<\/h2>\n
npm install express\n<\/code><\/pre>\n
package.json<\/code> file.<\/p>\n
index.js<\/code> in your project directory. This will be the entry point for our application. Add the following code to initialize a new Express app:<\/p>\n
const express = require('express');\nconst app = express();\n\nconst port = 3000;\n\napp.listen(port, () => {\n console.log(`Server running at http:\/\/localhost:${port}`);\n});\n<\/code><\/pre>\n
node index.js\n<\/code><\/pre>\n
Creating routes and handling requests<\/h2>\n
app.METHOD()<\/code> syntax, where METHOD is the HTTP method (in uppercase) and the path is specified as a string. For example, to create a route to handle GET requests to the root URL path (
\/<\/code>), we can add the following code:<\/p>\n
app.get('\/', (req, res) => {\n res.send('Hello World!');\n});\n<\/code><\/pre>\n
\/<\/code>) and respond with the message “Hello World!”.<\/p>\n
\/users<\/code> path (for creating new user accounts), we can add the following code:<\/p>\n
app.post('\/users', (req, res) => {\n \/\/ create new user account\n res.send('User account created');\n});\n<\/code><\/pre>\n
\/users<\/code> path and create a new user account.<\/p>\n
Adding middleware<\/h2>\n
app.use()<\/code> method. We can pass one or more functions as arguments to this method, and they will be executed for every incoming request.<\/p>\n
app.use((req, res, next) => {\n console.log(`${req.method} ${req.url} - ${new Date()}`);\n next();\n});\n<\/code><\/pre>\n
body-parser<\/code> for parsing request bodies or
cors<\/code> for handling cross-origin requests. To use these libraries, we need to install them as dependencies and require them in our code:<\/p>\n
npm install body-parser cors\n<\/code><\/pre>\n
const bodyParser = require('body-parser');\nconst cors = require('cors');\n\napp.use(bodyParser.json());\napp.use(cors());\n<\/code><\/pre>\n
body-parser<\/code> and
cors<\/code> middleware to our Express app.<\/p>\n
Connecting to a database<\/h2>\n
mongoose<\/code> package:<\/p>\n
npm install mongoose\n<\/code><\/pre>\n
const mongoose = require('mongoose');\n\nmongoose.connect('mongodb:\/\/localhost\/my-api', {\n useNewUrlParser: true,\n useUnifiedTopology: true\n}).then(() => {\n console.log('Database connected');\n}).catch((err) => {\n console.error(err);\n});\n<\/code><\/pre>\n
27017<\/code>) and a database called
my-api<\/code>. If the connection is successful, it logs a message to the console.<\/p>\n
Implementing CRUD operations<\/h2>\n
POST<\/code> route like this:<\/p>\n
app.post('\/users', (req, res) => {\n const { name, email, password } = req.body;\n\n const user = new User({\n name,\n email,\n password\n });\n\n user.save().then(() => {\n res.status(201).send(user);\n }).catch((err) => {\n console.error(err);\n res.status(500).send('Error creating user');\n });\n});\n<\/code><\/pre>\n
name<\/code>,
email<\/code>, and
password<\/code> fields from the request body, creates a new
User<\/code> object using Mongoose, and saves it to the database. If the operation is successful, it returns a
201 Created<\/code> status code and the user object in the response. If there is an error, it returns a
500 Internal Server Error<\/code> status code and an error message.<\/p>\n
GET<\/code> to retrieve a list of users,
PUT<\/code> to update a user account, and
DELETE<\/code> to delete a user account. These routes will use Mongoose methods like
find<\/code>,
findOne<\/code>,
update<\/code>, and
remove<\/code> to interact with the database.<\/p>\n
Testing the API<\/h2>\n
npm install supertest --save-dev\n<\/code><\/pre>\n
test.js<\/code> in your project directory and add the following code:<\/p>\n
const request = require('supertest');\nconst app = require('.\/index');\n\ndescribe('Test API endpoints', () => {\n it('should return Hello World message', async () => {\n const res = await request(app).get('\/');\n expect(res.statusCode).toEqual(200);\n expect(res.text).toEqual('Hello World!');\n });\n});\n<\/code><\/pre>\n
GET<\/code> request to the root URL path and verifies that the response has a
200 OK<\/code> status code and the message “Hello World!”.<\/p>\n
npm test\n<\/code><\/pre>\n
Conclusion<\/h2>\n