Requests & Responses
PAM HTTP handlers work with the runtime’s own Pam\Http\Request and Pam\Http\Response objects. On top of them,
the package adds form requests for validation, DTO hydration, JSON resources for consistent output and a single
Problem Details format for every error.
The Request
Section titled “The Request”Pam\Http\Request is immutable. The most used members:
| Member | Returns |
|---|---|
$request->method, $request->path |
The method and the path, without the query string. |
route(string $key, ?string $default = null) |
A route parameter. |
routeParameters() |
All route parameters. |
getQuery(string $key, mixed $default = null), query() |
Query string values. |
getHeader(string $name, ?string $default = null), headers() |
Headers; names are case-insensitive and repeated values are joined with , . |
body(), json() |
The raw body, or the body decoded as JSON (throws JsonException on invalid JSON). |
Cookies, form fields and uploads come from the superglobals PAM fills for each request. See The Request in the runtime documentation for the full surface.
The Response
Section titled “The Response”Each request gets a fresh Pam\Http\Response. Its methods are fluent:
return $response ->status(201) ->header('location', '/api/orders/42') ->json(['id' => 42], 201);json($data, $status = 200) sets application/json; charset=utf-8, send($body) writes a scalar body as
text/plain unless you set a content type, and cookie(), stream() and sse() are also available. See
The Response.
Form Requests
Section titled “Form Requests”Form requests move validation and authorization out of controllers. Extend FormRequest and return the rules for
each field:
namespace App\Http\Requests;
use App\Domain\UserType;use Pam\Api\Validation\FormRequest;use Pam\Api\Validation\Rule;
final class StoreUserRequest extends FormRequest{ public function rules(): array { return [ 'name' => ['required', 'string'], 'email' => ['required', 'string', 'email'], 'type' => ['required', 'integer', Rule::enum(UserType::class)], ]; }
public function authorize(): bool { return true; }}Type-hint the form request on a controller action. The container builds it with the current request, which runs
authorize() and then the rules before your action starts:
public function store(StoreUserRequest $request): UserResource{ $validated = $request->validated(); // only fields that passed every rule $email = $request->input('email'); // one validated value
return new UserResource($this->users->create($validated), 201);}The request body must be a JSON object (an empty body counts as {}). validated() contains only the fields that
were present and passed every rule; fields without rules are ignored.
Available Rules
Section titled “Available Rules”| Rule | Passes when |
|---|---|
required |
The field is present and is not null or ''. |
string |
The value is a string. |
integer |
The value is a JSON integer. |
boolean |
The value is a JSON boolean. |
array |
The value is a JSON array or object. |
email |
The value is a valid email address. |
Rule::enum(Enum::class) |
The value is a valid case of a backed enum. |
Type rules skip absent fields, so combine them with required when the field is mandatory. An unknown rule name
throws an InvalidArgumentException.
Custom Rules
Section titled “Custom Rules”Implement ValidationRule. Return null when the value is valid or an error message:
use Pam\Api\Validation\ValidationRule;
final readonly class Uppercase implements ValidationRule{ public function validate(string $field, mixed $value): ?string { return is_string($value) && strtoupper($value) === $value ? null : "The {$field} field must be uppercase."; }}'code' => ['required', 'string', new Uppercase()],Authorizing Form Requests
Section titled “Authorizing Form Requests”When authorize() returns false, the request fails with 403 before any rule runs.
Validation Errors
Section titled “Validation Errors”A failed validation throws ValidationException, which PAM HTTP renders as 422 Problem Details with every
message grouped by field:
{ "errors": { "title": ["The title field is required."], "status": ["The status field is invalid."] }, "type": "https://pam.dev/problems/1", "title": "The submitted data is invalid.", "status": 422, "code": 1}Data Transfer Objects
Section titled “Data Transfer Objects”dto() hydrates a class from the validated data by matching constructor parameter names. Backed enum
parameters are converted with tryFrom(), and parameters with defaults may be omitted:
final readonly class CreatePostData{ public function __construct( public string $title, public PostStatus $status = PostStatus::Draft, ) {}}$data = $request->dto(CreatePostData::class);A missing required parameter or an invalid enum value throws an InvalidArgumentException. A small helper on
the form request keeps controllers tidy:
public function data(): CreatePostData{ return $this->dto(CreatePostData::class);}JSON Resources
Section titled “JSON Resources”A resource turns a domain object into the JSON your API promises. Extend the readonly JsonResource and
implement toArray(); the wrapped value is in $this->resource:
namespace App\Http\Resources;
use Pam\Api\Http\JsonResource;use Pam\Http\Request;
final readonly class PostResource extends JsonResource{ public function toArray(Request $request): array { return [ 'id' => $this->resource->id, 'title' => $this->resource->title, 'status' => $this->resource->status->value, ]; }}Return it from a handler. The output is wrapped in a data envelope:
return new PostResource($post); // 200 {"data":{...}}return new PostResource($post, 201); // 201 CreatedThe status must be between 100 and 599; anything else throws when the resource is constructed.
Resource Collections
Section titled “Resource Collections”collection() wraps every item and returns a ResourceCollection. Add metadata with withMeta():
return PostResource::collection($posts)->withMeta(['total' => count($posts)]);{"data":[{"id":1,"title":"A","status":1}],"meta":{"total":1}}Collections always respond with 200. Any class implementing Responsable
(toResponse(Request, Response): Response) can be returned the same way.
Errors
Section titled “Errors”Problem Details
Section titled “Problem Details”Every error PAM HTTP produces uses RFC 9457 Problem Details with
application/problem+json; charset=utf-8 and a stable integer code:
code |
ProblemCode |
Typical status |
|---|---|---|
| 1 | ValidationFailed |
422 |
| 2 | Unauthenticated |
401 |
| 3 | Forbidden |
403 |
| 4 | NotFound |
404 |
| 5 | Conflict |
409 |
| 6 | RateLimited |
429 |
| 7 | Timeout |
504 |
| 8 | InternalError |
500 |
| 9 | MethodNotAllowed |
405 |
The type is https://pam.dev/problems/{code}.
Throwing HTTP Errors
Section titled “Throwing HTTP Errors”Throw HttpException anywhere in a handler, middleware or service. Extra details are merged into the body, but
they can never replace type, title, status or code:
use Pam\Api\Http\HttpException;use Pam\Api\Http\ProblemCode;
throw new HttpException(409, ProblemCode::Conflict, 'Version conflict.', ['currentVersion' => 3]);{"currentVersion":3,"type":"https://pam.dev/problems/5","title":"Version conflict.","status":409,"code":5}Unexpected Exceptions
Section titled “Unexpected Exceptions”Any other exception is logged through PAM telemetry with its class, message, file and line, and the client
receives only a generic 500:
{"type":"https://pam.dev/problems/8","title":"Internal Server Error","status":500,"code":8}Exception messages never reach the client.
Custom Error Handler
Section titled “Custom Error Handler”Replace the handler for unexpected exceptions with onError(). It receives the exception and the response and
must return a Response:
$app->onError(static function (Throwable $error, Response $response): Response { Sentry::captureException($error);
return $response->json(['error' => 'Request failed'], 500);});HttpException (including validation errors) is always rendered as Problem Details and does not reach
onError().