API routes let your app send or get data without showing a new page. They act like helpers that give data when asked.
Why API routes serve data endpoints in Svelte
Introduction
Syntax
Svelte
export async function GET(event) { // handle GET request return new Response(JSON.stringify({ message: 'Hello' }), { headers: { 'Content-Type': 'application/json' } }); } export async function POST(event) { // handle POST request const data = await event.request.json(); return new Response(JSON.stringify({ received: data }), { headers: { 'Content-Type': 'application/json' } }); }
API routes use special functions like GET or POST to handle different request types.
They return a Response object with data and headers to tell the browser what kind of data it is.
Examples
Svelte
export async function GET() { return new Response(JSON.stringify({ greeting: 'Hi there!' }), { headers: { 'Content-Type': 'application/json' } }); }
Svelte
export async function POST(event) { const data = await event.request.json(); return new Response(JSON.stringify({ youSent: data }), { headers: { 'Content-Type': 'application/json' } }); }
Sample Program
This API route sends a list of users as JSON when a GET request is made. It helps the frontend get user data without loading a new page.
Svelte
export async function GET() { const users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ]; return new Response(JSON.stringify(users), { headers: { 'Content-Type': 'application/json' } }); }
Important Notes
API routes are like mini servers inside your app that only send data.
Always set the 'Content-Type' header to 'application/json' when sending JSON data.
You can handle different HTTP methods (GET, POST, etc.) by exporting functions with those names.
Summary
API routes serve data so your app can update parts without full page reloads.
They use functions named after HTTP methods to respond to requests.
They return JSON data with proper headers for easy use in your frontend.
Practice
1. Why do API routes in SvelteKit serve data endpoints instead of full HTML pages?
easy
Solution
Step 1: Understand the purpose of API routes
API routes are designed to send data, not full pages, so frontend can update parts dynamically.Step 2: Compare with full page reloads
Serving data endpoints avoids reloading the entire page, improving user experience and speed.Final Answer:
To provide data that frontend components can use without reloading the whole page -> Option DQuick Check:
API routes serve data, not full pages [OK]
Hint: API routes send data, not full pages, for smooth updates [OK]
Common Mistakes:
- Thinking API routes serve full HTML pages
- Confusing API routes with static file servers
- Assuming API routes only handle authentication
2. Which of the following is the correct way to define a GET handler in a SvelteKit API route?
easy
Solution
Step 1: Recall SvelteKit API route syntax
Handlers must be exported functions named after HTTP methods in uppercase, e.g., GET.Step 2: Check return type
Handlers return a Response object or an object with status and body; returning a string alone is invalid.Final Answer:
export async function GET() { return new Response('Hello'); } -> Option BQuick Check:
Use uppercase method names and return Response [OK]
Hint: Use uppercase method names and return Response objects [OK]
Common Mistakes:
- Using lowercase method names like get instead of GET
- Returning plain strings instead of Response or object
- Not exporting the handler function
3. Given this SvelteKit API route code, what will be the JSON response body?
export async function GET() {
return new Response(JSON.stringify({ success: true, count: 5 }), {
headers: { 'Content-Type': 'application/json' }
});
}medium
Solution
Step 1: Analyze the returned Response
The handler returns a Response with JSON stringified object and proper content-type header.Step 2: Understand JSON.stringify output
JSON.stringify converts the object { success: true, count: 5 } into a JSON string with keys and values quoted properly.Final Answer:
{"success":true,"count":5} -> Option CQuick Check:
JSON.stringify outputs JSON string with quotes [OK]
Hint: JSON.stringify outputs quoted JSON string [OK]
Common Mistakes:
- Confusing JSON string with plain object notation
- Ignoring content-type header importance
- Expecting array instead of object
4. Identify the error in this SvelteKit API route code:
export function GET() {
return { body: { message: 'Hi' } };
}medium
Solution
Step 1: Check return type requirements
SvelteKit expects API handlers to return a Response object or use the 'json()' helper for JSON responses.Step 2: Identify incorrect return format
Returning { body: { message: 'Hi' } } alone is not valid; it must be wrapped properly.Final Answer:
The function should return a Response object or use 'return json()' helper -> Option AQuick Check:
Return Response or use json() helper [OK]
Hint: Return Response or use json() helper for JSON data [OK]
Common Mistakes:
- Returning plain objects without wrapping
- Using lowercase function names
- Assuming async is always required
5. You want to create an API route in SvelteKit that returns a list of users as JSON. Which approach correctly serves this data endpoint with proper headers and JSON format?
const users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];hard
Solution
Step 1: Confirm correct function name and async usage
The handler must be exported as 'GET' in uppercase and can be async for flexibility.Step 2: Ensure proper JSON response with headers
Returning a Response with JSON stringified data and 'Content-Type: application/json' header is the correct pattern.Final Answer:
export async function GET() { return new Response(JSON.stringify(users), { headers: { 'Content-Type': 'application/json' } }); } -> Option AQuick Check:
Use uppercase GET and return Response with JSON and headers [OK]
Hint: Use uppercase GET and return Response with JSON headers [OK]
Common Mistakes:
- Returning raw arrays without wrapping
- Using lowercase function names
- Omitting content-type header
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
