Build a JSON endpoint in PHP

Intermediate  Nov 3, 2026

Return data from MySQL as JSON, with correct headers and status codes.

Build a JSON endpoint in PHP
The steps of this tutorial at a glance.
The steps of this tutorial at a glance.

The endpoint

<?php
// api/products.php
require __DIR__ . '/../db.php';

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

function respond(int $code, array $data): never
{
    http_response_code($code);
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    respond(405, ['error' => 'Method not allowed']);
}

$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);

if ($id) {
    $s = $pdo->prepare('SELECT id, name, price FROM products WHERE id = ?');
    $s->execute([$id]);
    $row = $s->fetch();
    $row ? respond(200, $row) : respond(404, ['error' => 'Not found']);
}

respond(200, $pdo->query('SELECT id, name, price FROM products LIMIT 50')->fetchAll());
How the code in this section fits into the page.
How the code in this section fits into the page.

Status codes to use

  • 200 OK, 201 created, 204 no content
  • 400 bad request, 401 not logged in, 403 not allowed, 404 not found, 422 validation failed
  • 405 wrong method, 429 too many requests, 500 server error
The main points of this section.
The main points of this section.

Good habits

  • Select only the columns you want to expose.
  • Never echo raw database errors.
  • Keep one error format, so your JavaScript can handle all errors the same way.
The main points of this section.
The main points of this section.

More tutorials