Error Handling in a PHP API: Consistent JSON Responses for 400, 401, 403, 404 and 500

Illustration of error handling in a plain PHP API with consistent JSON responses and HTTP status codes

Quick answer: Give every error from your PHP API the same JSON shape (for example success, message and errors), always with the right HTTP status: 400 for a malformed request, 401 when not authenticated, 403 when not allowed, 404 when the resource doesn't exist, 422 for invalid fields and 500 for internal failures. Catch exceptions with try/catch, log the details and never show internal messages to the client.

Handling errors properly is what makes an API professional, safe and easy to consume. When an API returns messy errors, HTML, a blank page or the wrong status code, the frontend, the mobile app or the integrated system can't tell what happened.

In a plain PHP API it is common to start with simple echo messages. As the project grows, you need consistent responses that separate validation, authentication, permission, missing routes and internal server failures.

In this article you will build error handling for a PHP API with consistent JSON responses for the main status codes: 400, 401, 403, 404, 422 and 500.

In short: a professional API always returns JSON, uses the correct HTTP status and hides server internals when something unexpected happens.

Why standardize errors in a PHP API?

An API can be called by many clients: a website, an admin panel, an Android app, a partner integration or another server. They all need responses they can predict. When each endpoint reports errors differently, every client needs special cases, and maintenance gets harder.

Common problems in APIs without consistent error handling:

  • Returning HTML when the client expects JSON;
  • Returning 200 OK even when something failed;
  • Showing the real database error to the user;
  • Different messages for the same kind of error;
  • No distinction between validation, authentication and permission errors;
  • A blank page on fatal errors;
  • Errors that are hard to debug in production.

A good JSON error format

{
  "success": false,
  "message": "Main error message.",
  "errors": {
    "field": "Details about this field"
  }
}

For simpler errors, errors can be left out:

{
  "success": false,
  "message": "Resource not found."
}

What matters is using the same shape across the whole API.

Response helpers

<?php

