Create CRUD APIs using Nodejs & MongoDB

Node.js and MongoDB: A Dynamic Duo for Robust API Development

Create CRUD APIs using Nodejs & MongoDB

Introduction

APIs are the backbone of frontend and backend applications. They play a critical role in enabling communication and data exchange between the frontend and backend of an application. You can create them using any server-side language like PHP, Python, Java, JavaScript, GO, etc., but we will build an API using JavaScript.

In this blog, we're going to build basic CRUD APIs using Node.js and MongoDB. If you're a frontend developer looking to explore the backend world, then this blog will be very helpful. So, without further ado, let's get started building our APIs.

Prerequisite

What is API and why it is everywhere?

An API, or Application Programming Interface, acts as a bridge between different software applications, enabling them to communicate and interact with each other. They set the rules and protocols for how applications can share information, simplifying the process for developers to create complex systems by reusing existing functionality.

APIs can be categorized into different types based on their purpose and implementation:

  1. Web APIs: These are APIs accessed over the web using standard protocols like HTTP. Web APIs are often used to integrate web services and enable communication between web applications.
    Example:- Google Maps API: Allows developers to integrate Google Maps into their web applications and customize maps, markers, and routes.

  2. RESTful APIs: REST (Representational State Transfer) is a design approach for networked applications. RESTful APIs follow REST principles and use standard HTTP methods (GET, POST, PUT, DELETE) to carry out operations on resources.
    Example:- Spotify API: Provides access to Spotify's music catalog, allowing developers to search for tracks, albums, and playlists.

  3. SOAP APIs: SOAP (Simple Object Access Protocol) is a protocol used for exchanging structured information in web services. SOAP APIs use XML to format messages and can be more complex than RESTful APIs.
    Example:- Salesforce API: Allows developers to access and manage Salesforce data and features using SOAP messages.

  4. GraphQL APIs: GraphQL is a query language for APIs that lets clients request only the data they need. This makes it a more flexible and efficient option for interacting with APIs than traditional RESTful APIs.
    Example:- Shopify GraphQL API: Allows developers to interact with Shopify's e-commerce platform and manage products, orders, and customers.

  5. Library APIs: These are APIs provided by programming libraries or frameworks, enabling developers to utilize the functionality offered by the library in their applications.
    Example:- TensorFlow API: Provides machine learning capabilities for developers, allowing them to create and train machine learning models in TensorFlow.

So now we have a brief understanding of what an API is and the different types of APIs. Let's set up our Node.js API project.

Project Setup

To set up a Node.js project with Prisma and MongoDB for a CRUD API, you'll need to follow these general steps:

Step-1: Initialize a new Node.js project

This step creates a new directory for your project and initializes a new Node.js project with default settings using npm init -y

mkdir node-api-demo
cd node-api-demo
npm init -y

Step-2: Install necessary dependencies

This step installs the required packages for your project, including Express for building the API, Prisma for database ORM, and MongoDB for the database itself.

npm install express prisma mongodb
  • Express: Express is a simple and flexible Node.js web application framework that offers a strong set of features for developing web and mobile applications. It makes the process of setting up web servers and managing HTTP requests and responses easier.

  • Prisma: Prisma is a modern database toolkit that simplifies database access and management for application developers. It provides a type-safe and auto-generated query builder that helps you write safer and more efficient database queries in your application.

  • MongoDB: MongoDB is a widely used open-source NoSQL database that stores data in flexible, JSON-like documents. It's scalable, high-performing, and doesn't require a fixed schema, making it a popular choice for modern web applications due to its flexibility and user-friendly nature.

Step-3: Set up Prisma for MongoDB

  • Install Prisma CLI:
    The Prisma CLI is a command-line tool used for managing Prisma projects. It's installed as a development dependency.

      npm install prisma -D
    
  • Initialize Prisma:
    Running npx prisma init initializes a new Prisma project in your current directory. This command sets up the necessary files and folders for Prisma.

      npx prisma init
    
  • Configure Prisma to use MongoDB in prisma/schema.prisma:
    In the prisma/schema.prisma file, you configure Prisma to use MongoDB as the datasource. You specify the MongoDB connection URL and other configuration options.

      generator client {
        provider = "prisma-client-js"
      }
    
      datasource db {
        provider = "mongodb"
        url      = "url mongodb cloud connection string"
      }
    

