application/x-www-form-urlencoded
Form DataAPI 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
format (HTML form content type). This can easily be done using the powerful event system of the framework.
⚠ Adding support for application/x-www-form-urlencoded
makes your API vulnerable to CSRF attacks. Be sure to enable proper countermeasures such as DunglasAngularCsrfBundle.
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.
DeserializeListener
DecoratorThis decorator is able to denormalize posted form data to the target object. In case of other format, it fallbacks to the original DeserializeListener.
<?php
// api/src/EventListener/DeserializeListener.php
namespace App\EventListener;
use ApiPlatform\Core\Exception\RuntimeException;
use ApiPlatform\Core\Util\RequestAttributesExtractor;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use ApiPlatform\Core\EventListener\DeserializeListener as DecoratedListener;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;
final class DeserializeListener
{
private $decorated;
private $denormalizer;
private $serializerContextBuilder;
public function __construct(DenormalizerInterface $denormalizer, SerializerContextBuilderInterface $serializerContextBuilder, DecoratedListener $decorated)
{
$this->denormalizer = $denormalizer;
$this->serializerContextBuilder = $serializerContextBuilder;
$this->decorated = $decorated;
}
public function onKernelRequest(GetResponseEvent $event): void {
$request = $event->getRequest();
if ($request->isMethodSafe() || $request->isMethod(Request::METHOD_DELETE)) {
return;
}
if ('form' === $request->getContentType()) {
$this->denormalizeFormRequest($request);
} else {
$this->decorated->onKernelRequest($event);
}
}
private function denormalizeFormRequest(Request $request): void
{
if (!$attributes = RequestAttributesExtractor::extractAttributes($request)) {
return;
}
$context = $this->serializerContextBuilder->createFromRequest($request, false, $attributes);
$populated = $request->attributes->get('data');
if (null !== $populated) {
$context['object_to_populate'] = $populated;
}
$data = $request->request->all();
$object = $this->denormalizer->denormalize($data, $attributes['resource_class'], null, $context);
$request->attributes->set('data', $object);
}
}
# 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'
Made with love by
Les-Tilleuls.coop can help you design and develop your APIs and web projects, and train your teams in API Platform, Symfony, Next.js, Kubernetes and a wide range of other technologies.
Learn more