Custom PHP

PHP REST API Design: The Rules I Use in Production

PHP REST API design is the practice of shaping endpoints, responses and errors so clients can integrate without guessing. In my builds it means plural resource paths, meaningful HTTP status codes, URI versioning, token authentication and cursor pagination — decided before the first route is written, not patched after a client complains.

By Saif Al Jahanwebdev-saif.com

Start with resources, not endpoints

A PHP REST API is defined by its resources before it is defined by its routes. I name collections with plural nouns — /customers, /invoices, /orders — and keep verbs out of the path, letting HTTP methods carry the action: GET to read, POST to create, PUT to replace, PATCH to modify, DELETE to remove. Nested resources stay shallow, so /customers/42/orders is fine while /customers/42/orders/8/items/3 is a smell. I use kebab-case for multiword segments and keep identifiers opaque and consistent. In PHP I map these routes to controllers in a single src/Controller directory and let PSR-15 middleware handle auth, JSON parsing and content negotiation before the controller runs.

  • Plural nouns for collections: /customers, not /getCustomers
  • HTTP methods express intent: GET, POST, PUT, PATCH, DELETE
  • Nesting capped at one level: /customers/42/orders
  • Stable, opaque IDs; never expose sequential internals as security

Use HTTP status codes as part of the contract

Status codes are part of the API contract, not decoration. Returning 200 for every outcome forces clients to parse the body to learn what happened, and it breaks caching and retry logic. I return 201 with a Location header pointing at /customers/42 after a create, 200 for a successful read or update, and 204 with an empty body for deletes. A malformed JSON body is 400; a well-formed body that fails validation is 422 with field-level messages. Missing or expired credentials are 401, while valid credentials without permission are 403. Conflicts such as a duplicate email are 409, rate limits are 429 with a Retry-After header, and unexpected failures are 500 with a generic message. In PHP I set these with http_response_code() or a PSR-7 response object, never by echoing JSON and hoping.

  • 201 + Location for created resources; 204 for successful deletes
  • 400 for malformed payloads vs 422 for validation failures
  • 401 unauthenticated vs 403 unauthorized
  • 409 conflicts, 429 with Retry-After, 500 with a generic message
  • Never return 200 with an error flag buried in the body

Version before you have to

Versioning is cheaper when it is part of the URL from day one. I use a path prefix — /v1/customers — because it is obvious in logs, cache keys and client code, and it lets a load balancer route old and new handlers differently. The alternative, content negotiation with Accept: application/vnd.webdev-saif.v2+json, is cleaner in theory but harder to debug and frequently mishandled by proxies. I keep older versions alive for a defined window, publish Deprecation and Sunset headers on the old version, and remove it only when telemetry shows no live traffic. That is the approach I use in the custom PHP work on webdev-saif.com. Breaking changes get a new version; additive fields do not. Inside the PHP code I keep version-specific boundary transformers so a v2 response shape does not leak into v1 handlers.

Authentication that survives a real client

Authentication should be decided before the first route ships. For machine-to-machine clients I issue short-lived JWTs sent as Authorization: Bearer <token>, with exp, iat and iss claims verified on every request, and a rotating refresh token stored server-side. For browser sessions I rely on HttpOnly, Secure, SameSite cookies rather than tokens in localStorage. Passwords are hashed with Argon2id via password_hash() and checked with password_verify(); tokens never appear in query strings because URLs end up in logs. In PHP I enforce this in PSR-15 middleware so no controller can accidentally skip it, and I keep public endpoints on an explicit allowlist. Scope checks belong there too, not scattered through business logic.

  • Bearer JWTs with exp, iat and iss verified on every request
  • Refresh tokens rotated server-side and revoked on suspected reuse
  • HttpOnly, Secure and SameSite cookies for browser sessions
  • Argon2id password hashes via password_hash() and password_verify()
  • Auth in middleware; public routes on an explicit allowlist

Pagination: offset versus cursor

