📖 Scenario: You are building a simple Svelte app to manage a list of books. You want to practice handling data operations like fetching the list, adding a new book, updating a book, and deleting a book using Svelte's reactive features and fetch API.
🎯 Goal: Create a Svelte component that handles GET, POST, PUT, and DELETE requests to manage a list of books. You will set up the initial data, configure the API endpoint, implement the core logic for each HTTP method, and complete the component with buttons to trigger these actions.
📋 What You'll Learn
Create a reactive variable books initialized as an empty array
Create a constant apiUrl with the value "/api/books"
Write async functions getBooks(), addBook(), updateBook(), and deleteBook() that use fetch with the correct HTTP methods
Add buttons in the Svelte component to call each function and update the books list accordingly
💡 Why This Matters
🌍 Real World
Managing data with GET, POST, PUT, DELETE requests is common in web apps for CRUD operations like managing books, users, or products.
💼 Career
Understanding how to handle HTTP methods in frontend frameworks like Svelte is essential for building interactive, data-driven applications in real jobs.
Progress0 / 4 steps
1
Setup initial data variable
Create a reactive variable called books and initialize it as an empty array [].
Svelte
Hint
Use let books = []; inside the <script> tag to create a reactive variable.
2
Add API URL configuration
Add a constant called apiUrl and set it to the string "/api/books" inside the <script> tag below the books variable.
Svelte
Hint
Use const apiUrl = "/api/books"; to store the API endpoint.
3
Implement GET, POST, PUT, DELETE functions
Inside the <script> tag, write four async functions: getBooks(), addBook(), updateBook(), and deleteBook(). Use fetch with the correct HTTP methods: GET for getBooks(), POST for addBook(), PUT for updateBook(), and DELETE for deleteBook(). Update the books variable with the fetched or updated data accordingly. For addBook() and updateBook(), send a JSON body with a book object having id and title. For deleteBook(), send the book id in the URL.
Svelte
Hint
Use fetch with the correct method option and update books with the JSON response.
4
Add buttons to trigger HTTP methods
In the Svelte component, below the <script> tag, add four buttons with the text Get Books, Add Book, Update Book, and Delete Book. Attach on:click event handlers to call the respective functions getBooks(), addBook(), updateBook(), and deleteBook(). Also, display the list of book titles in an unordered list <ul> with each book in a <li>.
Svelte
Hint
Add buttons with on:click handlers and use {#each} block to list book titles.
Practice
(1/5)
1. In SvelteKit, what is the main purpose of a GET handler in a route's +server.js file?
easy
A. To update existing data on the server
B. To delete data from the server
C. To fetch and return data when the route is requested
D. To send data to the server without expecting a response
Solution
Step 1: Understand the role of HTTP methods
GET requests are used to retrieve data from a server without changing it.
Step 2: Apply this to SvelteKit handlers
The GET handler in +server.js responds to GET requests by returning data to the client.
Final Answer:
To fetch and return data when the route is requested -> Option C
Quick Check:
GET handler fetches data = B [OK]
Hint: GET handlers always return data for reading [OK]
Common Mistakes:
Confusing GET with POST or PUT for data updates
Thinking GET modifies server data
Assuming GET sends data without response
2. Which of the following is the correct syntax to define a POST handler in SvelteKit's +server.js file?
easy
A. export async function POST({ request }) { return new Response('ok'); }
B. export async function post(request) { return new Response('ok'); }
Handlers must be exported async functions named in uppercase: GET, POST, PUT, DELETE.
Step 2: Check parameter and return type
The function receives an object with a request property and returns a Response object.
Final Answer:
export async function POST({ request }) { return new Response('ok'); } -> Option A
Quick Check:
Correct handler syntax = A [OK]
Hint: Use uppercase method names and destructured params [OK]
Common Mistakes:
Using lowercase function names like 'post'
Not exporting the function
Returning plain strings instead of Response objects
3. Given this SvelteKit PUT handler in +server.js:
export async function PUT({ request }) {
const data = await request.json();
return new Response(JSON.stringify({ updated: data.id }), { status: 200 });
}
What will be the response body if the client sends {"id": 42} in the request body?
medium
A. undefined
B. {"id":42}
C. 42
D. {"updated":42}
Solution
Step 1: Parse JSON from request
The handler reads JSON from the request body, so data = { id: 42 }.
Step 2: Return JSON with updated id
The response body is JSON stringified object with key 'updated' and value data.id (42).
Final Answer:
{"updated":42} -> Option D
Quick Check:
Response JSON includes updated id = D [OK]
Hint: PUT returns updated data wrapped in JSON [OK]
Common Mistakes:
Returning original data instead of updated key
Not stringifying JSON response
Confusing response body with request body
4. Identify the error in this DELETE handler code snippet:
export async function DELETE(request) {
const id = await request.json().id;
return new Response(`Deleted ${id}`, { status: 200 });
}
medium
A. The function parameter should be destructured to get request
B. Cannot await request.json().id directly; must await request.json() first
C. DELETE handlers cannot return Response objects
D. Missing export keyword before function
Solution
Step 1: Analyze request.json() usage
request.json() returns a Promise for the parsed body; you must await it fully before accessing properties.
Step 2: Identify incorrect await usage
Code tries to await request.json().id directly, which is invalid; must await request.json() first, then access .id.
Final Answer:
Cannot await request.json().id directly; must await request.json() first -> Option B
Quick Check:
Await full JSON before property access = C [OK]
Hint: Await request.json() fully before accessing properties [OK]
Common Mistakes:
Trying to await a property of a Promise
Not destructuring the parameter (optional but recommended)
Thinking DELETE handlers can't return Response
5. You want to create a SvelteKit API route that updates a user's name using a PUT handler and returns the updated user object. Which code snippet correctly implements this behavior?
hard
A. export async function PUT({ request }) {
const user = await request.json();
user.name = user.name.toUpperCase();
return new Response(JSON.stringify(user), { status: 200 });
}
B. export async function PUT(request) {
const user = await request.json();
user.name = user.name.toUpperCase();
return user;
}
C. export async function put({ request }) {
const user = await request.json();
user.name = user.name.toUpperCase();
return new Response(JSON.stringify(user));
}
D. export async function PUT({ request }) {
const user = request.json();
user.name = user.name.toUpperCase();
return new Response(JSON.stringify(user), { status: 200 });
}
Solution
Step 1: Confirm correct function signature and export
The handler must be exported async function named PUT with destructured { request } parameter.
Step 2: Await request.json() and modify data
Await the JSON body, then update the user.name property correctly.
Step 3: Return a Response with JSON string and status
Return new Response with JSON stringified user and status 200.
Final Answer:
export async function PUT({ request }) {
const user = await request.json();
user.name = user.name.toUpperCase();
return new Response(JSON.stringify(user), { status: 200 });
} -> Option A
Quick Check:
Proper async PUT handler with Response = A [OK]
Hint: Use uppercase function name, await JSON, return Response [OK]
Common Mistakes:
Not awaiting request.json()
Using lowercase function name 'put'
Returning raw object instead of Response
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.