CodeBlanks Logo Icon CodeBlanks

Challenge: Next.js API

Write an API route that returns products with GET and adds with POST.

Challenge: Next.js API

In this challenge you will write a Next.js App Router route handler. In app/api/items/route.js you define GET and POST functions.

GET returns a JSON array; POST reads the request body and responds with NextResponse.json at status 201. Remember to export.

Practice Write the API route handler

Write app/api/items/route.js. Import NextResponse. In export async function GET() return NextResponse.json([{ id: 1 }]). In export async function POST(request) read the body with request.json() and respond with NextResponse.json(body, { status: 201 }).

Starter code

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

// Write the GET and POST functions here

Sample solution

App.jsx
import { NextResponse } from 'next/server';

export async function GET() {
  return NextResponse.json([{ id: 1 }]);
}

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

Questions and answers

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

1 Where does an App Router route handler live?

  • app/api/items/route.js Correct answer
  • app/api/route.js
  • pages/api/items.js
  • server.js

Explanation: In App Router the route is defined in route.js.

2 Fill in the blank: respond with status 201

Question
import { NextResponse } from 'next/server';

export async function POST(request) {
  const body = await request.json();
  return NextResponse.json(body, { status: ____ });
}
Answer
import { NextResponse } from 'next/server';

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

Explanation: POST returns 201 for successful creation.

All lessons in Advanced