| | |

SvelteKit 08 🧡 API Endpoints — Building RESTful GET, POST, PUT, and DELETE Request Handlers

⏱️ Estimated read: 8 min | |

SvelteKit is not just a framework for building frontend applications; it is a full-stack engine capable of providing robust, performant API endpoints through +server.ts files. While Form Actions and load functions handle the needs of Svelte components, API endpoints allow you to build public-facing services, internal microservices, and webhook listeners that return JSON, binary data, or long-lived streams. By leveraging native web standard Request and Response objects, SvelteKit endpoints operate with high performance and minimal abstraction.

This chapter explores how to define RESTful endpoints, implement standard HTTP verbs, and handle dynamic URL parameters. We will cover how to use the built-in json helper to simplify data serialization, how to manage error states with appropriate status codes, and how to utilize ReadableStream to handle large payloads or real-time data streaming.

Key point: SvelteKit API endpoints, defined in +server.ts files, provide a standard, high-performance way to handle arbitrary HTTP requests; by using native Request and Response objects, they offer total control over headers, status codes, and data streaming in a way that is isomorphic and fully integrated with your server environment.


Why exists

The decoupled architecture need. Many applications require a clear separation between the UI and the data layer. API endpoints allow mobile apps, external clients, or third-party webhooks to interact with your business logic without depending on the Svelte application’s rendering cycle.

The binary/file manipulation problem. While load functions are optimized for page data, they are not designed for direct file serving or image processing. API endpoints allow you to manipulate streams, proxy files from private buckets, and perform dynamic binary operations with ease.

The webhook listener requirement. External services like Stripe or GitHub require an entry point to send event data. +server.ts files act as traditional controller endpoints, providing the flexibility needed to verify signatures, parse raw bodies, and return custom acknowledgment codes.

The legacy integration challenge. Often, a project must interact with legacy systems or non-Svelte internal services. API endpoints provide a clean, URL-based interface to perform CRUD operations that are consistent with industry standards, regardless of the consumer.

The high-performance streaming necessity. When generating large CSVs, reports, or real-time event logs, buffering the entire result into memory is a recipe for server crashes. API endpoints allow you to stream data chunk by chunk, drastically reducing memory overhead and improving perceived performance.


a. Basic structure and the Response object

Every +server.ts file acts as an endpoint. Instead of load functions, you export functions named after HTTP verbs: GET, POST, PUT, PATCH, DELETE, and OPTIONS. Each function receives a RequestEvent object and must return a Response object.

// src/routes/api/hello/+server.ts
import { json } from '@sveltejs/kit';

export async function GET() {
  return json({ message: 'Hello, World!' });
}

The json helper is a convenience utility that sets the Content-Type: application/json header automatically. If you need to perform custom logic, such as setting specific cache headers or cookies, you can construct the Response object manually: return new Response(JSON.stringify(data), { status: 200, headers: { 'Content-Type': 'application/json' } });.


b. Implementing RESTful verbs and parameters

SvelteKit handles dynamic routing for APIs exactly like it does for pages. You use the [id] folder structure, and SvelteKit provides the dynamic parameter to your function via the params object. This enables you to build standard RESTful patterns for resource management.

// src/routes/api/users/[id]/+server.ts
export async function PUT({ params, request }) {
  const body = await request.json();
  const userId = params.id;
  await updateDatabase(userId, body);
  return new Response(null, { status: 204 }); // 204 No Content
}

By mapping the HTTP methods correctly, you ensure your API follows conventional REST standards. GET is for retrieval, POST for creation, PUT for full updates, PATCH for partial updates, and DELETE for removal. Using the appropriate status codes—like 201 Created for successful posts or 404 Not Found for missing resources—is essential for client-side interoperability.


c. Streaming and advanced data handling

Streaming is one of the most powerful features of +server.ts. If you return a ReadableStream in the Response constructor, SvelteKit will stream the response body to the client. This is essential for long-running processes or data-heavy requests that shouldn’t wait for total completion before delivering the first byte.

// src/routes/api/stream/+server.ts
export async function GET() {
  const stream = new ReadableStream({
    start(controller) {
      controller.enqueue('Data chunk 1\n');
      controller.enqueue('Data chunk 2\n');
      controller.close();
    }
  });

  return new Response(stream, {
    headers: { 'Content-Type': 'text/plain' }
  });
}

Beyond text, you can stream binary data or proxy requests. Because +server.ts is just a standard handler, you have full access to request.headers, request.body, and request.formData(), allowing you to build complex proxy services or middleware layers right within your project.


Complete Example Session

// ============================================
// PART 1: GET REQUEST
// ============================================
import { json } from '@sveltejs/kit';
export const GET = () => json({ items: [1, 2, 3] });

// ============================================
// PART 2: POST WITH BODY PARSING
// ============================================
export const POST = async ({ request }) => {
  const data = await request.json();
  return json({ id: 1 }, { status: 201 });
};

// ============================================
// PART 3: DYNAMIC PARAMS
// ============================================
export const DELETE = ({ params }) => {
  console.log(`Deleting item ${params.id}`);
  return new Response(null, { status: 204 });
};

// ============================================
// PART 4: ERROR HANDLING
// ============================================
import { error } from '@sveltejs/kit';
export const PATCH = () => {
  throw error(405, 'Method not allowed');
};

// ============================================
// PART 5: STREAMING
// ============================================
export const GET = () => new Response(myReadableStream);

// ============================================
// PART 6: HEADERS CONTROL
// ============================================
export const GET = () => json({ ok: true }, { headers: { 'Cache-Control': 'max-age=60' } });

