Deviopath › Next.js

Todos API (GET + POST)

Medium · Route Handlers

A route.ts file creates an API endpoint. You export one async function per HTTP method (GET, POST, PUT, DELETE, ...). Each receives the incoming Request and returns a Response. Response.json(data, { status }) sends JSON. (Next.js also has NextRequest / NextResponse, which extend these Web classes with extras.) If a method has no exported function, Next.js answers 405 Method Not Allowed for you.

Implement the handlers for /api/todos on the in-memory db:

- GET: respond 200 with the todos array. With ?done=true return only done todos, with ?done=false only open ones. Any other value (or no param) returns all.

- POST: read the JSON body with await request.json(). - If the body is not valid JSON, respond 400 with { error: "Invalid JSON" }. - title must be a string that is not empty after trim(). Otherwise respond 400 with { error: "Title is required" }. - Create { id, title, done } with the next id (db.nextId++, only for created todos), the trimmed title and done: true only if the body has done: true. Respond 201 with the new todo.

The driver runRequests(requests) is already written. Each request is { method, url, body? } (body is a raw string) and the result is { status, body } per request.

Next: Validate a Server Action