API Developmentbeginner
Standardize API response format
API Response Formatter
Standardize API response format
Standardize API response format across all endpoints.
Instructions
Create a response helper:
// lib/api-response.ts
interface ApiResponse<T> {
data: T;
meta?: {
page?: number;
limit?: number;
total?: number;
totalPages?: number;
};
}
interface ApiError {
error: {
code: string;
message: string;
details?: unknown;
};
}
export function success<T>(data: T, status = 200): Response {
return Response.json({ data }, { status });
}
export function created<T>(data: T): Response {
return Response.json({ data }, { status: 201 });
}
export function paginated<T>(data: T[], total: number, page: number, limit: number): Response {
return Response.json({
data,
meta: { page, limit, total, totalPages: Math.ceil(total / limit) },
});
}
export function error(code: string, message: string, status: number, details?: unknown): Response {
return Response.json({ error: { code, message, details } }, { status });
}
export function noContent(): Response {
return new Response(null, { status: 204 });
}
Usage:
export async function GET() {
const users = await getUsers();
return success(users); // { data: [...] }
}
export async function DELETE() {
await deleteUser(id);
return noContent(); // 204 no body
}