CodeBlanks Logo Icon CodeBlanks

Summary - API routes

Write an API that lists products and adds a new one.

Summary - API routes

In this group you saw Next.js API routes: app/api/.../route.js, HTTP methods, JSON responses and error handling. Each method gets its own export async function.

NextResponse.json for JSON responses, await request.json() to read the body, try/catch for errors are the standard tools.

Now write a small CRUD route: GET and POST together.

Practice CRUD route

Write GET and POST functions. GET: return NextResponse.json({ items: ["a", "b"] }). POST: read body with await request.json(), return NextResponse.json({ created: data }, { status: 201 }). Include import { NextResponse } from "next/server" and both export async functions.

Starter code

App.jsx
// app/api/items/route.js

// import NextResponse, GET ve POST fonksiyonlarını yaz

Sample solution

App.jsx
// app/api/items/route.js
import { NextResponse } from "next/server";

export async function GET() {
  return NextResponse.json({ items: ["a", "b"] });
}

export async function POST(request) {
  const data = await request.json();
  return NextResponse.json({ created: data }, { status: 201 });
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is an API route file?

  • app/users/api.js
  • app/api/users/page.js
  • app/api/users/route.js Correct answer
  • app/route.js

Explanation: API = app/api/.../route.js.

2 POST body

Question
export async function POST(request) {
  const body = await request.____();
  return NextResponse.json({ data: body });
}
Answer
export async function POST(request) {
  const body = await request.json();
  return NextResponse.json({ data: body });
}

Explanation: await request.json() gives the JSON body.

All lessons in Advanced