Svelte and SvelteKit course ยท Module 14: Hooks, API and Deployment
API Routes (+server.js)
In this lesson3
Basic API
A +server.js file exports functions named after HTTP methods. Each one receives the request and returns a standard Response object:
// 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() is part of the plain Web API: it turns an object into JSON and sets the Content-Type header. In SvelteKit 3 the json() and text() helpers from @sveltejs/kit are deprecated.
Dynamic 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, 'Not found');
}
return Response.json(warrior);
}
export async function DELETE({ params }) {
await db.warriors.delete({
where: { id: params.id }
});
return new Response(null, { status: 204 });
}Headers and Cookies
export async function GET({ cookies, request }) {
// Read cookie
const session = cookies.get('session');
// Read header
const auth = request.headers.get('Authorization');
// Set cookie (the default path is '/')
cookies.set('visited', 'true', {
httpOnly: true,
maxAge: 60 * 60 * 24 * 7
});
return Response.json({ data });
}API endpoints are the gates of your fortress - other applications talk to your server through them.
Code for this lesson: 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);
// Simulate GET
async function fetchWarriors() {
loading = true;
await new Promise(r => setTimeout(r, 500));
response = { method: 'GET', data: warriors };
loading = false;
}
// Simulate 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;
}
// Simulate 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>Test the API</h2>
<div class="buttons">
<button onclick={fetchWarriors} disabled={loading}>
GET /api/warriors
</button>
<button onclick={createWarrior} disabled={loading}>
POST (add Ivar)
</button>
<button onclick={deleteWarrior} disabled={loading}>
DELETE (remove last)
</button>
</div>
</section>
{#if response}
<section class="response">
<h2>Response</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>State in "database" ({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>Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. How do you create a GET /api/warriors endpoint?