API
Intermediate
Route Handlers (API Routes)
Build API endpoints with Route Handlers for WebSockets, webhooks, and external integrations.
22 min
3 sections
api
route-handlers
webhooks
1
2
3
01. Creating API Endpoints
Section 1 of 3
Route Handlers are defined in route.ts files and export HTTP methods like GET, POST, PUT, PATCH, DELETE, and HEAD.
typescript
// app/api/users/route.ts
import { NextResponse } from 'next/server';
export async function GET() {
const users = await db.user.findMany();
return NextResponse.json(users);
}
export async function POST(request: Request) {
const data = await request.json();
const user = await db.user.create({ data });
return NextResponse.json(user, { status: 201 });
}Exercise
Create a Hello API
Practice
Create a simple API endpoint at /api/hello that returns a JSON greeting.
Back to Course