How to Create a REST API in Plain PHP (JSON, Routing, CRUD and Bearer Token)

Example of a REST API in plain PHP with JSON, routes and a Bearer token

Quick answer: To build a REST API in plain PHP, send every request to one index.php through .htaccess and use a small router that maps the HTTP method and URL to a controller. Always answer in JSON with the correct HTTP status code, use PDO with prepared statements for the CRUD, and protect routes by reading the token from the Authorization: Bearer header. In production, add validation, CORS, rate limiting and logging.

What you will build

In this guide you will put together a REST API in plain PHP (no framework) with:

  • JSON responses
  • Clean routes (GET, POST, PUT, DELETE)
  • An example CRUD (/api/posts)
  • Validation and error handling
  • Simple Bearer token authentication

Folder structure (simple and scalable)

/public
  /api
    index.php
    .htaccess
/src
  /Controllers
    PostController.php
  /Core
    Router.php
    Response.php
    Auth.php
  /Db
    Database.php

Only /public is served by the web server; your classes in /src stay out of reach.

1) Clean URLs on Apache (.htaccess)

Create /public/api/.htaccess:

RewriteEngine On

# Pass the Authorization header to PHP (needed on many Apache setups)
CGIPassAuth On

# If the file or folder exists, serve it directly
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# Everything else goes to index.php
RewriteRule ^ index.php [QSA,L]

On Nginx, the equivalent is try_files $uri $uri/ /api/index.php?$query_string; inside the location /api/ block.

2) index.php: the API's entry point

Create /public/api/index.php:

<?php
header('Content-Type: application/json; charset=UTF-8');

require_once __DIR__ . '/../../src/Core/Router.php';
require_once __DIR__ . '/../../src/Core/Response.php';
require_once __DIR__ . '/../../src/Core/Auth.php';
require_once __DIR__ . '/../../src/Controllers/PostController.php';

$router = new Router();

// Health check
$router->get('/api/health', function () {
  Response::json(['ok' => true, 'service' => 'my-api']);
});

// Posts CRUD (example)
$controller = new PostController();

$router->get('/api/posts', [$controller, 'index']);
$router->get('/api/posts/{id}', [$controller, 'show']);

// Protected routes
$router->post('/api/posts', function () use ($controller) {
  Auth::requireBearer();
  $controller->store();
});

$router->put('/api/posts/{id}', function ($params) use ($controller) {
  Auth::requireBearer();
  $controller->update($params['id']);
});

$router->delete('/api/posts/{id}', function ($params) use ($controller) {
  Auth::requireBearer();
  $controller->destroy($params['id']);
});

// Run
$router->dispatch($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']);

3) Router.php: a small router with parameters

Create /src/Core/Router.php:

<?php
class Router {
  private array $routes = [];

  public function get($path, $handler)    { $this->add('GET', $path, $handler); }
  public function post($path, $handler)   { $this->add('POST', $path, $handler); }
  public function put($path, $handler)    { $this->add('PUT', $path, $handler); }
  public function delete($path, $handler) { $this->add('DELETE', $path, $handler); }

  private function add($method, $path, $handler) {
    $this->routes[] = compact('method', 'path', 'handler');
  }

  public function dispatch($method, $uri) {
    $path = parse_url($uri, PHP_URL_PATH);
    $pathMatched = false;

    foreach ($this->routes as $r) {
      $pattern = '#^' . preg_replace('#\{([a-zA-Z_][a-zA-Z0-9_]*)\}#', '(?P<$1>[^/]+)', $r['path']) . '$#';

      if (!preg_match($pattern, $path, $matches)) continue;
      $pathMatched = true;
      if ($r['method'] !== $method) continue;

      $params = array_filter($matches, fn($k) => !is_int($k), ARRAY_FILTER_USE_KEY);
      return call_user_func($r['handler'], $params);
    }

    // The URL exists but not for this method: 405, otherwise 404
    $pathMatched
      ? Response::error('Method Not Allowed', 405)
      : Response::error('Not Found', 404);
  }
}

