Installation Add the package via Composer:
composer require api-platform/json-schema
Register the service provider in config/app.php (if not auto-discovered):
'providers' => [
// ...
ApiPlatform\JsonSchema\JsonSchemaServiceProvider::class,
],
Basic Usage Generate a JSON Schema from a PHP class (e.g., an Eloquent model or DTO):
use ApiPlatform\JsonSchema\JsonSchemaGenerator;
$generator = app(JsonSchemaGenerator::class);
$schema = $generator->generateSchema(new YourClass());
First Use Case Use the schema to validate incoming API requests or document your API:
$schemaJson = json_encode($schema, JSON_PRETTY_PRINT);
file_put_contents('schema.json', $schemaJson);
Schema Generation for Models Integrate with API Platform or standalone:
$userSchema = $generator->generateSchema(new User());
Dynamic Schema Generation Generate schemas dynamically in controllers or middleware:
public function showSchema(Request $request)
{
$schema = $this->jsonSchemaGenerator->generateSchema(new YourModel());
return response()->json($schema);
}
Validation Integration
Use the schema with a validator (e.g., Symfony Validator or JSON Schema validators like justinrainbow/json-schema):
$validator = new \Symfony\Component\Validator\Validator\ValidatorBuilder();
$validator = $validator->getValidator();
$errors = $validator->validate($data, $constraintsFromSchema($schema));
API Documentation
Embed schemas in OpenAPI/Swagger docs (e.g., via nelmio/api-doc-bundle):
# config/packages/nelmio_api_doc.yaml
swagger:
schemas:
User: !php/const ApiPlatform\JsonSchema\JsonSchemaGenerator::class
api-platform/core for seamless schema generation from entities.$cacheKey = 'schema_' . md5(get_class($object));
$schema = cache()->remember($cacheKey, now()->addHours(1), function () use ($generator, $object) {
return $generator->generateSchema($object);
});
$schema = $generator->generateSchema($object, [
'exclude' => ['password', 'createdAt'],
]);
Circular References Avoid infinite loops with recursive relationships:
// May cause issues if not handled
$generator->generateSchema(new User()); // User hasMany Posts, Post belongsTo User
Fix: Use context to limit depth or break cycles manually.
Type Mismatches The generator may not infer complex types (e.g., custom collections) accurately. Override with annotations or metadata:
/**
* @JsonSchema(type="array", items={"type": "string"})
*/
public function getTags(): array { ... }
Performance Generating schemas for large objects (e.g., deeply nested graphs) can be slow. Cache aggressively or lazy-load.
API Platform Quirks
If using API Platform, ensure your entity has proper ApiResource configuration. The generator respects serializationContext and denormalizationContext.
json_encode($schema, JSON_PRETTY_PRINT) to debug structure.Custom Schema Generators
Extend ApiPlatform\JsonSchema\Generator\GeneratorInterface for custom logic:
class CustomGenerator implements GeneratorInterface {
public function generateSchema($object, array $context = []): array {
// Custom logic
}
}
Register it in the container:
$this->app->bind(JsonSchemaGenerator::class, function () {
return new CustomGenerator();
});
Modify Default Behavior
Override the default generator in config/services.php:
'api_platform.json_schema' => [
'generator' => App\CustomGenerator::class,
],
Add Metadata Use annotations or attributes to customize schema generation:
use ApiPlatform\JsonSchema\Annotation\JsonSchema;
class User {
/**
* @JsonSchema(type="string", format="date-time")
*/
public $createdAt;
}
Handle Complex Types For custom types (e.g., UUIDs, enums), register type handlers:
$generator->addTypeHandler('uuid', function () {
return ['type' => 'string', 'format' => 'uuid'];
});
How can I help you explore Laravel packages today?