Node.js and Express are two of the most popular tools for building web applications and RESTful APIs. REST (Representational State Transfer) is an architectural style that enables communication between systems over the internet. RESTful APIs provide a way for applications to interact with each other in a simple and standardized way.
In this article, we’ll walk you through the process of building a RESTful API with Node.js and Express.
Step 1: Set up the Project
To get started, you need to create a new Node.js project. Open up your terminal and run the following command:
perl
mkdir my-api && cd my-api
npm init -y
This will create a new directory called my-api
and initialize a new Node.js project inside it. The -y
flag tells npm
to use the default settings for the package.json
file.
Next, install the express
package by running the following command:
npm install express
This will install express
and its dependencies in your project.
Step 2: Create the Server
Now that we have the project set up, we can start building the API. First, we need to create an instance of the express
application and set up the server.
Create a new file called server.js
in the root directory of your project and add the following code:
javascript
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
This code imports the express
package, creates an instance of the express
application, and sets the port for the server to listen on. The process.env.PORT || 3000
expression sets the port to the value of the PORT
environment variable if it exists, otherwise it sets it to 3000
.
Run the server by running the following command in your terminal:
node server.js
You should see a message in the terminal that says Server listening on port 3000
. If you open a web browser and navigate to http://localhost:3000
, you should see a message that says Cannot GET /
.
Step 3: Create the Routes
Now that we have the server set up, we can create the routes for the API. Routes define the endpoints that the API provides and the actions that should be taken when those endpoints are accessed.
Create a new file called routes.js
in the root directory of your project and add the following code:
javascript
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('Hello, World!');
});
module.exports = router;
This code creates a new router using the express.Router()
method and defines a single route that responds to a GET
request to the root endpoint (/
) with a simple message.
In server.js
, import the routes.js
file and use the router by adding the following code:
javascript
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const routes = require('./routes');
app.use('/', routes);
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
This code imports the routes.js
file and sets up the express
application to use the routes defined in that file when a request is made to the root endpoint.
Restart the server by running node server.js
in your terminal and navigate to http://localhost:3000
in your web browser. You should see the message Hello, World!
.
Step 4: Handle POST Requests
Now let’s add a route to handle POST
requests to the API. This will allow clients to send data to the server.
Add the following code to routes.js
:
javascript
router.post('/users', (req, res) => {
const user = req.body;
// do something with the user data
res.send('User created successfully');
});
This code defines a route that responds to POST
requests to the /users
endpoint. It extracts the user data from the request body using req.body
and then sends a simple response back to the client.
To handle POST
requests, we need to add some middleware to our express
application that will parse the request body. Add the following code to server.js
:
javascript
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const routes = require('./routes');
app.use(express.json()); // add this line
app.use('/', routes);
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
This code adds the express.json()
middleware to the application, which will parse JSON request bodies. Now, when a client sends a POST
request to the /users
endpoint with JSON data in the request body, we can access that data in our route handler using req.body
.
Restart the server by running node server.js
in your terminal and send a POST
request to the /users
endpoint using a tool like curl
or Postman
. For example:
json
curl -X POST -H "Content-Type: application/json" -d '{"name": "John", "email": "john@example.com"}' http://localhost:3000/users
You should see a message in the terminal that says User created successfully
.
Step 5: Add Error Handling
Finally, let’s add some error handling to our API. This will ensure that our server doesn’t crash if an error occurs and will provide helpful error messages to clients.
Add the following code to routes.js
:
javascript
router.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});
This code defines error handling middleware that will be called if an error occurs in any of our routes. It logs the error to the console and sends a generic error message to the client with a 500 status code.
Now, let’s create an error by adding some code to our POST /users
route handler that intentionally throws an error:
javascript
router.post('/users', (req, res) => {
const user = req.body;
if (!user.name) {
throw new Error('Name is required');
}
// do something with the user data
res.send('User created successfully');
});
This code checks if the name
property is present in the request body and throws an error if it is not.
Restart the server by running node server.js
in your terminal and send a POST
request to the /users
endpoint without a name
property in the request body. For example:
json
curl -X POST -H "Content-Type: application/json" -d '{"email": "john@example.com"}' http://localhost:3000/users
You should see an error message in the terminal that says Error: Name is required
. The client will receive a 500
status code and the message Something went wrong!
.
Conclusion
In this article, we walked you through the process of building a RESTful API with Node.js and Express.