Node.js is a popular server-side JavaScript runtime environment, and Express.js is a widely-used web framework for building web applications with Node.js. In this blog post, we will learn how to build a RESTful API using Node.js and Express.js.

What is a RESTful API?

A RESTful API is a web service that follows the principles of the Representational State Transfer (REST) architecture. It is an interface for interacting with a web application or service using standard HTTP methods such as GET, POST, PUT, and DELETE. A RESTful API returns data in a standard format such as JSON or XML, which can be easily parsed by client applications.

Setting up the Project Before we begin building our RESTful API, we need to set up our project. Create a new directory and navigate to it in your terminal. Then run the following command to initialize a new Node.js project:

npm init -y

Next, install the following dependencies:

npm install express body-parser cors
  • Express.js is the web framework we will use to build our API.
  • Body-parser is middleware that parses incoming request bodies in a middleware before your handlers, available under the req.body property.
  • Cors is middleware that allows cross-origin requests to your API.

Creating the Server Create a new file called server.js and add the following code:

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();

app.use(bodyParser.json());
app.use(cors());

app.listen(3000, () => {
  console.log('Server started on port 3000');
});

In the code above, we are importing the required dependencies and creating a new Express.js application. We then use body-parser to parse incoming request bodies, and cors to allow cross-origin requests to our API. Finally, we start the server and listen on port 3000.

Defining the Routes Now that we have set up our server, we can define the routes for our API. Create a new file called routes.js and add the following code:

const express = require('express');
const router = express.Router();

// GET route
router.get('/hello', (req, res) => {
  res.send('Hello World!');
});

// POST route
router.post('/hello', (req, res) => {
  const name = req.body.name;
  res.send(`Hello ${name}!`);
});

module.exports = router;

In the code above, we define two routes for our API:

  • A GET route that responds with a “Hello World!” message.
  • A POST route that expects a name parameter in the request body and responds with a personalized greeting.

Integrating the Routes To integrate the routes into our application, we need to import them in our server.js file and use them as middleware. Modify your server.js file as follows:

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const routes = require('./routes');

const app = express();

app.use(bodyParser.json());
app.use(cors());
app.use('/api', routes);

app.listen(3000, () => {
  console.log('Server started on port 3000');
});

In the code above, we are importing the routes module we created earlier, and using it as middleware in our application. The app.use('/api', routes) line tells Express.js to use the routes module for all routes that start with /api.

Testing the API Now that we have set up our API, we can test it using a tool like Postman or cURL. Let’s test our API by sending a GET request to /api/hello and a POST request to /api/hello with a name parameter.

If you’re using Postman, create a new request with the following details:

  • Method: GET
  • URL: http://localhost:3000/api/hello

Click the “Send” button to send the request, and you should see a “Hello World!” message in the response.

Next, create a new request with the following details:

  • Method: POST
  • URL: http://localhost:3000/api/hello
  • Body: { "name": "John" }
  • Headers: Content-Type: application/json

Click the “Send” button to send the request, and you should see a personalized greeting in the response, like “Hello John!”.

 

Conclusion:

In this blog post, we learned how to build a RESTful API using Node.js and Express.js. We created a simple API with two routes and used middleware like body-parser and cors to handle request bodies and cross-origin requests. We also saw how to test our API using Postman or cURL. With this knowledge, you can start building your own RESTful APIs using Node.js and Express.js.