Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions core/json-schema.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,15 @@ with a resource or a DTO class references its schema.
A list shape such as `array{int, string}` is serialized as a JSON array, so it keeps being
documented as an array.

## Using the Symfony JsonSchema Component (Experimental)

Since API Platform 5.1, the Symfony integration can build schemas with the
[`symfony/json-schema`](https://github.com/symfony/json-schema) component by setting
`api_platform.json_schema.generator: true`. The option is experimental and not available with
Laravel. See the [upgrade guide](upgrade-guide.md#json-schema-generator-experimental) for the
migration steps, the services that no longer apply, and the `#[AsJsonSchemaDefinitionProcessor]`
extension point.

## Generating a JSON Schema Programmatically

To generate JSON Schemas programmatically, use the `api_platform.json_schema.schema_factory`.
Expand Down
217 changes: 216 additions & 1 deletion core/upgrade-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

## API Platform 5.0 to 5.1

5.1 only adds deprecations, they keep working until they are removed in 6.0.
5.1 only adds deprecations, they keep working until they are removed in 6.0, and one opt-in
experimental feature: the [JSON Schema generator](#json-schema-generator-experimental).

### API Platform 5.1 Deprecations

Expand Down Expand Up @@ -37,6 +38,220 @@ stay valid.
$operation = $operation->withParameters($parameters);
```

### JSON Schema Generator (Experimental)

> [!WARNING] This feature is experimental and opt-in. It can change in a minor release. It is
> implemented in [api-platform/core#8683](https://github.com/api-platform/core/pull/8683) (see the
> [changed files](https://github.com/api-platform/core/pull/8683/files)). The legacy factory chain
> stays the default and is not removed in 5.1.

API Platform 5.1 can build JSON Schemas with the
[`symfony/json-schema`](https://github.com/symfony/json-schema) component instead of
`ApiPlatform\JsonSchema\SchemaFactory`. The generated schemas are meant to match the legacy ones:
the same functional test goldens run against both implementations
([`GoldenSchemaTest`](https://github.com/soyuka/core/blob/feat/json-schema-kernel/tests/Functional/JsonSchema/GoldenSchemaTest.php)).

#### Enable the Generator

Install the component, which requires PHP 8.2 or later and `symfony/json-schema` `^8.2`, and set the
flag:

```console
composer require symfony/json-schema
```

```yaml
# api/config/packages/api_platform.yaml
api_platform:
json_schema:
generator: true # defaults to false
```

The option is defined in
[`Configuration.php`](https://github.com/soyuka/core/blob/feat/json-schema-kernel/src/Symfony/Bundle/DependencyInjection/Configuration.php).
If `symfony/json-schema` is missing, the container throws a `LogicException` at compile time
([`ApiPlatformExtension.php`](https://github.com/soyuka/core/blob/feat/json-schema-kernel/src/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php)).

The generator is available with the Symfony integration only. The Laravel service provider
(`ApiPlatform\Laravel\ApiPlatformProvider`) has no such option and keeps registering the legacy
`SchemaFactory`, `DefinitionNameFactory` and `SchemaPropertyMetadataFactory`.

#### What Keeps Working

When the flag is on,
[`json_schema_generator.php`](https://github.com/soyuka/core/blob/feat/json-schema-kernel/src/Symfony/Bundle/Resources/config/json_schema_generator.php)
redefines the `api_platform.json_schema.schema_factory` service with
[`ApiPlatform\JsonSchema\Generator\GeneratorSchemaFactory`](https://github.com/soyuka/core/blob/feat/json-schema-kernel/src/JsonSchema/Generator/GeneratorSchemaFactory.php),
which implements `ApiPlatform\JsonSchema\SchemaFactoryInterface`. Everything that targets the
service id or the interface keeps working:

- The `ApiPlatform\JsonSchema\SchemaFactoryInterface` alias still points to
`api_platform.json_schema.schema_factory`
([`json_schema.php`](https://github.com/soyuka/core/blob/feat/json-schema-kernel/src/Symfony/Bundle/Resources/config/json_schema.php)).
- The format wrappers still decorate `api_platform.json_schema.schema_factory`: Hydra, JSON:API and
HAL at priority `0`, `ApiPlatform\JsonSchema\BackwardCompatibleSchemaFactory` at priority `-2`.
Your own decorators of that id keep applying on top of the generator.
- The `api:json-schema:generate` command, the OpenAPI factory and the MCP schema factory use the
same service id.
- `#[ApiProperty(schema: [...])]`, `jsonSchemaContext` and `openapiContext` are still honored. The
`ApiPlatform\JsonSchema\Metadata\Property\Factory\SchemaPropertyMetadataFactory` decoration of
`api_platform.metadata.property.metadata_factory` stays registered, and the generator reads its
result.
- The `openapi_definition_name` serializer context key still sets the definition name.

#### What No Longer Applies

The following legacy classes are not used by the generator. Decorating or replacing them has no
effect on the core schema factory.

- `ApiPlatform\JsonSchema\SchemaFactory` (final) is not instantiated anymore. Depend on
`SchemaFactoryInterface`. The generator does not implement `SchemaFactoryAwareInterface`.
- `api_platform.json_schema.definition_name_factory` (`DefinitionNameFactory`,
`DefinitionNameFactoryInterface`) is replaced by
[`ApiPlatform\JsonSchema\Generator\ApiPlatformDefinitionPolicy`](https://github.com/soyuka/core/blob/feat/json-schema-kernel/src/JsonSchema/Generator/ApiPlatformDefinitionPolicy.php),
service `api_platform.json_schema.generator.definition_policy`, an implementation of
`Symfony\Component\JsonSchema\DefinitionPolicy\DefinitionPolicyInterface`.
- The property schema logic of `SchemaFactory` is replaced by
[`ApiPropertySchemaProvider`](https://github.com/soyuka/core/blob/feat/json-schema-kernel/src/JsonSchema/Generator/ApiPropertySchemaProvider.php)
(`PropertySchemaProviderInterface`) and
[`ApiPropertySchemaEnricher`](https://github.com/soyuka/core/blob/feat/json-schema-kernel/src/JsonSchema/Generator/ApiPropertySchemaEnricher.php)
(`PropertySchemaEnricherInterface`), both in `ApiPlatform\JsonSchema\Generator`.

The definition name factory is still passed to the Hydra, JSON:API and HAL wrappers (`hydra.php`,
`jsonapi.php`, `hal.php`), so a decorator of `api_platform.json_schema.definition_name_factory` only
affects the names those wrappers compute themselves. To change how definitions are named, decorate
`api_platform.json_schema.generator.definition_policy`. `ApiPlatformDefinitionPolicy` is `final`, so
decorate the service and implement `DefinitionPolicyInterface::nameFor()`:

```php
public function nameFor(
ObjectType|GenericType $type,
Configuration $config,
SchemaDocument $document,
?DefinitionParent $parent = null,
): string;
```

The name is the identity of a definition: anything that changes its shape (groups, attributes,
format) must be part of it, otherwise the generator throws when two shapes share a name. The
`ApiPlatformDefinitionPolicy` methods used by the built-in processors (`isPartial()`,
`resolveGenId()`, `findNestedOperation()`) are not part of the interface; a decorating policy has to
keep them if you inject the decorated service into the built-in processors.

If you decorated `SchemaPropertyMetadataFactory` itself, move the change to a regular
`PropertyMetadataFactoryInterface` decorator, or to a custom
`Symfony\Component\JsonSchema\PropertySchemaEnricher\PropertySchemaEnricherInterface`
(`enrich(PropertySchema $property, Configuration $config, SchemaDocument $document): PropertySchema`)
or `Symfony\Component\JsonSchema\PropertySchemaProvider\PropertySchemaProviderInterface`
(`provide(string $class, string $property, Configuration $config, SchemaDocument $document): ?array`).
Both interfaces come from `symfony/json-schema`. `GeneratorSchemaFactory` instantiates its own
provider and enricher in its constructor and does not collect tagged ones, so custom providers and
enrichers need a decorated `api_platform.json_schema.schema_factory` or a different approach: the
supported extension point in 5.1 is the definition processor described below.

#### Customize Definitions

A definition processor post-processes every object definition once its properties are built. It
implements `Symfony\Component\JsonSchema\DefinitionProcessor\DefinitionProcessorInterface`
(`@experimental` in `symfony/json-schema`):

```php
public function process(
array $definition,
ObjectType|GenericType $type,
Configuration $config,
SchemaDocument $document,
?DefinitionParent $parent,
): array;
```

`$parent` is `null` for the root definition. A processor can only change the definition it receives;
`SchemaDocument::describe()` returns the schema of another type to reference. Processors do not run
on the inline schemas returned by a class schema resolver.

Register a processor with the
[`ApiPlatform\Metadata\AsJsonSchemaDefinitionProcessor`](https://github.com/soyuka/core/blob/feat/json-schema-kernel/src/Metadata/AsJsonSchemaDefinitionProcessor.php)
attribute. With autoconfiguration, the Symfony bundle adds the
`api_platform.json_schema.definition_processor` tag and throws a `RuntimeException` if the class
does not implement `DefinitionProcessorInterface`. Without autoconfiguration, tag the service
yourself.

```php
<?php
// api/src/JsonSchema/RelaxedBookDefinitionProcessor.php
namespace App\JsonSchema;

use ApiPlatform\Metadata\AsJsonSchemaDefinitionProcessor;
use App\ApiResource\Book;
use Symfony\Component\JsonSchema\Configuration;
use Symfony\Component\JsonSchema\DefinitionParent;
use Symfony\Component\JsonSchema\DefinitionProcessor\DefinitionProcessorInterface;
use Symfony\Component\JsonSchema\SchemaDocument;
use Symfony\Component\TypeInfo\Type\GenericType;
use Symfony\Component\TypeInfo\Type\ObjectType;

#[AsJsonSchemaDefinitionProcessor]
final class RelaxedBookDefinitionProcessor implements DefinitionProcessorInterface
{
public function process(array $definition, ObjectType|GenericType $type, Configuration $config, SchemaDocument $document, ?DefinitionParent $parent): array
{
$class = ($type instanceof GenericType ? $type->getWrappedType() : $type)->getClassName();

if (Book::class !== $class) {
return $definition;
}

unset($definition['required']);

return $definition;
}
}
```

This is the logic of the built-in
[`PartialUpdateDefinitionProcessor`](https://github.com/soyuka/core/blob/feat/json-schema-kernel/src/JsonSchema/Generator/PartialUpdateDefinitionProcessor.php),
which drops `required` on partial updates. Ordering: `GeneratorSchemaFactory` runs
`PartialUpdateDefinitionProcessor`, `NestedOperationDefinitionProcessor` and, when a class
discriminator resolver exists, `DiscriminatorDefinitionProcessor` first, then the tagged processors
(`tagged_iterator('api_platform.json_schema.definition_processor')`). Among tagged processors, the
order follows the `priority` of the tag, higher first. The attribute has no `priority` argument, so
to set one, tag the service explicitly:

```yaml
# api/config/services.yaml
services:
App\JsonSchema\RelaxedBookDefinitionProcessor:
tags:
- { name: api_platform.json_schema.definition_processor, priority: 10 }
```

When JSON-LD is enabled, the bundle registers `ApiPlatform\Hydra\JsonSchema\ItemDefinitionProcessor`
([source](https://github.com/soyuka/core/blob/feat/json-schema-kernel/src/Hydra/JsonSchema/ItemDefinitionProcessor.php))
the same way.

#### Output Differences

The golden tests assert the same output for both implementations, so most schemas are identical. The
generator-specific behaviors that are visible in code:

- Definition names keep the legacy pattern (`<ShortName>-<groups>_<attributes>`, `.partial`,
`_noid`, `.jsonMergePatch`, `validation.<groups>`), computed in
`ApiPlatformDefinitionPolicy::nameFor()`. Short-name collisions are disambiguated with more
namespace segments, as before.
- Discriminator maps keep `enum` with a single value on the type property, and the OpenAPI 3 dialect
keeps the `discriminator` object with `propertyName` and `mapping`
([`DiscriminatorDefinitionProcessor.php`](https://github.com/soyuka/core/blob/feat/json-schema-kernel/src/JsonSchema/Generator/DiscriminatorDefinitionProcessor.php),
golden
[`input_discriminator_map.json`](https://github.com/soyuka/core/blob/feat/json-schema-kernel/tests/Functional/JsonSchema/golden/input_discriminator_map.json)).
The Swagger 2 dialect gets no `oneOf` or `discriminator`.
- With the flag on, the Hydra wrapper receives `$addReferencedItemBaseSchemas: true` and adds the
`HydraItemBaseSchema` and `HydraItemBaseSchemaWithoutId` definitions to the document when a
definition references them through `allOf`
([`ItemDefinitionProcessor.php`](https://github.com/soyuka/core/blob/feat/json-schema-kernel/src/Hydra/JsonSchema/ItemDefinitionProcessor.php)).

If a schema differs from the legacy output for your resources and the difference is not listed here,
report it on [GitHub](https://github.com/api-platform/core/issues).

## API Platform 4.4 to 5.0

5.0 removes long-deprecated APIs. Components ship with a `@beta` stability flag (for example
Expand Down
Loading