In SvelteKit, API routes are used to serve data endpoints. Why is this approach preferred over serving data directly from page components?
Think about how separating concerns helps in organizing code.
API routes handle data fetching and processing separately from UI rendering. This separation makes the app easier to maintain and test.
Consider a SvelteKit app where a page component fetches JSON data from an API route. What is the expected behavior when the page loads?
Think about how JSON data is commonly used between backend and frontend.
API routes return JSON data that page components fetch and use to render dynamic content.
Which of the following code snippets correctly defines a SvelteKit API route that returns JSON data?
export async function GET() { // return JSON data }
Remember that API routes must return a Response object with proper headers.
In SvelteKit, API routes return a Response object with JSON string and content-type header to serve JSON data correctly.
Given this API route code, why does it cause a runtime error when called?
export async function GET() { return { message: 'Hello' }; }
Check what the API route function is expected to return.
SvelteKit API routes must return a Response object. Returning a plain object causes a runtime error.
Consider a SvelteKit page component that fetches data from an API route returning { "count": 5 }. What will be the value of count displayed on the page after loading?
<script> import { onMount } from 'svelte'; let count = 0; onMount(async () => { const res = await fetch('/api/count'); const data = await res.json(); count = data.count; }); </script> <p>Count: {count}</p>
Think about when count is updated and what onMount does.
The page starts with count = 0, but after fetching data from the API route, count is updated to 5 and displayed.