Skip to main content

How to write API

General Guidelines​

Our API implementation follows the same patterns as in Next.js route handlers, with a few important additions:

API Handler Wrapping​

All API handlers must be wrapped with httpApiWrapper

Creating an API Endpoint​

API endpoints should be placed in the src/app/api/ directory, typically:

src/app/api/v1/user/route.ts

Basic API Structure​

export const GET = httpApiWrapper(async (req: Request) => {
const data = ...

if (!data) {
throw apiNotFoundError("Data not found");
}

return apiOkResponse(data);
});

Anonymous APIs​

By default, all APIs require authentication. To create an API endpoint that doesn't require authentication:

export const publicApi = httpApiWrapper(
async () => {
...
},
{ anonymous: true },
);

Client-Side Usage​

To call your APIs from client components, use the standard API client functions:

// GET request
const data = await apiGet<ResponseType>("endpoint", id);

// POST request
const result = await apiPost<ResponseType, RequestType>("endpoint", requestData);

// PUT request
const updated = await apiPut<ResponseType, RequestType>("endpoint", updateData);

// DELETE request
await apiDelete("endpoint", id);

Response Format​

Responses should only be returned using standard response functions

Available functions for creating API responses:

Error Handling​

Errors should be thrown using error functions

Available functions for creating API errors: