An API is used by people you may never meet, in code you will never see. They cannot ask what you meant. All they have is the behaviour of the endpoints, and whatever they learn from the first one they will assume about the rest.
That is why consistency matters more than cleverness. A plain API that behaves the same way everywhere is easier to build on than an elegant one full of exceptions. These are the decisions that produce the first kind.
Decide the response shape before the first endpoint
The most valuable hour in an API project is the one spent writing down what a response looks like — before any endpoint exists. Mine is an envelope with three fields:
{
"success": true,
"data": { "id": 42, "title": "Quarterly report" },
"message": null
}
A failure uses the same envelope, with the reason:
{
"success": false,
"data": null,
"message": "Validation failed",
"errors": {
"email": ["The email field must be a valid email address."]
}
}
The client now needs exactly one function to read every response, and one place to handle every error. Whether you use an envelope or return bare resources is a matter of taste; that every endpoint does the same thing is not.
In Laravel this takes one base method and one exception handler:
abstract class ApiController extends Controller
{
protected function success(mixed $data = null, ?string $message = null, int $status = 200): JsonResponse
{
return response()->json(['success' => true, 'data' => $data, 'message' => $message], $status);
}
}
$exceptions->render(function (Throwable $e, Request $request) {
if (! $request->is('api/*')) {
return null;
}
$envelope = fn (string $message, int $status, ?array $errors = null) => response()->json(
['success' => false, 'data' => null, 'message' => $message] + ($errors === null ? [] : ['errors' => $errors]),
$status
);
return match (true) {
$e instanceof ValidationException => $envelope('Validation failed', 422, $e->errors()),
$e instanceof ModelNotFoundException => $envelope('Resource not found', 404),
$e instanceof AuthenticationException => $envelope('Unauthenticated', 401),
default => $envelope(config('app.debug') ? $e->getMessage() : 'Server error', 500),
};
});
With the handler in place, no controller ever formats an error. A missing record anywhere in the application becomes the same 404 body.
Use status codes for what they mean
The envelope does not replace HTTP status codes. Clients, proxies and monitoring tools all read the status line first.
| Code | Use it when |
|---|---|
| 200 | The request succeeded and there is something to return |
| 201 | A resource was created |
| 204 | It succeeded and there is nothing to say |
| 401 | The caller is not authenticated |
| 403 | The caller is authenticated but not allowed |
| 404 | The resource does not exist — or the caller may not know that it does |
| 409 | The request conflicts with the current state |
| 422 | The input failed validation |
| 429 | Too many requests |
Returning 200 with "success": false inside is the classic mistake. It makes every failure invisible to anything that is not parsing the body.
Name resources, not actions
URLs identify things; HTTP methods say what to do with them.
GET /api/v1/projects list
POST /api/v1/projects create
GET /api/v1/projects/{slug} read one
PATCH /api/v1/projects/{slug} change part of one
DELETE /api/v1/projects/{slug} remove one
Use plural nouns, lower-case, with hyphens. When an operation genuinely is an action — publishing, cancelling, retrying — model it as a sub-resource: POST /orders/{id}/cancellation reads oddly at first, but it keeps the whole surface predictable.
Version from the first day
/api/v1/ costs nothing when the API is new. Adding it after clients exist means breaking them or maintaining two sets of routes forever.
A version is a promise about what will not change. Within v1 you may add fields and endpoints; you may not remove a field, rename one, or change what a value means. When that becomes necessary, v2 appears alongside and v1 keeps working until its clients have moved.
Validate everything, and say what was wrong
Every field that enters the system is checked, and the response tells the client which fields failed and why — keyed by field name, so a form can show each message next to its input.
Be strict about types. "quantity": "3" and "quantity": 3 are different things, and accepting both today means supporting both forever. And validate options against the server's own list rather than a hard-coded one:
'project_type' => ['required', Rule::in($settings->lines('hire_project_types'))],
The allowed values come from the same place the client reads them, so the two can never disagree.
Paginate every list
A list endpoint without a limit works with ten rows and fails with ten thousand. Paginate from the start, and return the metadata a client needs to draw its controls:
{
"success": true,
"data": {
"items": [],
"meta": { "total": 124, "page": 2, "per_page": 9, "last_page": 14 }
},
"message": null
}
Cap per_page on the server. A client that asks for a million rows should get your maximum, not an out-of-memory error.
Make unsafe requests safe to repeat
Networks drop responses. A client that sent a payment request and heard nothing back has to choose between retrying — and perhaps paying twice — or giving up on a payment that may have gone through.
An idempotency key removes the dilemma. The client generates a unique key for the operation and sends it with every attempt; the server stores the key with the result, and answers a repeated key with the stored result instead of doing the work again.
POST /api/v1/orders
Idempotency-Key: 5f0c2f1e-8a53-4c1b-9d0a-6f6d7a2b9c11
Anything that creates money, stock or messages deserves this.
Protect the API from its callers
- Authenticate with tokens that can be revoked individually, and give each token only the abilities it needs.
- Rate-limit by caller, with a stricter limit on the expensive endpoints — sign-in, search, anything that sends email.
- Never expose internals. A stack trace in a production response is documentation for an attacker. Log the detail; return
Server error. - Return only what is public. A draft post should be a 404 to the public API, not a record with
"status": "draft".
Document as you build
Documentation written at the end describes what the author remembers. Written alongside the code, it describes what the code does.
It does not have to be elaborate. For each endpoint: the method and path, the parameters with their types, an example response, and the errors it can return. If writing that table feels awkward for some endpoint, the endpoint is probably the awkward part.
The test of a good API
Hand someone the documentation for one endpoint and ask them to guess how another one behaves — its URL, its response, what happens when they send bad input. If they guess right, the API is consistent, and consistent is what makes it trustworthy.
