Mutations, APIs and security · Lesson 10 of 16
Route Handlers: building an API
route.ts, GET and POST, Request and Response, and status codes.
A route.ts file in any app/ folder creates an API endpoint at that URL. You export functions named after HTTP methods (GET, POST, PATCH, DELETE); each takes a Request and returns a Response, the same Web APIs as in the browser.
// app/api/courses/route.ts -> GET /api/courses?track=web, POST /api/courses
import { NextResponse, type NextRequest } from "next/server"
export async function GET(request: NextRequest) {
const track = request.nextUrl.searchParams.get("track")
const courses = await getCourses({ track })
return NextResponse.json(courses)
}
export async function POST(request: Request) {
const user = await getUser()
if (!user) return NextResponse.json({ error: "Sign in first" }, { status: 401 })
const body = await request.json().catch(() => null)
if (!body?.title) return NextResponse.json({ error: "title is required" }, { status: 400 })
const course = await createCourse(body.title, user.id)
return NextResponse.json(course, { status: 201 })
}| Status | Meaning |
|---|---|
200 OK | fine |
201 Created | something was created |
400 Bad Request | the data sent is invalid |
401 Unauthorized | not signed in |
403 Forbidden | signed in but not allowed |
404 Not Found | doesn't exist |
429 Too Many Requests | too many requests (rate limit) |
500 Internal Server Error | our fault |
Quick question
A signed-in user tries to delete a course that isn't theirs. What do you return?
Exercise
Write GET(request) that reads ?name= from the URL and returns JSON { "greeting": "Hello, NAME" } with status 200, or { "error": "name is required" } with status 400 when name is missing. The code below tries it twice.
200 {"greeting":"Hello, Nour"}
400 {"error":"name is required"}async function GET(request) {
return new Response("todo")
}
for (const url of ["https://seacode.tech/api/hello?name=Nour", "https://seacode.tech/api/hello"]) {
const res = await GET(new Request(url))
console.log(res.status, await res.text())
}Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.