function jsonResponse(int $statusCode, array $data): void
{
    http_response_code($statusCode);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

function errorResponse(int $statusCode, string $message, array $errors = []): void
{
    $response = ['success' => false, 'message' => $message];

    if (!empty($errors)) {
        $response['errors'] = $errors;
    }

    jsonResponse($statusCode, $response);
}

Usage:

<?php

errorResponse(404, 'User not found.');

errorResponse(422, 'Some fields are invalid.', [
    'email' => 'Enter a valid email address.',
    'password' => 'Password must be at least 8 characters long.'
]);

The HTTP status codes a PHP API uses most

StatusNameWhen to use it
200OKThe request succeeded.
201CreatedA new record was created.
400Bad RequestThe request is malformed, such as invalid JSON.
401UnauthorizedNo token was sent, or authentication failed.
403ForbiddenThe user is authenticated but not allowed.
404Not FoundThe route or resource doesn't exist.
422Unprocessable ContentThe JSON is valid but the data fails validation.
500Internal Server ErrorSomething unexpected failed on the server.

400: malformed request

Use 400 Bad Request when the API can't even read the request, for example when the body is not valid JSON:

<?php

$data = json_decode(file_get_contents('php://input'), true);

if (json_last_error() !== JSON_ERROR_NONE) {
    errorResponse(400, 'Invalid JSON.', [
        'json' => 'The request body is not valid JSON.'
    ]);
}

401: not authenticated

Use 401 Unauthorized when a route requires authentication and no valid token was sent, for example when the Authorization: Bearer TOKEN header is missing:

<?php

$authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '';

if ($authorization === '') {
    header('WWW-Authenticate: Bearer');
    errorResponse(401, 'Authentication token is missing.');
}

if (!str_starts_with($authorization, 'Bearer ')) {
    header('WWW-Authenticate: Bearer');
    errorResponse(401, 'Invalid token format.');
}
Tip: use 401 when the problem is authentication. If the user is authenticated but not allowed, use 403. For validating the token itself, see JWT authentication in PHP.

403: not allowed

Use 403 Forbidden when the user is authenticated but has no permission, such as a regular user calling an admin route:

<?php

// $user comes from the validated token
if ($user['role'] !== 'admin') {
    errorResponse(403, 'You are not allowed to access this resource.');
}

This tells the client that the user is logged in but can't perform that action, so it shouldn't send them back to the login screen.

404: route or resource not found

Use 404 Not Found in two situations: when the route doesn't exist, and when the requested record isn't in the database.

<?php

$stmt = $pdo->prepare('SELECT id, name, email FROM users WHERE id = :id');
$stmt->execute([':id' => $id]);
$user = $stmt->fetch();

if (!$user) {
    errorResponse(404, 'User not found.');
}

Your router should also end with a 404 when no route matches (and a 405 when the path exists but not for that HTTP method). See how to create a REST API in plain PHP.

422: invalid fields

422 Unprocessable Content means the API understood the request, but the data breaks its rules:

<?php

$errors = [];

if (!is_string($data['name'] ?? null) || trim($data['name']) === '') {
    $errors['name'] = 'Name is required.';
}

if (!is_string($data['email'] ?? null) || trim($data['email']) === '') {
    $errors['email'] = 'Email is required.';
} elseif (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
    $errors['email'] = 'Enter a valid email address.';
}

if ($errors) {
    errorResponse(422, 'Some fields are invalid.', $errors);
}

This format works well for forms: the client can show each message under the matching field. More in input validation in a plain PHP API.

500: internal server failure

Use 500 Internal Server Error for unexpected failures: a database error, an uncaught exception, a missing file, a lost connection. In production, never return the real error message. Log it and return a generic one:

<?php

try {
    $stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
    $stmt->execute([':id' => $id]);
    $user = $stmt->fetch();
} catch (PDOException $e) {
    error_log('Database error: ' . $e->getMessage());
    errorResponse(500, 'Internal server error.');
}
Watch out: table names, database users, file paths and SQL details must never appear in the public response.

A custom ApiException

In larger projects, a custom exception lets you throw an error with its HTTP status and field errors from anywhere, and handle them all in one place:

<?php

class ApiException extends Exception
{
    public function __construct(
        string $message,
        private int $statusCode = 500,
        private array $errors = []
    ) {
        parent::__construct($message);
    }

    public function getStatusCode(): int
    {
        return $this->statusCode;
    }

    public function getErrors(): array
    {
        return $this->errors;
    }
}

Global handlers for uncaught errors

Global handlers make sure that even an error nobody caught still returns JSON instead of HTML or a blank page. The error handler turns PHP warnings into exceptions, so they reach the same place:

<?php

const APP_DEBUG = false; // true only in development

set_error_handler(function (int $severity, string $message, string $file, int $line): bool {
    if (!(error_reporting() & $severity)) {
        return false;
    }
    throw new ErrorException($message, 0, $severity, $file, $line);
});

set_exception_handler(function (Throwable $e) {
    if ($e instanceof ApiException) {
        errorResponse($e->getStatusCode(), $e->getMessage(), $e->getErrors());
    }

    error_log('Uncaught ' . get_class($e) . ': ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());

    $response = ['success' => false, 'message' => 'Internal server error.'];

    if (APP_DEBUG) {
        $response['debug'] = [
            'message' => $e->getMessage(),
            'file' => $e->getFile(),
            'line' => $e->getLine()
        ];
    }

    jsonResponse(500, $response);
});

Keep APP_DEBUG set to false in production. Fatal errors such as memory exhaustion don't reach these handlers, which is why the server log still matters; see how to find the cause of a PHP 500 error.

Suggested structure

/api
  /core
    response.php        (jsonResponse, errorResponse)
    ApiException.php
    error-handler.php   (set_error_handler, set_exception_handler)
  /controllers
    UserController.php
  /middlewares
    AuthMiddleware.php
  index.php

Complete endpoint with error handling

With the handlers in place, the endpoint only throws; it doesn't need to repeat try/catch for every case:

<?php

require_once __DIR__ . '/core/response.php';
require_once __DIR__ . '/core/ApiException.php';
require_once __DIR__ . '/core/error-handler.php';

$id = $_GET['id'] ?? null;

if ($id === null || $id === '') {
    throw new ApiException('Missing ID.', 400, ['id' => 'Send the user ID.']);
}

if (!ctype_digit((string) $id)) {
    throw new ApiException('Invalid ID.', 422, ['id' => 'The ID must be a positive whole number.']);
}

$pdo = new PDO(
    'mysql:host=localhost;dbname=your_db;charset=utf8mb4',
    'user',
    'password',
    [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]
);

$stmt = $pdo->prepare('SELECT id, name, email FROM users WHERE id = :id');
$stmt->bindValue(':id', (int) $id, PDO::PARAM_INT);
$stmt->execute();
$user = $stmt->fetch();

if (!$user) {
    throw new ApiException('User not found.', 404);
}

jsonResponse(200, ['success' => true, 'data' => $user]);

// A PDOException (database down, bad query) reaches the global handler,
// gets logged, and the client receives a generic 500.

Validation errors vs. internal errors

Don't mix them up. A validation error means the client sent something wrong (an invalid email, an empty required field, a malformed ID): use 400 or 422. An internal error means the problem is on your side (server, database, code, infrastructure): use 500.

Type of errorExampleStatus
Invalid JSONBroken request body400
Invalid fieldBadly formatted email422
Not authenticatedNo token sent401
Not allowedRegular user calling an admin route403
Not foundID that doesn't exist404
Internal errorDatabase failure500

Common mistakes in PHP API error handling

1. Returning 200 for an error

A response with "success": false and status 200 OK confuses clients, monitoring tools and caches. If the user wasn't found, the status must be 404.

2. Returning errors as HTML

An API answers in JSON, including when something goes wrong.

3. Showing the real server error

Messages like SQLSTATE[42S02]: Base table or view not found belong in the log, not in the response.

4. Not logging

If the API only says "internal error" and you don't log the real one, you won't be able to find the problem later.

5. Mixing business rules with error handling

Keep response helpers, exception classes and validation in their own files.

Checklist for PHP API error handling

  • Does every response return JSON, with Content-Type: application/json?
  • Does the HTTP status change with the type of error?
  • Do validation errors return the list of invalid fields?
  • Are internal errors logged?
  • Are database details hidden from users?
  • Do authentication errors use 401 and permission errors 403?
  • Do missing resources use 404 and unexpected failures 500?

Conclusion

Error handling is what turns a simple PHP API into a professional one. With consistent JSON responses, the right status codes, a custom exception, global handlers and internal logs, your application is safer, easier to debug and more predictable for every client.

Use one structure for every success and error, whether the route is a sign-up, a login, a query, a webhook, an admin panel or a partner integration.

Frequently asked questions about error handling in PHP APIs

Should a PHP API return errors as JSON?

Yes. An API should return JSON for both successes and errors, so the frontend, the mobile app or the integration can handle them the same way.

Which status should I use for invalid JSON?

400 Bad Request, because the structure of the request is wrong.

Which status should I use for invalid fields?

422 Unprocessable Content is a good choice for fields like an invalid email or a short password.

What is the difference between 401 and 403?

401 means the user is not authenticated or sent an invalid token. 403 means the user is authenticated but not allowed to access the resource.

Should I show the real database error in the API response?

No. In production, log the database details and return a generic message.

Do I need a framework to handle errors properly?

No. In plain PHP you can build helpers, a custom exception and global handlers that give you professional, consistent error handling.

More in PHP