API – Creating a Api in NodeJS with Prisma ORM & MongoDB

To create an example API in Node.js with MongoDB using Prisma ORM, you’ll first need to set up a Node.js project and configure Prisma to use MongoDB. Below is a step-by-step guide to create a basic API.

Step 1: Set Up Your Project

Initial…


This content originally appeared on DEV Community and was authored by Dhiman_aman

To create an example API in Node.js with MongoDB using Prisma ORM, you'll first need to set up a Node.js project and configure Prisma to use MongoDB. Below is a step-by-step guide to create a basic API.

Step 1: Set Up Your Project

  1. Initialize a Node.js Project:
   mkdir prisma-mongodb-example
   cd prisma-mongodb-example
   npm init -y
  1. Install Required Packages: Install express for building the API, prisma for ORM, and @prisma/client for Prisma Client.
   npm install express prisma @prisma/client
  1. Install Prisma CLI:
   npx prisma init

Step 2: Configure Prisma for MongoDB

  1. Configure .env File: Update the .env file generated by Prisma to include your MongoDB connection string. For example:
   DATABASE_URL="mongodb://localhost:27017/mydatabase"
  1. Set Prisma Schema to Use MongoDB: Update the prisma/schema.prisma file to use MongoDB as the provider and define a model. Here is an example schema:
   datasource db {
     provider = "mongodb"
     url      = env("DATABASE_URL")
   }

   generator client {
     provider = "prisma-client-js"
   }

   model User {
     id    String @id @default(auto()) @map("_id") @db.ObjectId
     name  String
     email String @unique
   }

Step 3: Generate Prisma Client

Run the following command to generate the Prisma Client based on the schema:

npx prisma generate

Step 4: Create a Basic Express API

  1. Create an index.js File: This file will initialize the Express application and define the API routes.
   const express = require('express');
   const { PrismaClient } = require('@prisma/client');

   const prisma = new PrismaClient();
   const app = express();
   app.use(express.json());

   // Create a new user
   app.post('/users', async (req, res) => {
     const { name, email } = req.body;
     try {
       const user = await prisma.user.create({
         data: { name, email },
       });
       res.json(user);
     } catch (error) {
       res.status(400).json({ error: error.message });
     }
   });

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

   // Get a single user by ID
   app.get('/users/:id', async (req, res) => {
     const { id } = req.params;
     try {
       const user = await prisma.user.findUnique({
         where: { id },
       });
       if (user) {
         res.json(user);
       } else {
         res.status(404).json({ error: 'User not found' });
       }
     } catch (error) {
       res.status(500).json({ error: error.message });
     }
   });

   // Update a user by ID
   app.put('/users/:id', async (req, res) => {
     const { id } = req.params;
     const { name, email } = req.body;
     try {
       const user = await prisma.user.update({
         where: { id },
         data: { name, email },
       });
       res.json(user);
     } catch (error) {
       res.status(400).json({ error: error.message });
     }
   });

   // Delete a user by ID
   app.delete('/users/:id', async (req, res) => {
     const { id } = req.params;
     try {
       await prisma.user.delete({
         where: { id },
       });
       res.json({ message: 'User deleted successfully' });
     } catch (error) {
       res.status(500).json({ error: error.message });
     }
   });

   const PORT = process.env.PORT || 3000;
   app.listen(PORT, () => {
     console.log(`Server is running on http://localhost:${PORT}`);
   });

Step 5: Run the Application

  1. Run the Application:
   node index.js
  1. Test the Endpoints: Use tools like Postman or cURL to test the CRUD operations for the User model.

Conclusion

This example demonstrates how to create a basic CRUD API in Node.js with MongoDB using Prisma ORM. You can expand this example by adding more models, relationships, and validation logic as needed for your application.


This content originally appeared on DEV Community and was authored by Dhiman_aman


Print Share Comment Cite Upload Translate Updates
APA

Dhiman_aman | Sciencx (2024-09-07T05:59:51+00:00) API – Creating a Api in NodeJS with Prisma ORM & MongoDB. Retrieved from https://www.scien.cx/2024/09/07/api-creating-a-api-in-nodejs-with-prisma-orm-mongodb/

MLA
" » API – Creating a Api in NodeJS with Prisma ORM & MongoDB." Dhiman_aman | Sciencx - Saturday September 7, 2024, https://www.scien.cx/2024/09/07/api-creating-a-api-in-nodejs-with-prisma-orm-mongodb/
HARVARD
Dhiman_aman | Sciencx Saturday September 7, 2024 » API – Creating a Api in NodeJS with Prisma ORM & MongoDB., viewed ,<https://www.scien.cx/2024/09/07/api-creating-a-api-in-nodejs-with-prisma-orm-mongodb/>
VANCOUVER
Dhiman_aman | Sciencx - » API – Creating a Api in NodeJS with Prisma ORM & MongoDB. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/09/07/api-creating-a-api-in-nodejs-with-prisma-orm-mongodb/
CHICAGO
" » API – Creating a Api in NodeJS with Prisma ORM & MongoDB." Dhiman_aman | Sciencx - Accessed . https://www.scien.cx/2024/09/07/api-creating-a-api-in-nodejs-with-prisma-orm-mongodb/
IEEE
" » API – Creating a Api in NodeJS with Prisma ORM & MongoDB." Dhiman_aman | Sciencx [Online]. Available: https://www.scien.cx/2024/09/07/api-creating-a-api-in-nodejs-with-prisma-orm-mongodb/. [Accessed: ]
rf:citation
» API – Creating a Api in NodeJS with Prisma ORM & MongoDB | Dhiman_aman | Sciencx | https://www.scien.cx/2024/09/07/api-creating-a-api-in-nodejs-with-prisma-orm-mongodb/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.