API Routes

Creating API endpoints in @constela/start

Create API endpoints by creating TypeScript files with HTTP method handlers.

Basic API Route

typescript
// src/routes/api/users.ts
import type { APIContext } from '@constela/start';

export async function GET({ params, query }: APIContext) {
  const users = await db.users.findMany();
  return Response.json({ users });
}

export async function POST({ request }: APIContext) {
  const body = await request.json();
  const user = await db.users.create(body);
  return Response.json({ created: user }, { status: 201 });
}

export async function PUT({ request, params }: APIContext) {
  const body = await request.json();
  const user = await db.users.update(params.id, body);
  return Response.json({ updated: user });
}

export async function DELETE({ params }: APIContext) {
  await db.users.delete(params.id);
  return new Response(null, { status: 204 });
}

APIContext

The APIContext object provides access to request information:

PropertyTypeDescription
requestRequestThe incoming request object
paramsRecord<string, string>Route parameters
queryURLSearchParamsQuery string parameters
envobjectEnvironment bindings (for edge runtimes)

Dynamic API Routes

Use square brackets for dynamic API endpoints:

text
src/routes/api/users/[id].ts → /api/users/:id
typescript
// src/routes/api/users/[id].ts
import type { APIContext } from '@constela/start';

export async function GET({ params }: APIContext) {
  const user = await db.users.findById(params.id);
  if (!user) {
    return new Response('Not found', { status: 404 });
  }
  return Response.json(user);
}

Response Helpers

Return standard Response objects:

typescript
// JSON response
return Response.json({ data: 'value' });

// JSON with status
return Response.json({ error: 'Not found' }, { status: 404 });

// Plain text
return new Response('Hello, world!');

// No content
return new Response(null, { status: 204 });

// Redirect
return Response.redirect('/new-url', 302);

File Structure

text
src/routes/
├── api/
│   ├── users.ts          # /api/users (GET, POST)
│   ├── users/
│   │   └── [id].ts       # /api/users/:id (GET, PUT, DELETE)
│   └── health.ts         # /api/health
└── index.json            # / (page)