APIs

PHP REST API Starter

Consistent JSON API response helper with explicit HTTP status codes.

Overview

Consistent JSON API response helper with explicit HTTP status codes.

What this script does

This starter demonstrates the core implementation pattern. Adapt database fields, configuration and error handling to your application.

Source code

<?php
declare(strict_types=1);
function jsonResponse(array $payload,int $status=200): never {
    http_response_code($status); header('Content-Type: application/json; charset=utf-8');
    header('X-Content-Type-Options: nosniff');
    echo json_encode($payload,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR);
    exit;
}
// jsonResponse(['data'=>['id'=>123]]);
// jsonResponse(['error'=>['message'=>'Not found']],404);

Download starter source: Download PHP REST API Starter source

Installation and customization

  1. Review the code and required PHP extensions.
  2. Configure database and storage settings outside the public web root where applicable.
  3. Add authorization, rate limiting and logging for public-facing endpoints.
  4. Test valid, invalid and boundary inputs before deployment.

> This is a learning starter, not a complete production application. Apply the security and deployment requirements of your project.