4) Response.php: consistent JSON

Create /src/Core/Response.php:

<?php
class Response {
  public static function json($data, int $code = 200) {
    http_response_code($code);
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
  }

  public static function error(string $message, int $code = 400, $details = null) {
    $payload = ['error' => $message];
    if ($details !== null) $payload['details'] = $details;
    self::json($payload, $code);
  }

  public static function readJsonBody(): array {
    $data = json_decode(file_get_contents('php://input'), true);
    if (!is_array($data)) self::error('Invalid JSON', 422);
    return $data;
  }
}

5) Auth.php: Bearer token (simple and direct)

Create /src/Core/Auth.php:

<?php
class Auth {
  public static function requireBearer() {
    $hdr = $_SERVER['HTTP_AUTHORIZATION']
        ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] // some servers use this name
        ?? '';

    if (!preg_match('/^Bearer\s+(\S+)$/i', $hdr, $m)) {
      Response::error('Unauthorized', 401);
    }

    // Simple version: one API key in an environment variable.
    // For user logins, issue and validate a JWT instead.
    $expected = (string) getenv('API_TOKEN');
    if ($expected === '' || !hash_equals($expected, $m[1])) {
      Response::error('Invalid token', 401);
    }
  }
}

A fixed token is fine for server-to-server integrations. When each user logs in, replace it with a signed, expiring token: see JWT authentication in PHP.

6) PostController.php: example CRUD

Create /src/Controllers/PostController.php:

<?php
require_once __DIR__ . '/../Core/Response.php';

class PostController {

  public function index() {
    // Static example (connect it to the database later)
    Response::json([
      ['id' => 1, 'title' => 'Post 1'],
      ['id' => 2, 'title' => 'Post 2'],
    ]);
  }

  public function show($params) {
    $id = (int)($params['id'] ?? 0);
    if ($id <= 0) Response::error('Invalid ID', 422);

    Response::json(['id' => $id, 'title' => 'Example post']);
  }

  public function store() {
    $data = Response::readJsonBody();
    if (empty($data['title'])) Response::error('title is required', 422);

    // Save it to the database here...
    Response::json(['message' => 'Created', 'data' => $data], 201);
  }

  public function update($id) {
    $id = (int)$id;
    if ($id <= 0) Response::error('Invalid ID', 422);

    $data = Response::readJsonBody();
    Response::json(['message' => 'Updated', 'id' => $id, 'data' => $data]);
  }

  public function destroy($id) {
    $id = (int)$id;
    if ($id <= 0) Response::error('Invalid ID', 422);

    Response::json(['message' => 'Deleted', 'id' => $id]);
  }
}

When you connect the controller to MySQL, use PDO with prepared statements in every query: see how to prevent SQL injection with PDO.

Status codes your API should use

  • 200 OK and 201 Created for successful reads and creations;
  • 401 when the token is missing or invalid, 403 when the user is authenticated but not allowed;
  • 404 for a resource or route that doesn't exist, 405 for the wrong method;
  • 422 for invalid input;
  • 500 for unexpected server errors (log the details, return a generic message).

7) Testing with curl

GET without a token:

curl -i https://www.example.com/api/posts

POST with a Bearer token:

curl -i -X POST https://www.example.com/api/posts \
  -H "Authorization: Bearer YOUR_TEST_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"title":"My post"}'

If the POST always returns 401 even with the right token, the server is probably dropping the Authorization header; check the CGIPassAuth On line in .htaccess.

Recommended improvements for production

  • Validate tokens against the database or use JWT with expiration
  • Add CORS headers if a frontend on another domain calls the API
  • Log errors and keep every response in the same shape (success, data, error); see how to find the cause of a PHP 500 error
  • Add simple rate limiting to prevent abuse

More in PHP