Online admissions open for the SEO, web development and networking & cybersecurity courses. Enquire for the next batch.

REST API Development in PHP: Design, Build and Secure

7 min read Updated By the SkillNewton team

What is REST API development?

REST API development is building a web service that exposes data as resources at URLs, such as /api/v1/products/5, and lets clients act on them with standard HTTP methods like GET, POST, PUT, PATCH and DELETE. The server replies with a status code and, usually, a JSON body. PHP can build REST APIs with or without a framework.

Resources, methods and the vocabulary of REST

A resource is a thing your API exposes, named with a plural noun: /products is a collection and /products/5 is one item. The HTTP method says what to do with it. If APIs are new to you, read the introduction to APIs first.

MethodExampleActionIdempotent?
GET/productsList or read; never changes dataYes
POST/productsCreate a new itemNo
PUT/products/5Replace the whole itemYes
PATCH/products/5Change some fieldsNot necessarily
DELETE/products/5Remove the itemYes

Idempotent means repeating the same request has the same effect as sending it once, which lets clients retry safely. Stateless means every request carries everything needed to process it, including authentication.

Status codes that clients rely on

CodeMeaningUse when
200 OKSuccess with a bodyReturning a resource or list
201 CreatedNew resource createdAfter POST, with a Location header
204 No ContentSuccess, no bodyAfter DELETE
400 Bad RequestMalformed requestInvalid JSON
401 UnauthorizedNot authenticatedMissing or invalid token
403 ForbiddenAuthenticated but not allowedEditing someone else's data
404 Not FoundNo such resourceUnknown ID or URL
422 Unprocessable ContentValid JSON, invalid dataValidation errors
429 Too Many RequestsRate limit reachedThrottling clients

Return errors in a consistent shape. RFC 9457, Problem Details for HTTP APIs, defines a standard JSON format with type, title and status fields and the application/problem+json media type.

Designing response bodies, filtering and pagination

Decide on one response shape and use it everywhere, so client developers never have to guess. A common pattern wraps results in a data key and puts paging details in a separate meta key:

GET /api/v1/products?category=stationery&sort=-price_paise&page=2&per_page=20

{
  "data": [
    { "id": 41, "name": "Fountain pen", "price_paise": 45000 },
    { "id": 17, "name": "Gel pen", "price_paise": 2000 }
  ],
  "meta": { "page": 2, "per_page": 20, "total": 57 }
}
  • Use query parameters for filtering, sorting and paging, never for the resource identity.
  • Check sort fields against an allow-list, because column names cannot be bound as SQL parameters.
  • Cap per_page at a sensible maximum so one request cannot ask for every row.
  • Use consistent field names, such as snake_case, and send dates in ISO 8601 format with a time zone.
  • Store money as integers in the smallest unit, such as paise, to avoid rounding errors.

Only return the fields a client needs. Never send password hashes, internal flags or other users' personal data just because they are in the database row.

JSON responses and routing in plain PHP

One front controller receives every request, sends JSON with the right status and routes by method and path. Data is encoded as JSON with JSON_THROW_ON_ERROR so encoding problems are never silent.

<?php
// public/index.php
declare(strict_types=1);

