Auto-Generate DTOs from JSON API Responses

📖 1 minute read

Working with third-party APIs means writing a lot of DTOs. So I built a quick code generator that turns JSON fixtures into typed PHP classes.

The workflow:

  1. Capture fixtures: add HTTP middleware to dump API responses to JSON files
  2. Analyze schema: scan fixtures, merge similar structures, infer types
  3. Generate DTOs: output properly typed classes with serializer annotations
php artisan generate:dtos \
  --output=app/Services/SDK/ThirdParty \
  --namespace="App\\Services\\SDK\\ThirdParty"

The generator handles:

  • Type inference from JSON values (string/int/float/bool/null)
  • Nullability detection: if a field is missing in any fixture, it’s nullable
  • Nested objects: creates separate classes for complex types
  • Array types: uses Str::singular() to name item classes (products → Product)

This saved hours of manual DTO writing. The key insight: API responses are the source of truth. Let the actual data structure define your types, not the other way around.

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *