Overview
A useful API has consistent resource URLs, HTTP methods, response formats and error semantics. PHP can serve JSON APIs with a custom router or a framework; the important part is to define the contract and enforce it consistently.
Define the contract first
Document each endpoint's method, path, required parameters, response schema, authentication requirements and possible error responses. Use GET for retrieval, POST for creation or commands, PUT/PATCH for updates and DELETE for removal where those semantics fit.
Decode and validate JSON
Check the content type and body size. Decode with exceptions so malformed JSON is not confused with a valid null value:
<?php
try {
$payload = json_decode(
file_get_contents('php://input'),
true,
512,
JSON_THROW_ON_ERROR
);
} catch (JsonException $e) {
http_response_code(400);
echo json_encode(['error' => 'invalid_json']);
exit;
}
Then validate the expected fields and business rules. Never assume that a valid JSON document is valid application input.
Return consistent responses
Use appropriate status codes such as 200, 201, 204, 400, 401, 403, 404, 409, 422 and 500. Return a stable machine-readable error code and a safe message. Avoid exposing stack traces or SQL errors.
Security and operations
Authenticate callers, authorize each resource action, rate-limit sensitive endpoints and validate CORS policy. Use TLS. Avoid putting access tokens in URLs. Consider pagination, request IDs, timeouts and idempotency for operations that may be retried.
Official references
PHP JSON HTTP Semantics – RFC 9110
Define a consistent API contract
Choose resource-oriented paths, supported HTTP methods and stable response shapes. Use JSON request and response bodies with the correct content type. Validate every payload and return an appropriate status: 200 for successful reads or updates, 201 for creation, 204 for a successful response with no body, 400 for malformed input, 401 for missing authentication and 404 for missing resources.
Decode JSON safely
<?php
try {
$payload = json_decode(
file_get_contents('php://input'),
true,
512,
JSON_THROW_ON_ERROR
);
} catch (JsonException $e) {
http_response_code(400);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['error' => 'invalid_json']);
exit;
}
if (!is_array($payload) || !isset($payload['name']) || !is_string($payload['name'])) {
http_response_code(422);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['error' => 'validation_failed']);
exit;
}
A complete endpoint must also enforce body-size limits, authentication, authorization, rate limits and database constraints.
Design errors and pagination
Return machine-readable error codes and safe human-readable messages. Do not leak stack traces. For collections, define stable pagination and sorting; avoid unbounded result sets. Document whether pagination uses page numbers or cursors.
Version and secure the API
Avoid breaking clients silently. Version the API when a change is not backward compatible, document deprecation periods and test authorization for every resource identifier. CORS is not authentication; it controls browser access, not whether a caller is trusted.