Pagination is where APIs quietly become unusable at scale. Offset pagination — GET /v1/customers?page=3&per_page=20 — is simple and fine for small admin tables, but it returns duplicates and gaps when rows are inserted while a client pages through. For feeds and large datasets I use keyset or cursor pagination: GET /v1/orders?limit=20&cursor=eyJpZCI6..., with the next cursor returned in meta.next_cursor and a stable sort on (created_at, id). The SQL uses a tuple comparison rather than OFFSET, so performance does not degrade on page 500. I cap limit at 100 and return 400 when a client exceeds it. Total counts are optional because COUNT(*) on a large table is expensive; clients that need one can request it explicitly.

  • Offset pagination for small admin lists: page + per_page
  • Cursor pagination for large sets: limit + next_cursor
  • Stable sort key, ideally a tuple such as (created_at, id)
  • Hard cap on limit with a 400 response when exceeded
  • Return next_cursor in meta, not in an undocumented header

Errors and response shape

Consistency matters more than the specific envelope. I return { "data": ... } for successes, { "meta": { ... } } for pagination and rate-limit details, and { "errors": [{ "code": "validation.failed", "field": "email", "message": "..." }] } for failures. Stable machine-readable codes let clients branch without parsing prose, while the message stays human-readable. In PHP I build responses through one JsonResponder that calls json_encode() with JSON_THROW_ON_ERROR and sets Content-Type: application/json; charset=utf-8 every time. I never leak stack traces or raw PDO exceptions to clients; those go to logs. A single response shape also makes generated API documentation and contract tests far easier to keep honest.

How I verify the API before handing it over

Before I hand an API over, I test the contract rather than the implementation. I start with an OpenAPI 3.1 file that lists every path, parameter, status code and schema, then write Pest or PHPUnit tests that assert the exact status and JSON shape for each case — including the 422 and 409 branches clients actually hit. I run composer test in CI on PHP 8.2 with the same extensions as production, and check that Content-Type and Retry-After headers are present. Finally I replay real client sequences: create, paginate, update, delete, and confirm the auth middleware rejects a missing token. I build these APIs from Mymensingh, Bangladesh (GMT+6), and the same contract-first pass applies whether the client is local or overseas.

Frequently asked questions

What is PHP REST API design?

It is the practice of defining resources, HTTP methods, status codes, versions, authentication and pagination so a client can integrate without reading your source. I settle naming, error shapes and versioning before writing routes, then enforce them with middleware and tests. Good design shows up as predictable URLs, honest status codes and responses that never change shape without a version bump.

Should I use /v1/ in the URL or an Accept header for versioning?

I use /v1/ in the URL for most builds. It appears in access logs, browser devtools and CDN cache keys, which makes debugging straightforward. Accept-header versioning with a vendor media type is more RESTful in theory, but proxies and client libraries often mishandle it. Whichever you pick, publish Deprecation and Sunset headers before removing an old version.

When should an API return 401 instead of 403?

401 means the request has no valid credentials — the token is missing, expired or malformed. 403 means the credentials are valid but lack permission for that resource. In PHP I handle both in auth middleware so controllers never have to guess. Returning 403 for a missing token is a common mistake that makes client-side retry logic unreliable.

Offset or cursor pagination — which should I use?

Offset pagination with page and per_page is fine for small admin lists where users jump to arbitrary pages. Cursor pagination is better for feeds and large tables: it uses a stable sort key and a next_cursor, so inserts during paging do not cause duplicates and deep pages stay fast. I usually ship both and let the client choose.

Where should authentication live in a PHP API?

In middleware, not in individual controllers. A PSR-15 middleware layer can verify the bearer token, check scopes and attach the authenticated user to the request before any handler runs. I keep an explicit allowlist for public routes such as health checks and login. That structure makes it difficult to add a new endpoint and forget to protect it.

Written by Saif Al Jahan, webdev-saif.com · Mymensingh, Bangladesh. Last updated .