Good REST API design PHP projects share comes down to predictable resource-based routes, strict request validation, a clear authentication choice, one consistent JSON envelope and correct status codes. You can achieve this with a framework such as Laravel or Symfony, or with a small router and discipline. The decisions below matter more than the library.
Examples are described rather than version-specific. Test any sample code on a currently supported PHP version, and check your framework's documentation for exact syntax.
REST API design PHP basics: resources and routes
REST works best when URLs name things and HTTP methods say what to do with them. Use plural nouns and keep verbs out of paths.
| Method and path | Meaning |
|---|---|
| GET /orders | List orders (paginated) |
| POST /orders | Create an order |
| GET /orders/42 | Read one order |
| PATCH /orders/42 | Change part of an order |
| DELETE /orders/42 | Remove or cancel an order |
| GET /customers/7/orders | Orders belonging to a customer |
Some guidance that avoids later pain:
- Limit nesting to one level; deeper trees get awkward.
- For actions that are not simple CRUD, such as cancelling or approving, either model them as a sub-resource (POST /orders/42/cancellation) or accept a small, clearly named action endpoint rather than overloading PATCH.
- Put a version in the path or header from the start so you can evolve the contract.
- Use the same naming style everywhere, typically snake_case or camelCase for JSON fields, never both.
- Use GET only for reading. Anything that changes data must not be reachable through GET.
Whether you build on a framework or without one is a project decision; our comparison of Laravel, CodeIgniter and plain PHP covers it. Either way, keep route definitions in one place and controllers thin.
Request validation
Treat all input as hostile. Validation belongs at the edge of the application, before data reaches business logic or the database.
- Check that the content type is JSON when you expect JSON, and return a client error for malformed bodies.
- Validate required fields, types, lengths, ranges, allowed values and formats such as dates and emails.
- Allow only fields you expect (a whitelist). Ignoring or rejecting extra fields prevents mass-assignment mistakes, like a client setting
roleorprice. - Always use prepared statements or your framework's query builder for database access; validation does not replace parameter binding.
- Return all validation errors at once, keyed by field, so clients can show them together.
Enforce limits on body size and rate. Security basics are covered further in the OWASP-based PHP security checklist.
Authentication options
Authentication answers who is calling; authorisation answers what they may do. Choose by who your clients are.
- Session cookies: good for a browser front end served from the same site, with CSRF protection.
- API keys: simple for server-to-server access by partners. Store only hashes, allow rotation and scope keys to specific permissions.
- Bearer tokens (including JWT): common for mobile apps and single-page applications. Keep lifetimes short, use refresh tokens carefully and be aware that stateless tokens are hard to revoke before expiry.
- OAuth 2.0 with an identity provider: best when third parties act on behalf of users, or when you want single sign-on, at the cost of more moving parts.
Always use HTTPS, never put tokens in URLs, and check authorisation per resource: "is this user allowed to read order 42?" is a separate check from "is this user logged in?". Skipping it is one of the most common API flaws. See secure API development for SaaS products for more on threat thinking.
Consistent JSON responses
Pick one response shape and use it everywhere. Clients write less code when success and error bodies are predictable.
- Always send
Content-Type: application/jsonand encode with proper flags and error checking. - For collections, return an array under a named key plus pagination metadata, rather than a bare array, so you can add fields later without breaking clients.
- Represent dates in a standard format such as ISO 8601, with timezone, and money as integer minor units plus a currency code.
- Return null or omit absent fields consistently; document which you do.
- Never leak internals: database column names, stack traces or file paths.
Wrap response creation in one helper or resource class so the shape cannot drift between endpoints.
Errors and status codes
Status codes are part of your contract. A reliable set:
- 200 for successful reads and updates, 201 after creating something (with its location), 204 when there is nothing to return.
- 400 for malformed requests, 422 (or 400, if you choose) for validation failures.
- 401 when authentication is missing or invalid, 403 when it is valid but not permitted.
- 404 for unknown resources, 409 for conflicts such as duplicates or stale updates.
- 429 when rate limits apply, and 500 only for real server faults.
Make error bodies consistent: a short machine-readable code, a human message, and per-field details where relevant. A standard problem-details style shape is a good model. Install a global exception handler so uncaught errors become tidy JSON rather than HTML error pages, log the details server-side, and include a request ID the client can quote to support. Disable display of PHP errors in production.
Pagination and filtering
Never return an unbounded list. Enforce a default and maximum page size.
- Offset pagination (page and per_page) is simple and fine for modest data, but gets slow and inconsistent on large, changing tables.
- Cursor (keyset) pagination uses the last seen ID or timestamp and stays fast on large sets; it suits feeds and exports.
- Whitelist sortable and filterable fields, and map them to indexed columns. Accepting arbitrary sort fields invites slow queries and injection mistakes.
- Return enough metadata for clients to continue: next cursor or page, and optionally a total where it is cheap to compute.
Index the columns you filter and sort by. For database tuning, see MySQL query optimization for PHP applications.
Testing and documentation
Test endpoints through HTTP, not only functions: send a request, assert on status, headers and body. Cover success, validation failure, unauthenticated, forbidden and not-found cases for each endpoint, and run them in your pipeline. Add a contract test for the shapes clients depend on.
For documentation, describe the API in an OpenAPI specification and generate human-readable reference pages from it. Keep it close to the code, ideally generated or validated automatically so it cannot silently go stale. Include authentication instructions, an error catalogue, pagination rules and worked request and response examples. A changelog and deprecation policy complete the picture, and a collection that clients can import for manual trying is a courtesy that saves support time.
Putting it together
Define resources first, validate strictly, choose authentication to fit your clients, standardise responses and errors, paginate everything and document as you go. These habits matter more than whether the stack is Laravel, Symfony or hand-rolled. For a broader architectural view of API design in business systems, read designing scalable, maintainable APIs, or see how we work with Danish companies if you are planning a build.
Frequently asked questions
Which authentication fits a PHP API?
It depends on the client. Session cookies suit a same-site browser front end, API keys suit simple server-to-server access, bearer tokens suit mobile and single-page apps, and OAuth 2.0 suits third parties acting for users. Whatever you choose, use HTTPS and check authorisation per resource.
What status codes should I use?
Use 200 for successful reads and updates, 201 after creation, and 204 for empty responses. Use 400 or 422 for invalid input, 401 for missing authentication, 403 for forbidden, 404 for not found, 409 for conflicts, 429 for rate limits and 500 only for genuine server faults.
How do I document a PHP API?
Describe it in an OpenAPI specification and generate reference pages from it, ideally validated against the code so it cannot go stale. Include authentication steps, an error catalogue, pagination rules, request and response examples and a changelog. An importable request collection also helps client developers.