PHP APIs

Building a Simple JSON API with PHP

Create a small PHP JSON endpoint, validate request data, return consistent responses, and use appropriate HTTP status codes.

Building a Simple JSON API with PHP

A JSON API allows applications to exchange structured data over HTTP. PHP can create API endpoints by reading requests, validating input, and returning JSON responses with suitable status codes.

Send a JSON Response

Set the response content type and encode the response data.

header("Content-Type: application/json; charset=utf-8");

echo json_encode(
    ["message" => "API is ready"],
    JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR
);

In a larger application, centralize response formatting so endpoints use a consistent structure.

Read a JSON Request

For a JSON request body, read php://input and decode it.

$rawBody = file_get_contents("php://input");

try {
    $data = json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $exception) {
    http_response_code(400);
    echo json_encode(["error" => "Invalid JSON"]);
    exit;
}

After decoding, validate that required fields exist and have the expected types and formats. Never assume client-supplied data is trustworthy.

Use HTTP Status Codes

Common response codes include 200 for a successful request, 201 for a created resource, 400 for invalid input, 401 for missing or invalid authentication, 403 for insufficient permission, 404 for a missing resource, and 500 for an unexpected server error.

Do not return stack traces or database credentials to API clients.

API Security

Use HTTPS, authenticate protected endpoints, authorize every operation, validate input, and apply rate limits where appropriate. Use prepared statements for database access and avoid exposing internal implementation details.

Conclusion

A useful PHP JSON API has predictable response formats, correct HTTP status codes, clear validation, and appropriate security controls. Start with small endpoints and introduce routing and shared middleware as the API grows.

Share this page Help other developers discover this resource.