Content · Programming · PHP

Building Data Transfer Objects for API Responses

Use typed immutable response DTOs to separate application models from serialized JSON fields.

1 views Published Oct 17, 2026 Updated Oct 17, 2026 Know-Stuff

Use typed immutable response DTOs to separate application models from serialized JSON fields. The examples below demonstrate the main workflow, an edge case and one practical integration pattern.

What Does This Workflow Do?


Use the first example to see the core idea. The additional examples demonstrate validation and a separate integration scenario. Set timeouts, validate destinations, keep secrets out of logs and follow the protocol semantics for the chosen status code.

Syntax:

The complete workflow is demonstrated below; individual calls are explained in context.

Requirements and Data Flow


There is no single function signature for this workflow. The required variables depend on the request, server configuration and libraries used in the examples.

Example 1: Basic Usage


Use typed immutable response DTOs to separate application models from serialized JSON fields.

<?php
final readonly class ProductResponse { public function __construct(public int $id, public string $name) {} }
$product = new ProductResponse(10, "Notebook");
echo json_encode(["id" => $product->id, "name" => $product->name], JSON_THROW_ON_ERROR);

This example demonstrates the central operation. The final output depends on the supplied input and, where relevant, the runtime or connected service.

Example 2: Handling a Different Case


<?php
final readonly class AccountResponse { public function __construct(public int $id, public bool $active) {} }
$response = new AccountResponse(12, true);
var_dump($response->active);

The second example focuses on a different input or failure condition, so the behavior can be distinguished from the basic case.

Practical Example


<?php
final readonly class ItemResponse { public function __construct(public string $sku, public int $stock) {} }
$item = new ItemResponse("A-12", 5);
echo json_encode(get_object_vars($item), JSON_THROW_ON_ERROR);

The practical example demonstrates how the same subject fits into a larger application. Use your own file paths, endpoints and validated inputs rather than copying sample settings directly.

Important Behavior and Edge Cases


  • Set timeouts, validate destinations, keep secrets out of logs and follow the protocol semantics for the chosen status code.
  • Keep the example scoped to its stated purpose. A sample does not replace application authentication, authorization, production configuration or deployment review.
  • A response status, media type and headers are part of the HTTP contract; do not expose sensitive details in error bodies.

Comparison With Related Functions


ApproachDifference
Building Data Transfer Objects for API ResponsesUse typed immutable response DTOs to separate application models from serialized JSON fields.
HTTP status handlingCommunicates success or failure using protocol-defined response codes.

Common Beginner Mistakes


MistakeCorrect Approach
Ignoring errors from Building Data Transfer Objects for API ResponsesCheck the actual result and handle the expected error path.
Using the demonstration unchanged in productionAdapt file paths, configuration, authentication and permission rules to the application.
Treating input or returned data as trustedApply validation at input boundaries and context-aware escaping at output boundaries.

Key Takeaways


  • Set timeouts, validate destinations, keep secrets out of logs and follow the protocol semantics for the chosen status code.
  • Keep the example scoped to its stated purpose. A sample does not replace application authentication, authorization, production configuration or deployment review.
  • A response status, media type and headers are part of the HTTP contract; do not expose sensitive details in error bodies.

Use typed immutable response DTOs to separate application models from serialized JSON fields. Use this approach when its capabilities and constraints match the application. Handle invalid data, failure conditions and resource cleanup explicitly.

Share this resourceSend this page to someone who may find it useful.