0
0
Svelteframework~5 mins

Why API routes serve data endpoints in Svelte

Choose your learning style9 modes available
Introduction

API routes let your app send or get data without showing a new page. They act like helpers that give data when asked.

When you want to get user info without reloading the page.
When your app needs to save form data to a database.
When you want to fetch a list of items to show in a list.
When you need to update part of the page based on user actions.
When you want to keep your data logic separate from your page layout.
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
This example sends a simple JSON greeting when the GET request is made.
Svelte
export async function GET() {
  return new Response(JSON.stringify({ greeting: 'Hi there!' }), {
    headers: { 'Content-Type': 'application/json' }
  });
}
This example reads JSON data sent by the client and sends it back in the response.
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' }
  });
}
OutputSuccess
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.