Step-4: Define Prisma model

In the prisma/schema.prisma file, you define your data model using Prisma's schema language. This defines the structure of your data and how it will be stored in the database.

model Users{
  id          String @id @default(uuid()) @map("_id") @db.String
  name        String?
  email       String @unique
  createdAt DateTime     @default(now())
}

Step-5: Generate Prisma client

After defining your model, you generate the Prisma client using npx prisma generate. This generates the client code that you can use to interact with your database in your Node.js application.

npx prisma generate

Step-6: Creating Express server with CRUD APIs routes

This step involves creating an Express server in your index.js file. You define routes for handling CRUD operations (Create, Read, Update, Delete) for your data model.

const express = require('express');
const { PrismaClient } = require('@prisma/client');

const prisma = new PrismaClient();
const app = express();

app.use(express.json());

app.get('/users', async (req, res) => {
  const users = await prisma.users.findMany();
  res.json(users);
});

app.post('/users', async (req, res) => {
  const { name, email } = req.body;
  const user = await prisma.users.create({
    data: {
      name,
      email,
    },
  });
  res.json(user);
});

app.put('/users/:id', async (req, res) => {
  const { id } = req.params;
  const { name, email } = req.body;
  const user = await prisma.users.update({
    where: { id },
    data: {
      name,
      email,
    },
  });
  res.json(user);
});

app.delete('/users/:id', async (req, res) => {
  const { id } = req.params;
  await prisma.users.delete({
    where: { id },
  });
  res.json({"msg":"User Deleted !!", "status":true});
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});
  • express: This is the Express.js framework for building web applications.

  • PrismaClient: This is the Prisma client used to interact with the database.

  • prisma: Creates a new instance of the Prisma client, which will be used to interact with the database.

  • app: Creates a new instance of the Express application.

  • express.json(): Parses incoming JSON requests and makes it available in req.body

  • GET /users: Retrieves a list of all users from the database.

  • POST /users: Creates a new user in the database.

  • PUT /users/:id: Updates an existing user with the specified ID.

  • DELETE /users/:id: Deletes an existing user with the specified ID.

  • Starts the Express server on port 3000 and logs a message to indicate that the server is running

Step-7: Start the server

Finally, you start your Express server using node index.js. This starts the server, and you can then access your API endpoints to perform CRUD operations on your MongoDB database.

node index.js

Step:-8 Testing APIs

To test the apis which we develop, we need to use Postman. Why Postman? Postman is a popular software application used for API development. It provides a user-friendly interface for sending HTTP requests to a server, viewing the responses and commonly used for testing APIs during development, allowing developers to quickly test different endpoints, parameters, and authentication methods.

  1. Create an User using API

  2. Get an User using API

  3. Update an User using API

  4. Delete an User using API

Conclusion

In conclusion, building CRUD APIs using Node.js and MongoDB is a valuable skill for any developer looking to bridge the gap between frontend and backend development. Throughout this guide, we've covered the essential steps from setting up your project environment to testing your APIs with Postman.

By following these steps, you not only gain a deeper understanding of how APIs function but also equip yourself with the knowledge to create robust and scalable web applications. Remember, the journey doesn't stop here; continue experimenting with different databases, explore more advanced features of Node.js and MongoDB, and keep refining your API development skills.

Thank you for reading my article. Feel free to comment and share your suggestions or thoughts.

Also, Follow me on Twitter or Linkedin share Cloud, System Design, Code, and many more tech stuff ๐Ÿ˜Š

Resources

Did you find this article valuable?

Support Pradhumansinh Padhiyar by becoming a sponsor. Any amount is appreciated!

ย