Initialize a Next.js project if you haven’t already, by running:
npx create-next-app@latest my-student-api
cd my-student-api
BashInstall Prisma as a dev dependency and initialize it in your project:
npm install prisma --save-dev
npx prisma init
BashInstall Prisma Client to interact with the database:
npm install @prisma/client
BashSet up your database connection in .env
:
DATABASE_URL="mysql://user:password@localhost:3306/mydb"
BashDefine your data model for students in prisma/schema.prisma
:
model Student {
id Int @id @default(autoincrement())
firstName String
lastName String
email String @unique
age Int
// Any other fields you require
}
BashRun the migration to create your database schema:
npx prisma migrate dev
BashCreate API routes for CRUD operations in the app/routes/api
directory, for example:
Read – Fetch all students or a specific student by ID:
// app/routes/api/students.ts
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
// GET /api/students
export async function get() {
const students = await prisma.student.findMany();
return new Response(JSON.stringify(students), {
status: 200,
headers: {
'Content-Type': 'application/json',
},
});
}
// POST /api/students to create a new student
export async function post({ request }) {
const data = await request.json();
const createdStudent = await prisma.student.create({ data });
return new Response(JSON.stringify(createdStudent), {
status: 201,
headers: {
'Content-Type': 'application/json',
},
});
}
// PUT /api/students/:id
export async function put({ request, params }) {
const data = await request.json();
const { id } = params;
try {
const student = await prisma.student.update({
where: { id: parseInt(id, 10) },
data,
});
return new Response(JSON.stringify(student), {
status: 200,
headers: {
'Content-Type': 'application/json',
},
});
} catch (error) {
return new Response(JSON.stringify({ error: "Student not found" }), {
status: 404,
headers: {
'Content-Type': 'application/json',
},
});
}
}
// DELETE /api/students/:id
export async function del({ params }) {
const { id } = params;
try {
const student = await prisma.student.delete({
where: { id: parseInt(id, 10) },
});
return new Response(JSON.stringify(student), {
status: 200,
headers: {
'Content-Type': 'application/json',
},
});
} catch (error) {
return new Response(JSON.stringify({ error: "Student not found or already deleted" }), {
status: 404,
headers: {
'Content-Type': 'application/json',
},
});
}
}
JavaScriptget student by id
// app/routes/api/students/[id].ts
import { PrismaClient } from '@prisma/client';
import { getServerData } from 'next';
const prisma = new PrismaClient();
export async function getServerData({ params }) {
const { id } = params;
try {
const student = await prisma.student.findUnique({
where: { id: parseInt(id, 10) }, // Ensure the ID is an integer
});
if (student) {
return {
props: { student },
};
} else {
return {
status: 404,
props: { error: "Student not found" },
};
}
} catch (error) {
return {
status: 500,
props: { error: "An error occurred while fetching the student" },
};
}
}
JavaScript