
- Svelte - Home
- Svelte - Introduction
- Svelte - Installation
- Svelte - Reactivity
- Svelte - Props
- Svelte - Logic
- Svelte - Events
- Svelte - Bindings
- Svelte - Classes
- Svelte - Styles
- Svelte - Actions
- Svelte - Transitions
- Svelte - Advance Reactivity
- Svelte - Reusing Content
- Svelte - Motion
- Svelte - Advanced Binding
- Svelte - Advanced Transitions
- Svelte - Context API
- Svelte - Special Elements
- SvelteKit Basics
- SvelteKit - Introduction
- SvelteKit - Routing
- SvelteKit - Loading Data
- SvelteKit - Headers
- SvelteKit - Cookies
- SvelteKit - Shared Modules
- SvelteKit - Forms
- SvelteKit - API Routes
- SvelteKit - States
- SvelteKit - Errors
- SvelteKit - Redirects
- SvelteKit Advanced
- SvelteKit - Hooks
- SvelteKit - Page Options
- SvelteKit - Link Options
- SvelteKit - Advanced Routing
- SvelteKit - Advanced Loading
- SvelteKit - Environment Variables
- Svelte Resources
- svelte - Useful Resources
- svelte - Discussion
Sveltekit - API Routes
API routes in SvelteKit allow developers to create server-side endpoints that can handle various HTTP methods, such as GET, POST, PUT, and DELETE. This functionality is essential for building dynamic applications that require data manipulation and retrieval.
GET Handlers
GET handlers are used to manage requests sent to specific parts of your application. When a client sends a GET request, the corresponding GET handler processes the request and returns a response, which usually includes some data.
Structure of a GET Handler
A basic structure of a GET handler in SvelteKit looks like this:
// src/routes/example/+server.js import { json } from '@sveltejs/kit'; export function GET() { const data = { message: "Hello, world!" }; return json(data); }
POST Handlers
POST handlers in SvelteKit are server-side functions that manage HTTP POST requests. They are important for processing data submissions, like form entries or API requests that create or update resources.
Structure of a Post Handler
You can specify a post handler in SvelteKit by following the steps mentioned below:
- Create the API Route: In your SvelteKit project, go to the src/routes/api folder and create a file called posts/+server.ts.
- Implement the POST Handler: In +server.ts, export a function that handles the POST request.
// src/routes/api/posts/+server.ts import type { RequestHandler } from '@sveltejs/kit'; export const POST: RequestHandler = async ({ request }) => { const data = await request.json(); // Parse JSON data from the request // Here you can process the data, e.g., save it to a database console.log(data); // Respond with a success message return new Response(JSON.stringify({ message: 'Post created successfully!' }), { status: 201, headers: { 'Content-Type': 'application/json' } }); };
async function createPost(postData) { const response = await fetch('/api/posts', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(postData) }); const result = await response.json(); console.log(result.message); // Handle success message }
Put Handler
A PUT handler in SvelteKit is a function that handles incoming PUT requests to update existing resources on the server. You use the PUT handler to change a resource at a specific URL, like /api/items/[id].
Structure of a Put Handler
You can create a simple put handler using the following example structure:
export async function PUT({ params, request, cookies }) { const { done } = await request.json(); const userid = cookies.get('userid'); await database.toggleTodo({ userid, id: params.id, done }); return new Response(null, { status: 204 }); }
Delete Handler
A DELETE handler in SvelteKit is a function that handles with incoming DELETE requests to remove specific resources from the server. Its purpose is to delete a resource at a specific URL, such as /api/items/[id].
Structure of a Delete Handler
You can create a simple delete handler using the following example structure:
export async function DELETE({ params, cookies }) { const userid = cookies.get('userid'); await database.deleteTodo({ userid, id: params.id }); return new Response(null, { status: 204 }); }
Example
The following is a simple example that demonstrates how to sveltekit get handler. In the example below, we created a demo database and fetched that data using Sveltekit get handlers.
<!--1. src/lib/db.js - Mock database--> export const users = [ { id: 1, name: 'John Doe', email: 'john@example.com' }, { id: 2, name: 'Jane Smith', email: 'jane@example.com' } ]; <!--2. src/routes/api/users/+server.js - GET all users--> import { json } from '@sveltejs/kit'; import { users } from '$lib/db'; export async function GET({ url }) { // Handle query parameters const search = url.searchParams.get('search'); if (search) { const filteredUsers = users.filter(user => user.name.toLowerCase().includes(search.toLowerCase()) ); return json(filteredUsers); } return json(users); } <!--3. src/routes/api/users/[id]/+server.js - GET single user--> import { json } from '@sveltejs/kit'; import { users } from '$lib/db'; export async function GET({ params }) { const id = parseInt(params.id); const user = users.find(u => u.id === id); if (!user) { return new Response(JSON.stringify({ error: 'User not found' }), { status: 404 }); } return json(user); } <!--. src/routes/users/+page.js - Load data for page--> export async function load({ fetch }) { const response = await fetch('/api/users'); const users = await response.json(); return { users }; } <!--5. src/routes/users/+page.svelte - Display users--> <script> export let data; let searchTerm = ''; let users = data.users; async function searchUsers() { const res = await fetch(`/api/users?search=${searchTerm}`); users = await res.json(); } </script> <div class="container"> <h1>Users List</h1> <div class="search"> <input type="text" bind:value={searchTerm} placeholder="Search users..." /> <button on:click={searchUsers}>Search</button> </div> <div class="users"> {#each users as user} <div class="user-card"> <h3>{user.name}</h3> <p>{user.email}</p> </div> {/each} </div> </div> <style> .container { max-width: 800px; margin: 0 auto; padding: 20px; } .search { margin: 20px 0; } .user-card { border: 1px solid #ddd; padding: 10px; margin: 10px 0; border-radius: 4px; } </style> <!--6. src/routes/+layout.svelte - Basic layout--> <nav> <a href="/">Home</a> <a href="/users">Users</a> </nav>
Output