// ============================================
// PART 7: AUTHENTICATION CHECK
// ============================================
export const POST = ({ locals }) => {
  if (!locals.user) throw error(401, 'Unauthorized');
  return json({ secret: 'data' });
};

// ============================================
// PART 8: BINARY DATA
// ============================================
export const GET = async () => {
  const buffer = await fs.readFile('image.png');
  return new Response(buffer, { headers: { 'Content-Type': 'image/png' } });
};

// ============================================
// PART 9: CORS (CORS CONFIG)
// ============================================
export const OPTIONS = () => new Response(null, { headers: { 'Access-Control-Allow-Origin': '*' } });

// ============================================
// PART 10: FORM DATA HANDLING
// ============================================
export const POST = async ({ request }) => {
  const data = await request.formData();
  return json({ received: data.get('field') });
};

This sequence covers the full spectrum from simple JSON retrieval to authenticated actions, binary handling, and complex response configuration.


Quick Reference

HTTP Method Mapping

MethodRoleStatus Code
GETRetrieve resource200
POSTCreate resource201
PUTReplace resource200 / 204
PATCHPartial update200 / 204
DELETEDelete resource204

Response Helpers

HelperPurpose
json()Serialize objects, set JSON header
error()Throw clean HTTP error responses
ResponseNative object for raw control
paramsExtract dynamic URL parts

Best Practices

✅ Do This:

// Use the json helper for objects
return json({ success: true });                              // ✅

// Always return correct status codes
return new Response(null, { status: 204 });                 // ✅

// Extract params for dynamic resources
export const GET = ({ params }) => { /* ... */ };           // ✅

// Use locals for authentication
export const POST = ({ locals }) => { /* ... */ };          // ✅

❌ Don’t Do This:

// Don't manually stringify if using json()
return new Response(JSON.stringify(data));                  // ❌

// Don't return 200 for missing content
return json({ error: 'Not found' }, { status: 200 });       // ❌

// Don't block the loop with massive buffers
return new Response(massiveBuffer); // Stream instead      // ❌

// Don't log sensitive request headers
console.log(request.headers);                               // ❌

Common Pitfalls

PitfallWhy It HappensFix
Mismatched methodWrong function nameUse GET, POST, etc.
Memory bloatLoading files into memoryUse ReadableStream
CORS errorsMissing OPTIONS handlerHandle preflight requests
Silent failureNot throwing error()Use error(code, msg)

Real-World Examples

1. Public JSON API

export const GET = () => json(data);

2. Item creation

export const POST = async ({ request }) => { /* save */ }

3. Dynamic lookup

export const GET = ({ params }) => { /* find(params.id) */ }

4. Protected webhook

export const POST = ({ locals }) => { /* verify */ }

5. Image serving

return new Response(fileBuffer, { headers: {'Content-Type': 'image/jpeg'} });

6. CORS preflight

export const OPTIONS = () => new Response(null, { headers: { 'Access-Control-Allow-Methods': 'GET' } });

7. Streaming log

return new Response(logStream);

8. Form data consumption

const data = await request.formData();

9. Method not allowed

throw error(405);

10. Cache control

return json(data, { headers: { 'Cache-Control': 'public, max-age=3600' } });

Visual

Request/Response Lifecycle

┌──────────────────────────────────────────────┐
│  CLIENT                                      │
│  Request (GET /api/user/1)                   │
│      │                                       │
│      ▼                                       │
│  SERVER (+server.ts)                         │
│  1. Match Function (GET)                     │
│  2. Execute Logic                            │
│  3. Return Response Object                   │
│      │                                       │
│      ▼                                       │
│  CLIENT                                      │
│  Response (Status 200, JSON)                 │
└──────────────────────────────────────────────┘

Streaming Architecture

┌──────────────────────────────────────────────┐
│  SERVER                                      │
│  ┌────────────────────┐                      │
│  │ ReadableStream     │                      │
│  │ ├─ chunk 1         │                      │
│  │ ├─ chunk 2         │──► HTTP Connection   │
│  │ └─ close()         │                      │
│  └────────────────────┘                      │
└──────────────────────────────────────────────┘

REST Method Mapping

┌──────────────────────────────────────────────┐
│  RESOURCE: /api/posts/[id]                   │
│  GET    ──► Read  (fetch post)               │
│  POST   ──► Create (new post)                │
│  PUT    ──► Replace (full update)            │
│  DELETE ──► Remove (delete post)             │
└──────────────────────────────────────────────┘

Summary

ItemValue
Route file+server.ts
ExportHTTP Verb (GET, POST, etc)
Serializationjson() helper
Error handlingerror(status, message)
StreamingReadableStream
Dynamic routeparams.id

Key takeaways:

  • Use +server.ts for machine-to-machine interfaces. This is the correct tool when you need to serve data to external consumers rather than rendering UI.
  • Leverage native web standards. By using Request and Response, your SvelteKit API code remains highly portable and standard-compliant.
  • Implement REST correctly. Use the right HTTP methods and status codes to ensure that your API is predictable and easy to integrate with.
  • Stream for performance. When handling high-volume data, always prefer ReadableStream over buffering large objects into memory.
  • Namespace your APIs. Organizing your endpoints under src/routes/api/... is a common convention to separate server logic from UI routes.

Remember: API endpoints are the backbone of your application’s data layer. Whether you are building a full REST API for mobile clients, creating a webhook listener, or serving raw binary data, +server.ts gives you the surgical control required. By adhering to REST principles, managing errors properly, and streaming large payloads, you ensure that your SvelteKit application is not just a framework for the web, but a powerful platform for modern service-oriented architecture.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!