Search code examples
symfonysymfony4autowired

Autowire request body to controller


I'm searching for a clean and simple way to autowire a POST request's body as a controller action argument, and deserialize it at the same time if application/json is set.

I've looked at events or ParamConverter, but none seem to be very adequate for this purpose.

I would use it as a shortuct to avoid using the Request object.

Eg:

POST /api/v1/admin/category HTTP/1.1
Host: localhost:8000
Authorization: Bearer token
Content-Type: application/json
Cache-Control: no-cache

{
    "name": "frombody"
}
public function createCategoty(array $body) {
    $body['name'] -> equals "frombody"
}

Solution

  • Since Symfony 6.3, the correct way is using #[MapRequestPayload].

    Read more here