Next.js API Project — Building a Complete CRUD API

▲ Next.js 15+ (App Router) 🟢 Chapter 23 of 43 📂 Phase 10: Route Handlers & Backend 📅 2026 Edition
📌 Covered in this chapter: CRUD Operations · Validation · Pagination · Search & Sorting · Error Handling · API Documentation Basics
Ee chapter lo, previous chapter concepts anni కలిపి — ఒక complete Course API build cheద్దాం: Create, Read, Update, Delete, plus search & pagination.
1Project Structure for a CRUD API
app/ └── api/ └── courses/ ├── route.ts → GET (list), POST (create) └── [id]/ └── route.ts → GET (one), PUT (update), DELETE
2List & Create Endpoint (with Pagination & Search)
💻 Example 1: GET with Pagination + Search, POST to Create
app/api/courses/route.ts ▶ Run in Compiler
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 });
}
3Single-Resource Endpoint (Get, Update, Delete by ID)
💻 Example 2: Full CRUD for a Single Course
app/api/courses/[id]/route.ts ▶ Run in Compiler
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` });
}
4Error Handling Pattern for APIs

Production API లో, unexpected errors ni try/catch తో wrap చేసి, consistent error response format ఇవ్వడం best practice:

💻 Example 3: Consistent Error Response
app/api/courses/route.ts ▶ Run in Compiler
export async function GET() {
  try {
    // ... database logic here
    return NextResponse.json({ courses: [] });
  } catch (err) {
    return NextResponse.json({ error: "Something went wrong" }, { status: 500 });
  }
}
⚠️ Common Mistake: No Input Validation on PUT/POST

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 చేయాలి.

💻 Hands-on Interactive Practice Challenge

Add a GET handler variant that returns 404 if a course ID doesn't exist in a sample in-memory array.

app/api/courses/[id]/route.ts ▶ Run in Compiler
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);
}
Run This Challenge in Online Node.js IDE →
Frequently Asked Questions (FAQ)

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 రావాలంటే.

OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on Next.js 15+ (App Router) · Last updated August 2026