0
0
Svelteframework~30 mins

Why API routes serve data endpoints in Svelte - See It in Action

Choose your learning style9 modes available
Why API routes serve data endpoints
📖 Scenario: You are building a simple Svelte app that needs to get data from the server. Instead of putting data directly in the page, you will create an API route that sends data as JSON. This is how real apps separate data from the page and allow dynamic updates.
🎯 Goal: Create a SvelteKit API route that returns a JSON list of products. Then fetch this data in a Svelte page and display the product names.
📋 What You'll Learn
Create an API route file src/routes/api/products/+server.js that returns JSON data
Define a list of products as an array of objects with id and name
Create a config variable for the API path in the page component
Fetch the product data from the API route using fetch
Display the product names in a list on the page
💡 Why This Matters
🌍 Real World
Web apps often get data from backend APIs. Using API routes to serve JSON lets the frontend fetch data dynamically and update the UI without reloading the whole page.
💼 Career
Understanding API routes and data fetching is essential for frontend and full-stack developers working with modern frameworks like SvelteKit, React, or Next.js.
Progress0 / 4 steps
1
Create the product data array
In the file src/routes/api/products/+server.js, create a constant called products that is an array with these exact objects: { id: 1, name: 'Apple' }, { id: 2, name: 'Banana' }, and { id: 3, name: 'Cherry' }.
Svelte
Hint

Use export const products = [...] to create the array of product objects.

2
Add the API route handler
In src/routes/api/products/+server.js, add an exported function called GET that returns a JSON response with the products array.
Svelte
Hint

Use export function GET() and return json(products) to send JSON data.

3
Set the API path in the page component
In the Svelte page file src/routes/+page.svelte, create a constant called apiPath and set it to the string '/api/products'.
Svelte
Hint

Define const apiPath = '/api/products'; to hold the API URL.

4
Fetch and display products in the page
In src/routes/+page.svelte, write an async function called loadProducts that fetches from apiPath, converts the response to JSON, and stores it in a products variable. Then use a {#each} block to display each product's name in an unordered list.
Svelte
Hint

Use fetch inside an async function and onMount to load data. Then display with {#each}.