Next.js API Project — Building a Complete CRUD API
import { NextRequest, NextResponse } from "next/server";
export async function GET(request: NextRequest) {
const page = Number(request.nextUrl.searchParams.get("page") || "1");
const search = request.nextUrl.searchParams.get("search") || "";
// ... fetch from database, filter by search, paginate by page
return NextResponse.json({ page, search, results: [] });
}
export async function POST(request: NextRequest) {
const body = await request.json();
if (!body.title) {
return NextResponse.json({ error: "Title is required" }, { status: 400 });
}
// ... insert into database
return NextResponse.json({ message: "Course created" }, { status: 201 });
}
import { NextRequest, NextResponse } from "next/server";
type Params = { params: Promise<{ id: string }> };
export async function GET(request: NextRequest, { params }: Params) {
const { id } = await params;
// ... fetch course by id
return NextResponse.json({ id, title: "Sample Course" });
}
export async function PUT(request: NextRequest, { params }: Params) {
const { id } = await params;
const body = await request.json();
// ... update course by id
return NextResponse.json({ message: `Course ${id} updated`, data: body });
}
export async function DELETE(request: NextRequest, { params }: Params) {
const { id } = await params;
// ... delete course by id
return NextResponse.json({ message: `Course ${id} deleted` });
}
Production API లో, unexpected errors ni try/catch తో wrap చేసి, consistent error response format ఇవ్వడం best practice:
export async function GET() {
try {
// ... database logic here
return NextResponse.json({ courses: [] });
} catch (err) {
return NextResponse.json({ error: "Something went wrong" }, { status: 500 });
}
}
Update/Create endpoints లో body fields validate చేయకుండా direct ga database లో save చేయడం — malformed leda malicious data DB ni corrupt చేయవచ్చు. Prathi write operation ki mundు required fields, types check చేయాలి.
Add a GET handler variant that returns 404 if a course ID doesn't exist in a sample in-memory array.
import { NextRequest, NextResponse } from "next/server";
const courses = [{ id: "1", title: "Next.js Mastery" }];
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params;
const course = courses.find((c) => c.id === id);
if (!course) {
return NextResponse.json({ error: "Course not found" }, { status: 404 });
}
return NextResponse.json(course);
}
Q Pagination ఎలా implement చేయాలి real database తో?
Typically LIMIT/OFFSET (SQL) leda skip/take (Prisma) వాడతారు — page number ni database query offset కి convert చేస్తారు. Chapter 25 (Prisma ORM) లో ఇది hands-on చూద్దాం.
Q API documentation ఎలా రాయాలి?
Simple projects కి, README లో endpoints, params, sample responses document చేయవచ్చు. Larger APIs కి OpenAPI/Swagger spec generate చేయడం industry standard.
Q Ee API ni external mobile app నుండి call చేయవచ్చా?
Avunు — ఇదే Route Handlers pెద్ద advantage. Kani CORS headers సరిగ్గా configure చేయాలి, వేరే domain నుండి requests రావాలంటే.