diff --git a/core/bootstrap.md b/core/bootstrap.md index 5e65f9cbe7a..0420b2326d6 100644 --- a/core/bootstrap.md +++ b/core/bootstrap.md @@ -1,27 +1,452 @@ # Bootstrapping the Core Library -You may want to run a minimal version of API Platform. This one file runs API Platform (without -GraphQL, Eloquent, Doctrine MongoDB...). It requires the following Composer packages: +API Platform core is a set of standalone components. This guide wires them by hand, without the +Symfony bundle or Laravel, to serve a JSON API from a single PHP file. + +The wiring follows the same steps as the framework integrations: + +1. Metadata factories describe your resources, their operations and their properties. +2. A router maps each operation to a URL and generates IRIs. +3. A serializer turns resources into JSON. +4. A provider chain reads the data, and a processor chain writes, serializes and builds the + response. +5. A controller runs both chains for the current request. > [!NOTE] > -> This documentation is a work in progress we're working on improving it, in the mean time we -> declare most of the services manually in the -> [ApiPlatformProvider](https://github.com/api-platform/core/blob/64768a6a5b480e1b8e33c639fb28b27883c69b79/src/Laravel/ApiPlatformProvider.php) -> it can be source of inspiration. +> The services are assembled in the Symfony bundle configuration +> ([`src/Symfony/Bundle/Resources/config`](https://github.com/api-platform/core/tree/main/src/Symfony/Bundle/Resources/config)) +> and in the Laravel +> [`ApiPlatformProvider`](https://github.com/api-platform/core/blob/main/src/Laravel/ApiPlatformProvider.php). +> Read them to see every optional service and its wiring. -## Components - -API Platform is installable as a set of components, for example: +## Installation ```console composer require \ - api-platform/serializer \ api-platform/metadata \ api-platform/state \ - api-platform/jsonld \ - phpdocumentor/reflection-docblock \ + api-platform/serializer \ + api-platform/symfony \ + symfony/config \ + symfony/http-foundation \ + symfony/property-access \ symfony/property-info \ symfony/routing \ + symfony/serializer \ + willdurand/negotiation +``` + +`api-platform/symfony` provides the IRI converter and the main controller. It also depends on +`symfony/http-kernel`, but this guide doesn't boot the HttpKernel. `symfony/config` is only needed +for the routing `ClosureLoader`. + +These packages are optional and enable more features: + +```console +composer require \ + phpstan/phpdoc-parser \ symfony/validator ``` + +- `phpstan/phpdoc-parser` lets the metadata read PHPDoc, such as the description of a resource. +- `symfony/validator` enables the validation described in [Writing Data](#writing-data-optional). + +## Creating a Resource + +Create `src/Author.php` and `src/Book.php`. The provider is a static method referenced as a +callable, so no service container is needed: + +```php +id = isset($uriVariables['id']) ? (int) $uriVariables['id'] : 1; + $book->title = 'API Platform'; + $book->author = new Author(); + + return $operation instanceof CollectionOperationInterface ? [$book] : $book; + } +} +``` + +Make sure `composer.json` autoloads the `App` namespace, then run `composer dump-autoload`: + +```json +{ + "autoload": { + "psr-4": { + "App\\": "src/" + } + } +} +``` + +## Wiring the Services + +Create `bootstrap.php` and add the following sections one after the other. + +### Metadata + +```php + ['application/json']]; + +$reflection = new ReflectionExtractor(); +$propertyInfo = new PropertyInfoExtractor([$reflection], [$reflection], [], [$reflection], [$reflection]); +$propertyAccessor = PropertyAccess::createPropertyAccessor(); + +// The directory containing your #[ApiResource] classes +$resourceNameCollectionFactory = new AttributesResourceNameCollectionFactory([__DIR__.'/src']); +$resourceClassResolver = new ResourceClassResolver($resourceNameCollectionFactory); +$propertyNameCollectionFactory = new PropertyInfoPropertyNameCollectionFactory($propertyInfo); + +$classMetadataFactory = new ApiClassMetadataFactory(new ClassMetadataFactory(new AttributeLoader())); + +$propertyMetadataFactory = new SerializerPropertyMetadataFactory( + $classMetadataFactory, + new AttributePropertyMetadataFactory(new PropertyInfoPropertyMetadataFactory($propertyInfo)), + $resourceClassResolver, +); + +$linkFactory = new LinkFactory($propertyNameCollectionFactory, $propertyMetadataFactory, $resourceClassResolver); + +// Each factory decorates the next one, the attributes factory runs first +$resourceMetadataFactory = new AlternateUriResourceMetadataCollectionFactory( + new FiltersResourceMetadataCollectionFactory( + new FormatsResourceMetadataCollectionFactory( + new InputOutputResourceMetadataCollectionFactory( + new OperationNameResourceMetadataCollectionFactory( + new LinkResourceMetadataCollectionFactory( + $linkFactory, + new UriTemplateResourceMetadataCollectionFactory( + $linkFactory, + new UnderscorePathSegmentNameGenerator(), + new NotExposedOperationResourceMetadataCollectionFactory( + $linkFactory, + new AttributesResourceMetadataCollectionFactory(), + ), + ), + ), + ), + ), + $formats, + [], + $formats, + ), + ), +); +``` + +Laravel uses this chain in +[`ApiPlatformDeferredProvider`](https://github.com/api-platform/core/blob/main/src/Laravel/ApiPlatformDeferredProvider.php), +and the Symfony bundle registers the same factories as decorators. Both wrap the result in caching +decorators (`CachedResourceMetadataCollectionFactory`, `CachedPropertyMetadataFactory`) that you can +add for production. The `ParameterResourceMetadataCollectionFactory` is also optional: add it to use +[parameters and filters](filters.md). + +### Routing and IRIs + +The router matches a request to an operation and generates the IRI of each resource. The routes come +from the operations: the Symfony bundle builds them in `ApiPlatform\Symfony\Routing\ApiLoader` and +Laravel in `src/Laravel/routes/api.php`. + +```php +use ApiPlatform\State\CallableProvider; +use ApiPlatform\Symfony\Routing\IriConverter; +use ApiPlatform\Symfony\Routing\Router as ApiRouter; +use Symfony\Component\Routing\Loader\ClosureLoader; +use Symfony\Component\Routing\RequestContext; +use Symfony\Component\Routing\Route; +use Symfony\Component\Routing\RouteCollection; +use Symfony\Component\Routing\Router; + +$routes = new RouteCollection(); +foreach ($resourceNameCollectionFactory->create() as $resourceClass) { + foreach ($resourceMetadataFactory->create($resourceClass) as $resource) { + foreach ($resource->getOperations() as $name => $operation) { + // Symfony routing expects ".{_format}" where RFC 6570 has "{._format}" + $path = str_replace('{._format}', '.{_format}', $operation->getUriTemplate()); + $routes->add($name, new Route( + $path, + ['_format' => null, '_api_resource_class' => $resourceClass, '_api_operation_name' => $name], + (array) $operation->getRequirements(), + [], + '', + [], + [$operation->getMethod()], + )); + } + } +} + +$context = new RequestContext(); +$router = new Router(new ClosureLoader(), static fn () => $routes, ['resource_type' => 'closure'], $context); + +$callableProvider = new CallableProvider(); +$iriConverter = new IriConverter( + $callableProvider, + new ApiRouter($router), + new IdentifiersExtractor($resourceMetadataFactory, $resourceClassResolver, $propertyNameCollectionFactory, $propertyMetadataFactory, $propertyAccessor), + $resourceClassResolver, + $resourceMetadataFactory, +); +``` + +`ApiPlatform\Symfony\Routing\IriConverter` and `Router` need Symfony routing. Laravel ships its own +`ApiPlatform\Laravel\Routing\IriConverter` and `Router` on top of the Laravel router. The rest of +the services only depend on `ApiPlatform\Metadata\IriConverterInterface`. + +The `IriConverter` also accepts a `UriVariablesConverter` and a `SkolemIriConverter` (blank node +IRIs). Both are optional. + +### Serializer + +```php +use ApiPlatform\Serializer\ItemNormalizer; +use ApiPlatform\Serializer\SerializerContextBuilder; +use Symfony\Component\Serializer\Encoder\JsonEncoder; +use Symfony\Component\Serializer\NameConverter\MetadataAwareNameConverter; +use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; +use Symfony\Component\Serializer\Serializer; + +$nameConverter = new MetadataAwareNameConverter($classMetadataFactory); +$serializer = new Serializer( + [ + new ItemNormalizer( + $propertyNameCollectionFactory, + $propertyMetadataFactory, + $iriConverter, + $resourceClassResolver, + $propertyAccessor, + $nameConverter, + $classMetadataFactory, + resourceMetadataFactory: $resourceMetadataFactory, + ), + new ObjectNormalizer($classMetadataFactory, $nameConverter), + ], + [new JsonEncoder()], +); +$contextBuilder = new SerializerContextBuilder($resourceMetadataFactory); +``` + +Add the Symfony `DateTimeNormalizer` before the `ObjectNormalizer` if your resources have date +properties. Other formats, such as JSON-LD and Hydra, bring their own normalizers and encoder in the +`api-platform/jsonld` and `api-platform/hydra` packages. + +### State + +The provider chain reads the data and the processor chain writes it, serializes it and creates the +response. Each decorator calls the next one. + +```php +use ApiPlatform\State\CallableProcessor; +use ApiPlatform\State\Processor\RespondProcessor; +use ApiPlatform\State\Processor\SerializeProcessor; +use ApiPlatform\State\Processor\WriteProcessor; +use ApiPlatform\State\Provider\ContentNegotiationProvider; +use ApiPlatform\State\Provider\ReadProvider; +use Negotiation\Negotiator; + +$provider = new ContentNegotiationProvider( + new ReadProvider($callableProvider, $contextBuilder), + new Negotiator(), + $formats, + $formats, +); + +$processor = new WriteProcessor( + new SerializeProcessor( + new RespondProcessor($iriConverter, $resourceClassResolver, null, $resourceMetadataFactory), + $serializer, + $contextBuilder, + ), + new CallableProcessor(), +); +``` + +`CallableProvider` and `CallableProcessor` call the `provider` and `processor` of the operation. +When these are class names instead of callables, pass a PSR-11 container to resolve them. + +### Handling the Request + +```php +use ApiPlatform\Symfony\Controller\MainController; +use Symfony\Component\HttpFoundation\Request; + +$request = Request::createFromGlobals(); +$context->fromRequest($request); +$request->attributes->add($router->match($request->getPathInfo())); + +$controller = new MainController($resourceMetadataFactory, $provider, $processor); +$controller($request)->send(); +``` + +The controller reads the operation from the `_api_resource_class` and `_api_operation_name` route +defaults, resolves the URI variables, applies the default stage flags (read, deserialize, write, +serialize), then runs the provider and the processor. + +## Running + +```console +php -S localhost:8000 bootstrap.php +curl http://localhost:8000/books +curl http://localhost:8000/books/1 +``` + +## HttpKernel and Laravel + +This guide runs the providers and processors from a controller. This is the default behavior of the +Symfony bundle (`MainController`) and of Laravel +(`ApiPlatform\Laravel\Controller\ApiPlatformController`). + +The classes in `ApiPlatform\Symfony\EventListener` (`AddFormatListener`, `ReadListener`, +`DeserializeListener`, `WriteListener`, `SerializeListener`, `RespondListener`) are tied to the +Symfony HttpKernel events. They are only registered when the Symfony bundle option +`use_symfony_listeners` is `true`. You don't need them here, and Laravel doesn't use them. + +## Writing Data (Optional) + +To accept `POST` requests, add a denormalizer and the `DeserializeProvider`. Declare a `Post` +operation and a `processor` on the resource: + +```php +use ApiPlatform\Metadata\Post; + +#[ApiResource( + operations: [new Get(), new GetCollection(), new Post()], + provider: [self::class, 'provide'], + processor: [self::class, 'process'], +)] +class Book +{ + // ... + + public static function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed + { + // Persist your data here + $data->id = 2; + + return $data; + } +} +``` + +In `bootstrap.php`, register an `ItemDenormalizer` next to the `ItemNormalizer` (it takes the same +arguments) and wrap the `ReadProvider`: + +```php +use ApiPlatform\Serializer\ItemDenormalizer; +use ApiPlatform\State\Provider\DeserializeProvider; + +// In the Serializer array, before the ObjectNormalizer +new ItemDenormalizer( + $propertyNameCollectionFactory, + $propertyMetadataFactory, + $iriConverter, + $resourceClassResolver, + $propertyAccessor, + $nameConverter, + $classMetadataFactory, + resourceMetadataFactory: $resourceMetadataFactory, +), + +$provider = new ContentNegotiationProvider( + new DeserializeProvider(new ReadProvider($callableProvider, $contextBuilder), $serializer, $contextBuilder), + new Negotiator(), + $formats, + $formats, +); +``` + +To validate the deserialized object with `symfony/validator`, wrap the `DeserializeProvider` in a +`ValidateProvider`: + +```php +use ApiPlatform\Symfony\Validator\State\ValidateProvider; +use ApiPlatform\Symfony\Validator\Validator; +use Symfony\Component\Validator\Validation; + +$validator = new Validator(Validation::createValidatorBuilder()->enableAttributeMapping()->getValidator()); + +// new ContentNegotiationProvider(new ValidateProvider(new DeserializeProvider(...), $validator), ...) +``` + +Validation errors and unknown routes throw exceptions. Catch them around the controller call to +render the error response you need. + +```console +curl -X POST http://localhost:8000/books \ + -H 'Content-Type: application/json' \ + -d '{"title": "Hello", "author": "/authors/1"}' +```