Design resource endpoints with explicit methods, status codes and JSON response shapes. The examples separate the essential operation from the conditions a production implementation must enforce.
What It Does
Design resource endpoints with explicit methods, status codes and JSON response shapes.
Prerequisites
Use a dedicated development environment with test accounts and records. Separate authorization, validation and error handling from response formatting; never copy demonstration-only secrets into production.
Example 1: Core Behavior
The first example isolates the core operation so its result is easy to understand.
<?php
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
header('Content-Type: application/json; charset=utf-8');
if ($method !== 'GET') { http_response_code(405); header('Allow: GET'); exit; }
echo json_encode(['items'=>[]], JSON_THROW_ON_ERROR);
Example 2: Alternative or Failure Case
The second example demonstrates an alternative outcome, rule or failure condition.
<?php
$payload = json_decode('{"name":"Example"}', true, 512, JSON_THROW_ON_ERROR);
if (!is_string($payload['name'] ?? null)) { http_response_code(422); exit; }
http_response_code(201);
echo json_encode(['id'=>18, 'name'=>$payload['name']], JSON_THROW_ON_ERROR);
Practical Example: Applying the Rule
The practical example shows how to carry the same constraint into application code.
<?php
$id = filter_var('42', FILTER_VALIDATE_INT);
if ($id === false) { http_response_code(400); exit; }
header('Content-Type: application/json');
echo json_encode(['id'=>$id, 'status'=>'active'], JSON_THROW_ON_ERROR);
Important Behavior and Edge Cases
Validate input and authorize resources before database changes; never expose stack traces as JSON.
Comparison with Related Functions or Patterns
| Approach | When it differs |
|---|---|
| PHP REST APIs: Getting Started | Design resource endpoints with explicit methods, status codes and JSON response shapes. |
| Related API or pattern | API resource design precedes adding an HTTP router. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Returning a generic success response without validating the method or input | Validate input and authorize resources before database changes; never expose stack traces as JSON. |
| Substituting a related API without checking its semantics | API resource design precedes adding an HTTP router. |
Key Takeaways
- Design resource endpoints with explicit methods, status codes and JSON response shapes.
- Validate input and authorize resources before database changes; never expose stack traces as JSON.
- API resource design precedes adding an HTTP router.
Select this API or pattern based on its documented behavior and the trust boundaries in your own application, and test all external integrations against their actual deployments.