function json(mixed $data, int $status = 200, array $headers = []): never
{
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    foreach ($headers as $name => $value) {
        header($name . ': ' . $value);
    }
    if ($status !== 204) {
        echo json_encode($data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    }
    exit;
}

function problem(int $status, string $title, array $extra = [], array $headers = []): never
{
    json(['type' => 'about:blank', 'title' => $title, 'status' => $status] + $extra,
        $status, ['Content-Type' => 'application/problem+json'] + $headers);
}

$pdo = new PDO('mysql:host=localhost;dbname=shop;charset=utf8mb4', 'shop_app', getenv('DB_PASSWORD') ?: '', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

$method = $_SERVER['REQUEST_METHOD'];
$path = rtrim((string) parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');

if ($path === '/api/v1/products') {
    match ($method) {
        'GET'   => json(['data' => $pdo->query('SELECT id, name, price_paise FROM products ORDER BY id LIMIT 50')->fetchAll()]),
        'POST'  => createProduct($pdo, authenticate($pdo)),
        default => problem(405, 'Method not allowed', [], ['Allow' => 'GET, POST']),
    };
}
if (preg_match('#^/api/v1/products/(\d+)$#', $path, $m) && $method === 'GET') {
    $stmt = $pdo->prepare('SELECT id, name, price_paise FROM products WHERE id = ?');
    $stmt->execute([(int) $m[1]]);
    $product = $stmt->fetch();
    $product ? json(['data' => $product]) : problem(404, 'Product not found');
}
problem(404, 'Not found');

The functions createProduct() and authenticate() follow in the next two sections; place them above the routing code. Run the API with php -S localhost:8000 -t public public/index.php.

Reading and validating JSON input

PHP does not fill $_POST for JSON bodies, so read the raw body from php://input. Validate types strictly and return every error at once with status 422.

<?php
function readJson(): array
{
    try {
        $data = json_decode((string) file_get_contents('php://input'), true, 32, JSON_THROW_ON_ERROR);
    } catch (JsonException) {
        problem(400, 'Request body must be valid JSON');
    }
    return is_array($data) ? $data : problem(400, 'Request body must be a JSON object');
}

function createProduct(PDO $pdo, int $userId): never
{
    $in = readJson();
    $errors = [];
    $name = is_string($in['name'] ?? null) ? trim($in['name']) : '';
    if ($name === '' || mb_strlen($name) > 120) {
        $errors['name'] = 'Name is required, up to 120 characters.';
    }
    $price = $in['price_paise'] ?? null;
    if (!is_int($price) || $price < 1) {
        $errors['price_paise'] = 'Price must be a positive whole number of paise.';
    }
    if ($errors) {
        problem(422, 'Validation failed', ['errors' => $errors]);
    }
    $pdo->prepare('INSERT INTO products (name, price_paise, created_by) VALUES (?, ?, ?)')
        ->execute([$name, $price, $userId]);
    $id = (int) $pdo->lastInsertId();
    json(['data' => ['id' => $id, 'name' => $name, 'price_paise' => $price]], 201,
        ['Location' => '/api/v1/products/' . $id]);
}

Unexpected failures, such as a lost database connection, must still produce JSON. Register an exception handler near the top of the front controller, log the details privately and send a generic 500 response. With display_errors switched off in production, clients never see stack traces or file paths.

<?php
set_exception_handler(function (Throwable $e): void {
    error_log((string) $e);
    problem(500, 'Internal server error');
});

Token authentication and versioning

APIs usually authenticate with a bearer token in the Authorization header instead of a session cookie. Generate tokens with bin2hex(random_bytes(32)), show each one to the user once and store only its SHA-256 hash, so a database leak does not expose working tokens.

<?php
function authenticate(PDO $pdo): int
{
    $header = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
    if (!preg_match('/^Bearer ([a-f0-9]{64})$/', $header, $m)) {
        problem(401, 'Missing or malformed token', [], ['WWW-Authenticate' => 'Bearer']);
    }
    $stmt = $pdo->prepare('SELECT user_id FROM api_tokens WHERE token_hash = ? AND revoked_at IS NULL');
    $stmt->execute([hash('sha256', $m[1])]);
    $userId = $stmt->fetchColumn();
    if ($userId === false) {
        problem(401, 'Invalid token', [], ['WWW-Authenticate' => 'Bearer']);
    }
    return (int) $userId;
}
  • Some Apache and FastCGI setups do not pass the Authorization header to PHP by default; check your server configuration if it is always empty.
  • Put the major version in the path, such as /api/v1/, and add /api/v2/ only for breaking changes. Adding new optional fields is not a breaking change.
  • Serve APIs only over HTTPS, apply rate limits and check per-record ownership on every request.
  • Allow cross-origin browser requests only from front ends you trust, using CORS headers.

Password-based login for the people who create tokens is covered in the PHP authentication guide.

Practical exercise: build and test a products API

Assemble the code above into one project on your machine, create the products and api_tokens tables and insert one hashed test token. Then test it from the terminal:

curl -i http://localhost:8000/api/v1/products
curl -i -X POST http://localhost:8000/api/v1/products \
  -H "Authorization: Bearer YOUR_64_CHARACTER_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name":"Gel pen","price_paise":2000}'
  • Add PATCH and DELETE for /api/v1/products/{id}, returning 200 and 204.
  • Add ?page= pagination with a maximum page size.
  • Call the API from a web page with the Fetch API.

You are done when a POST without a token returns 401, a negative price returns 422 with a field error, a valid POST returns 201 with a Location header and an unknown ID returns 404. API work is a major part of the advanced PHP course.

Common mistakes

  • Returning status 200 with an error message in the body, so clients cannot detect failures.
  • Using verbs in URLs such as /getProducts instead of methods on resource nouns.
  • Changing data on a GET request, which caches, crawlers and prefetching may trigger.
  • Storing API tokens in plain text in the database.
  • Echoing PHP warnings or stack traces into JSON responses, which breaks clients and leaks details.
  • Making breaking changes to an existing version instead of releasing a new one.

Frequently asked questions

Should I use PUT or PATCH for updates?

Use PUT when the client sends the complete resource to replace it, and PATCH when it sends only the fields that change. Many APIs offer PATCH alone because clients rarely want to resend everything.

Do I need a framework to build a REST API in PHP?

No, as this guide shows. A framework such as Laravel adds routing, validation and authentication packages that save time on larger APIs.

What is the difference between REST and GraphQL?

REST exposes many URLs, one per resource. GraphQL usually exposes one endpoint where the client describes exactly which fields it wants in a query.

How should I document my API?

The OpenAPI Specification is a widely used format for describing endpoints, parameters and responses, and many tools generate interactive documentation from it.

Want to Learn This Properly?

The Advanced PHP Web Development & Full-Stack Application Development (Online) turns guides like this into practised skills, with projects on real websites.

WhatsApp Call Us Now

Free counselling

Send an Enquiry

Tell us which course you are interested in. We reply by email or phone with the next batch and how to enrol.

Protected by reCAPTCHA. Google Privacy and Terms apply.

We reply by email or phone within working hours. No spam.