Building a RESTful API with Node.js and Express.js
Tags: node, api, javascript, beginners
Published: 2023-06-27 00:50:07

#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
```
2.**Initialize a new Node.js project:**
```
npm init -y
```
3.**Install Express.js:**
```
npm install express
```
#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}`);
});
```
#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);
});
```
#Testing the API 
Start the server by running the following command in your terminal:
```
node app.js
```
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
```
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' });
    });
});
```
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!