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:
- getJsonResponse - General JSON response with custom status code
- apiOkResponse - 200 OK with data
- apiCreatedResponse - 201 Created with data
- apiNoContentResponse - 204 No Content (without data)
- apiBadRequestResponse - 400 Bad Request with data
- apiInternalServerErrorResponse - 500 Internal Server Error
- apiNotFoundResponse - 404 Not Found with data
- apiResponse - General response with options
Error Handling
Errors should be thrown using error functions
Available functions for creating API errors:
- createApiError - Error with custom status code
- apiBadRequestError - 400 Bad Request
- apiUnauthorizedError - 401 Unauthorized
- apiForbiddenError - 403 Forbidden
- apiNotFoundError - 404 Not Found
- apiMethodNotAllowedError - 405 Method Not Allowed
- apiConflictError - 409 Conflict
- apiTooManyRequestsError - 429 Too Many Requests
- apiInternalServerError - 500 Internal Server Error