Skip to content
Merged
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
158 changes: 105 additions & 53 deletions core/form-data.md
Original file line number Diff line number Diff line change
@@ -1,91 +1,143 @@
# Accept `application/x-www-form-urlencoded` Form Data

API Platform only supports raw documents as request input (encoded in JSON, XML, YAML...). This has many advantages including support of types and the ability to send back to the API documents originally retrieved through a `GET` request.
However, sometimes - for instance, to support legacy clients - it is necessary to accept inputs encoded in the traditional [`application/x-www-form-urlencoded`](https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1) format (HTML form content type). This can easily be done using [the powerful event system](events.md) of the framework.

**⚠ Adding support for `application/x-www-form-urlencoded` makes your API vulnerable to [CSRF attacks](<https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)>). Be sure to enable proper countermeasures [such as DunglasAngularCsrfBundle](https://github.com/dunglas/DunglasAngularCsrfBundle).**
API Platform only supports raw documents as request input (encoded in JSON, XML, YAML...). This has many advantages
including support of types and the ability to send back to the API documents originally retrieved through a `GET` request.
However, sometimes - for instance, to support legacy clients - it is necessary to accept inputs encoded in the traditional
[`application/x-www-form-urlencoded`](https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1) format
(HTML form content type). This can easily be done using the powerful [System providers and processors](extending.md#system-providers-and-processors)
of the framework.

> [!WARNING]
> Adding support for `application/x-www-form-urlencoded` makes your API vulnerable to [CSRF (Cross-Site Request Forgery)](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)) attacks.
> It's crucial to implement proper countermeasures to protect your application.
>
> If you're using Symfony, make sure you enable [Stateless CSRF protection](https://symfony.com/blog/new-in-symfony-7-2-stateless-csrf).
>
> If you're working with Laravel, refer to the [Laravel CSRF documentation](https://laravel.com/docs/csrf) to ensure
> adequate protection against such attacks.

In this tutorial, we will decorate the default `DeserializeListener` class to handle form data if applicable, and delegate to the built-in listener for other cases.

## Create your `DeserializeListener` Decorator
## Create your `FormRequestProcessorDecorator` processor

This decorator is able to denormalize posted form data to the target object. In case of other format, it fallbacks to the original [DeserializeListener](https://github.com/api-platform/core/blob/91dc2a4d6eeb79ea8dec26b41e800827336beb1a/src/Bridge/Symfony/Bundle/Resources/config/api.xml#L85-L91).

```php
<?php
// api/src/EventListener/DeserializeListener.php
// api/src/State/FormRequestProcessorDecorator.php using Symfony or app/State/FormRequestProcessorDecorator.php using Laravel

namespace App\EventListener;
namespace App\State;

use ApiPlatform\Serializer\SerializerContextBuilderInterface;
use ApiPlatform\Symfony\EventListener\DeserializeListener as DecoratedListener;
use ApiPlatform\Util\RequestAttributesExtractor;
use ApiPlatform\State\ProcessorInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Serializer\SerializerContextBuilderInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;

final class DeserializeListener
final class FormRequestProcessorDecorator implements ProcessorInterface
{
private $decorated;
private $denormalizer;
private $serializerContextBuilder;
public function __construct(
private readonly ProcessorInterface $decorated,
private readonlyDenormalizerInterface $denormalizer,
private readonly SerializerContextBuilderInterface $serializerContextBuilder
) {}

public function __construct(DenormalizerInterface $denormalizer, SerializerContextBuilderInterface $serializerContextBuilder, DecoratedListener $decorated)
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed
{
$this->denormalizer = $denormalizer;
$this->serializerContextBuilder = $serializerContextBuilder;
$this->decorated = $decorated;
}

public function onKernelRequest(RequestEvent $event): void {
$request = $event->getRequest();
if ($request->isMethodCacheable(false) || $request->isMethod(Request::METHOD_DELETE)) {
return;
// If the content type is form data, we process it separately
if ('form' === $data->getContentType()) {
return $this->handleFormRequest($data);
}

if ('form' === $request->getContentType()) {
$this->denormalizeFormRequest($request);
} else {
$this->decorated->onKernelRequest($event);
}
// Delegate the processing to the original processor for other cases
return $this->decorated->process($data, $operation, $uriVariables, $context);
}

private function denormalizeFormRequest(Request $request): void
/**
* Handle form requests by deserializing the data into the correct entity
*/
private function handleFormRequest(Request $request)
{
if (!$attributes = RequestAttributesExtractor::extractAttributes($request)) {
return;
$attributes = $request->attributes->get('_api_attributes');
if (!$attributes) {
return null;
}

$context = $this->serializerContextBuilder->createFromRequest($request, false, $attributes);
$populated = $request->attributes->get('data');
if (null !== $populated) {
$context['object_to_populate'] = $populated;
}

// Deserialize the form data into an entity
$data = $request->request->all();
$object = $this->denormalizer->denormalize($data, $attributes['resource_class'], null, $context);
$request->attributes->set('data', $object);

return $this->denormalizer->denormalize($data, 'App\Entity\SomeEntity', null, $context);
}
}
```

## Creating the Service Definition
Next, configure the `FormRequestProcessorDecorator` according to whether you're using Symfony or Laravel, as shown below:

### Creating the Service Definition using Symfony

```yaml
# api/config/services.yaml
services:
# ...
'App\EventListener\DeserializeListener':
tags:
- {
name: 'kernel.event_listener',
event: 'kernel.request',
method: 'onKernelRequest',
priority: 2,
}
# Autoconfiguration must be disabled to set a custom priority
autoconfigure: false
decorates: 'api_platform.listener.request.deserialize'
arguments:
$decorated: '@App\EventListener\DeserializeListener.inner'
App\State\FormRequestProcessorDecorator:
decorates: api_platform.state.processor
arguments:
$decorated: '@App\State\FormRequestProcessorDecorator.inner'
$denormalizer: '@serializer'
$serializerContextBuilder: '@api_platform.serializer.context_builder'
tags:
- { name: 'api_platform.state.processor' }
```

### Registering a Decorated Processor using Laravel

```php
<?php
// app/Providers/AppServiceProvider.php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\State\FormRequestProcessorDecorator;
use ApiPlatform\Core\State\ProcessorInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;

class AppServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind(ProcessorInterface::class, function ($app) {
$decoratedProcessor = $app->make(ProcessorInterface::class);

return new FormRequestProcessorDecorator(
$decoratedProcessor,
$app->make(DenormalizerInterface::class),
$app->make(SerializerContextBuilderInterface::class)
);
});
}
}
```

## Using your `FormRequestProcessorDecorator` processor

Finally, you can use the processor in your API Resource like this:

```php
<?php
// api/src/ApiResource/SomeEntity.php with Symfony or app/ApiResource/SomeEntity.php with Laravel

namespace App\ApiResource;

use ApiPlatform\Metadata\Post;
use App\State\FormRequestProcessorDecorator;

#[Post(processor: FormRequestProcessorDecorator::class)]
class SomeEntity
{
//...
}
```
Loading