> ## Documentation Index
> Fetch the complete documentation index at: https://docs.apivalk.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Response

> Apivalk uses typed response objects to ensure consistent API output across your entire application.

## Creating a Response

Every response class must extend `AbstractApivalkResponse` and implement:

* `getStatusCode()`: Returns the HTTP status code (e.g., 200, 201, 404).
* `getDocumentation()`: Defines the schema for OpenAPI generation.
* `toArray()`: Returns the data to be rendered (usually as JSON).

### Example

```php theme={null}
namespace App\Http\Response\Pet;

use apivalk\apivalk\Http\Response\AbstractApivalkResponse;
use apivalk\apivalk\Documentation\ApivalkResponseDocumentation;
use apivalk\apivalk\Documentation\Property\StringProperty;

class GetPetResponse extends AbstractApivalkResponse
{
    private $pet;

    public function __construct(array $pet)
    {
        $this->pet = $pet;
    }

    public static function getStatusCode(): int
    {
        return self::HTTP_200_OK;
    }

    public static function getDocumentation(): ApivalkResponseDocumentation
    {
        $doc = new ApivalkResponseDocumentation();
        $doc->addProperty(new StringProperty('name', 'Name of the pet'));
        // ... add more properties
        return $doc;
    }

    public function toArray(): array
    {
        return [
            'id' => $this->pet['id'],
            'name' => $this->pet['name'],
        ];
    }
}
```

## Resource Responses (CRUD)

When a controller extends one of the `Abstract*ResourceController` bases, pair it with the matching pre-built response from `Http/Response/Resource/`:

| Response class            | Status | Used by                            |
| ------------------------- | ------ | ---------------------------------- |
| `ResourceCreatedResponse` | 201    | `AbstractCreateResourceController` |
| `ResourceViewResponse`    | 200    | `AbstractViewResourceController`   |
| `ResourceListResponse`    | 200    | `AbstractListResourceController`   |
| `ResourceUpdatedResponse` | 200    | `AbstractUpdateResourceController` |
| `ResourceDeletedResponse` | 200    | `AbstractDeleteResourceController` |

Each wraps the resource's `toArray($mode)` output under a `data` key. `ResourceListResponse` additionally takes a `PaginationResponseInterface` and emits the standard `pagination` envelope. The OpenAPI schema for these responses is generated from the `AbstractResource` declaration — you do **not** author response documentation by hand.

See [Resource Responses](/resources/responses).

## Built-in Error Responses

Apivalk provides several pre-defined error responses for common scenarios:

* `BadRequestApivalkResponse` (400)
* `UnauthorizedApivalkResponse` (401)
* `ForbiddenApivalkResponse` (403)
* `NotFoundApivalkResponse` (404)
* `MethodNotAllowedApivalkResponse` (405)
* `TooManyRequestsApivalkResponse` (429)
* `InternalServerErrorApivalkResponse` (500)
* `BadValidationApivalkResponse` (422) - Used automatically by the `RequestValidationMiddleware`.

## Headers

You can add custom headers to any response object:

```php theme={null}
$response->setHeaders([
    'X-Custom-Header' => 'Value'
]);

$response->addHeaders(['APP-ID' => '213']);
```

### Automatic Rate Limit Headers

When the [Rate Limit Middleware](/middleware/rate-limit) is active, Apivalk automatically appends rate limit information to the response headers. This ensures that clients are always aware of their current quota and remaining requests.

The following headers are automatically added:

* `X-RateLimit-Limit`: The maximum number of requests allowed in the current window.
* `X-RateLimit-Remaining`: The number of requests left for the current window.
* `X-RateLimit-Reset`: The time at which the current rate limit window resets (UTC timestamp).

If the rate limit is exceeded (429 Too Many Requests), the `Retry-After` header is also included.

## Pagination

If a route has [pagination enabled](/http/pagination), you can attach a pagination response object to your response. This will automatically inject the `pagination` metadata into the JSON output and the OpenAPI documentation.

```php theme={null}
use apivalk\apivalk\Http\Response\Pagination\PagePaginationResponse;

$response->setPaginationResponse(
    new PagePaginationResponse($page, $limit, $hasMore, $totalPages)
);
```

## Rendering

The `JsonRenderer` is the default renderer. It takes the array from `toArray()` and converts it to a JSON string, handling headers and status codes automatically.
