CodeBlanks Logo Icon CodeBlanks

Meydan okuma: Next.js API

Ürünleri GET ile döndüren ve POST ile ekleyen bir API rotası yazarsın.

Meydan okuma: Next.js API

Bu meydan okumada Next.js App Router ile bir API yol yazıcı (route handler) yazacaksın. app/api/items/route.js dosyasında GET ve POST fonksiyonları tanımlarsın.

GET bir JSON dizisi döndürür; POST gelen gövdeyi okur ve NextResponse.json ile 201 durum kodu yanıt verir. Dışa aktarmayı unutma.

Uygulama API yol yazıcıyı yaz

app/api/items/route.js yaz. NextResponse içe aktar. export async function GET() içinde NextResponse.json([{ id: 1 }]) döndür. export async function POST(request) içinde request.json() ile gövde al ve NextResponse.json(body, { status: 201 }) yanıt ver.

Başlangıç kodu

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

// GET ve POST fonksiyonlarını buraya yaz

Örnek çözüm

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 });
}

Soru ve cevaplar

Dersin sorularını cevaplarıyla birlikte inceleyebilirsin. Kendini denemek istersen dersi interaktif olarak çöz.

1 App Router'da API yol yazıcı hangi dosyada olur?

  • app/api/items/route.js Doğru cevap
  • app/api/route.js
  • pages/api/items.js
  • server.js

Açıklama: App Router'da yol route.js içinde tanımlanır.

2 Boşluğu doldur: 201 durum kodu ile yanıt ver

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

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

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

Açıklama: POST başarılı oluşturma için 201 döner.

İleri seviye bölümündeki tüm dersler