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

  1. Initialize a Node.js Project:
 mkdir prisma-mongodb-example cd prisma-mongodb-example npm init -y
Enter fullscreen mode
Exit fullscreen mode
  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
Enter fullscreen mode
Exit fullscreen mode
  1. Install Prisma CLI:
 npx prisma init
Enter fullscreen mode
Exit fullscreen mode

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"
Enter fullscreen mode
Exit fullscreen mode
  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 }
Enter fullscreen mode
Exit fullscreen mode

Step 3: Generate Prisma Client

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

npx prisma generate
Enter fullscreen mode
Exit fullscreen mode

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}`); });
Enter fullscreen mode
Exit fullscreen mode

Step 5: Run the Application

  1. Run the Application:
 node index.js
Enter fullscreen mode
Exit fullscreen mode
  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.


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top