Creating CRUD API's in Node.js and Express

A Detailed Blog on how to write CRUD api's

Creating CRUD API's in Node.js and Express

In this blog, we'll walk you through creating a basic API using Node.js and Express that performs CRUD operations (Create, Read, Update, Delete) on a simple dataset. By the end of this tutorial, you should have a good understanding of how to build a RESTful API with Node.js and Express.

Setting up the project:

Let's start by creating a new Node.js project and installing the necessary dependencies:

mkdir nodejs-crud-api && cd nodejs-crud-api
npm init -y
npm install express mongoose body-parser cors

We'll be using the Mongoose library to interact with a MongoDB database, Body-parser to parse incoming request bodies, and Cors to enable Cross-Origin Resource Sharing.

Connecting to MongoDB:

To connect to our MongoDB database, we'll create a new file called db.js and add the following code:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/my-database', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const db = mongoose.connection;

db.on('error', (error) => console.error(error));
db.once('open', () => console.log('Connected to Database'));

Replace my-database with the name of your database. This code connects to our MongoDB database using the Mongoose library and logs a message to the console when the connection is established.

Defining the Schema:

Next, we'll define a schema for our data. In this example, we'll be creating a simple API that manages books. Create a new file called book.js and add the following code:

const mongoose = require('mongoose');

const bookSchema = new mongoose.Schema({
  title: String,
  author: String,
  year: Number,
});

const Book = mongoose.model('Book', bookSchema);

module.exports = Book;

This code defines a new schema for a book with title, author, and year properties. We then create a new Book model using this schema, and export it as a module.

Creating the API routes:

With our database connection and data model defined, we can now create the API routes. Create a new file called index.js and add the following code:

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const Book = require('./book');
const app = express();
const port = 3000;

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

app.get('/books', async (req, res) => {
  const books = await Book.find();
  res.json(books);
});

app.get('/books/:id', async (req, res) => {
  const book = await Book.findById(req.params.id);
  res.json(book);
});

app.post('/books', async (req, res) => {
  const book = new Book(req.body);
  await book.save();
  res.json(book);
});

app.put('/books/:id', async (req, res) => {
  const { id } = req.params;
  const book = await Book.findByIdAndUpdate(id, req.body, { new: true });
  res.json(book);
});

app.delete('/books/:id', async (req, res) => {
  const { id } = req.params;
  await Book.findByIdAndDelete(id);
  res.json({ message: 'Book deleted successfully' });
});

app.listen(port, () => {
  console.log(`Server is listening on http://localhost:${port}`);
});

This code creates an Express application and sets up the necessary middleware. We define the following routes:

  • GET /books - retrieves all books from the database

  • `GET /books

Hope you got some valuable insights from this blog. Keep Learning , Keep Growing!