Kurs Svelte i SvelteKit · Moduł 14: Hooki, API i wdrożenie

API Routes (+server.js)

2 min czytania ·
W tej lekcji3

Podstawowe API

Plik +server.js eksportuje funkcje nazwane jak metody HTTP. Każda dostaje żądanie i zwraca standardowy obiekt Response:

// src/routes/api/warriors/+server.js
export async function GET() {
  const warriors = await db.warriors.findMany();
  return Response.json(warriors);
}

export async function POST({ request }) {
  const data = await request.json();
  const warrior = await db.warriors.create(data);
  return Response.json(warrior, { status: 201 });
}

Response.json() to część zwykłego Web API: zamienia obiekt na JSON i ustawia nagłówek Content-Type. W SvelteKit 3 pomocnicze funkcje json() i text() z @sveltejs/kit są przestarzałe.

Dynamiczne API

// src/routes/api/warriors/[id]/+server.js
import { error } from '@sveltejs/kit';

export async function GET({ params }) {
  const warrior = await db.warriors.findUnique({
    where: { id: params.id }
  });

  if (!warrior) {
    error(404, 'Nie znaleziono');
  }

  return Response.json(warrior);
}

export async function DELETE({ params }) {
  await db.warriors.delete({
    where: { id: params.id }
  });

  return new Response(null, { status: 204 });
}

Headers i Cookies

export async function GET({ cookies, request }) {
  // Odczytaj cookie
  const session = cookies.get('session');

  // Odczytaj header
  const auth = request.headers.get('Authorization');

  // Ustaw cookie (domyślna ścieżka to '/')
  cookies.set('visited', 'true', {
    httpOnly: true,
    maxAge: 60 * 60 * 24 * 7
  });

  return Response.json({ data });
}

Endpointy API to bramy Twojej twierdzy - przez nie inne aplikacje rozmawiają z Twoim serwerem.

Kod do tej lekcji: App.svelte
<script>
  // API Routes - +server.js

  let warriors = $state([
    { id: 1, name: 'Ragnar', strength: 95 },
    { id: 2, name: 'Bjorn', strength: 90 }
  ]);

  let response = $state(null);
  let loading = $state(false);

  // Symulacja GET
  async function fetchWarriors() {
    loading = true;
    await new Promise(r => setTimeout(r, 500));
    response = { method: 'GET', data: warriors };
    loading = false;
  }

  // Symulacja POST
  async function createWarrior() {
    loading = true;
    await new Promise(r => setTimeout(r, 500));
    const newWarrior = { id: Date.now(), name: 'Ivar', strength: 85 };
    warriors = [...warriors, newWarrior];
    response = { method: 'POST', data: newWarrior, status: 201 };
    loading = false;
  }

  // Symulacja DELETE
  async function deleteWarrior() {
    if (warriors.length === 0) return;
    loading = true;
    await new Promise(r => setTimeout(r, 500));
    const deleted = warriors[warriors.length - 1];
    warriors = warriors.slice(0, -1);
    response = { method: 'DELETE', data: deleted, status: 204 };
    loading = false;
  }
</script>

<main class="api-demo">
  <h1>API Routes (+server.js)</h1>

  <section class="code">
    <h2>src/routes/api/warriors/+server.js</h2>
    <pre>
export async function GET() {"{"}
  const warriors = await db.warriors.findMany();
  return Response.json(warriors);
{"}"}

export async function POST({"{"} request {"}"}) {"{"}
  const data = await request.json();
  const warrior = await db.warriors.create(data);
  return Response.json(warrior, {"{"} status: 201 {"}"});
{"}"}

export async function DELETE({"{"} params {"}"}) {"{"}
  await db.warriors.delete(params.id);
  return new Response(null, {"{"} status: 204 {"}"});
{"}"}
    </pre>
  </section>

  <section class="test">
    <h2>Testuj API</h2>
    <div class="buttons">
      <button onclick={fetchWarriors} disabled={loading}>
        GET /api/warriors
      </button>
      <button onclick={createWarrior} disabled={loading}>
        POST (dodaj Ivar)
      </button>
      <button onclick={deleteWarrior} disabled={loading}>
        DELETE (usuń ostatniego)
      </button>
    </div>
  </section>

  {#if response}
    <section class="response">
      <h2>Odpowiedź</h2>
      <p><strong>Method:</strong> {response.method}</p>
      {#if response.status}
        <p><strong>Status:</strong> {response.status}</p>
      {/if}
      <pre>{JSON.stringify(response.data, null, 2)}</pre>
    </section>
  {/if}

  <section class="state">
    <h2>Stan w "bazie" ({warriors.length})</h2>
    {#each warriors as w}
      <div class="warrior">{w.name} ({w.strength})</div>
    {/each}
  </section>
</main>

<style>
  .api-demo {
    font-family: 'Georgia', serif;
    max-width: 600px;
    margin: 0 auto;
    padding: 2rem;
    background: #0a1628;
    color: #b8d4f7;
    min-height: 100vh;
  }

  h1 {
    color: #4a90d9;
    text-align: center;
  }

  section {
    background: rgba(74, 144, 217, 0.1);
    border: 1px solid #4a90d9;
    border-radius: 8px;
    padding: 1rem;
    margin: 1rem 0;
  }

  h2 {
    color: #4a90d9;
    font-size: 1rem;
    margin-top: 0;
  }

  pre {
    background: rgba(0,0,0,0.5);
    padding: 1rem;
    border-radius: 4px;
    font-size: 0.8rem;
    overflow-x: auto;
  }

  .buttons {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
  }

  button {
    padding: 0.75rem;
    background: #1e3a5f;
    color: #b8d4f7;
    border: 1px solid #4a90d9;
    border-radius: 4px;
    cursor: pointer;
    text-align: left;
  }

  button:disabled {
    opacity: 0.5;
  }

  strong {
    color: #ffd700;
  }

  .warrior {
    padding: 0.5rem;
    background: rgba(0,0,0,0.3);
    border-radius: 4px;
    margin-bottom: 0.25rem;
  }
</style>

Hasła z dokumentacji w tej lekcji

Widzisz błąd w tej lekcji?

Sprawdź się

Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.

  1. 1. Jak utworzyć endpoint GET /api/warriors?

  1. PytanieEndpoint GET /api/warriors

Przydatne artykuły