DEV Community

Cover image for Building a RESTful API with Node.js and Express.js
Utkarsh Yadav
Utkarsh Yadav

Posted on

Building a RESTful API with Node.js and Express.js

Introduction:

In this developer journal, we will dive into building a RESTful API using Node.js and Express.js. RESTful APIs have become a fundamental part of modern web development, enabling communication between client applications and servers. We will explore the basic setup, routing, handling requests and responses, and connecting to a database. Let's get started!

Setting Up the Project:

To begin, let's set up our project. Open your terminal and follow these steps:
1.Create a new directory for your project:

mkdir restful-api
cd restful-api
Enter fullscreen mode Exit fullscreen mode

2.Initialize a new Node.js project:

npm init -y
Enter fullscreen mode Exit fullscreen mode

3.Install Express.js:

npm install express
Enter fullscreen mode Exit fullscreen mode

Creating the Express App:

Now that we have our project set up, let's create our Express application. Create a file named app.js in the project directory and add the following code:

const express = require('express');
const app = express();
const port = 3000;

app.use(express.json());

// We will define the routes here!!

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});
Enter fullscreen mode Exit fullscreen mode

Defining Routes:

Replace the comment // We will define the routes here!! in app.js with the following code:

const books = [];

app.get('/books', (req, res) => {
  res.json(books);
});

app.post('/books', (req, res) => {
  const { title, author } = req.body;
  const book = { title, author };
  books.push(book);
  res.status(201).json(book);
});
Enter fullscreen mode Exit fullscreen mode

Testing the API

Start the server by running the following command in your terminal:

node app.js
Enter fullscreen mode Exit fullscreen mode

Open your favorite API testing tool (e.g., Postman, curl) and send some requests to http://localhost:3000/books. Use a GET request to retrieve all books and a POST request to add a new book.

Handling Database Integration:

We'll use MongoDB and the mongoose library. Install mongoose by running the following command:

npm install mongoose
Enter fullscreen mode Exit fullscreen mode

In app.js add the following code after the -
const books = []; line

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/books', { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => {
    console.log('Connected to the database');
  })
  .catch((error) => {
    console.error('Error connecting to the database:', error);
  });

const Book = mongoose.model('Book', {
  title: String,
  author: String,
});

app.post('/books', (req, res) => {
  const { title, author } = req.body;
  const book = new Book({ title, author });
  book.save()
    .then((savedBook) => {
      res.status(201).json(savedBook);
    })
    .catch((error) => {
      res.status(500).json({ error: 'An error occurred' });
    });
});
Enter fullscreen mode Exit fullscreen mode

This code connects to a local MongoDB database named "books" and defines a Book model using Mongoose. The POST route now saves the book to the database using the model.

Conclusion:

In this developer journal, I've covered the basics of building a RESTful API with Node.js and Express.js. We set up the project, defined routes, handled requests and responses, and integrated a database using MongoDB and Mongoose. This is just the beginning of what you can accomplish with Node.js and Express.js in building powerful and scalable APIs. Happy coding!
ThankYou!

Top comments (0)