yhu420
yhu420

Reputation: 607

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"
}

Upvotes: -1

Views: 298

Answers (2)

yhu420
yhu420

Reputation: 607

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

Read more here

Upvotes: 0

Alister Bulman
Alister Bulman

Reputation: 35169

I've done that a couple of different ways recently.

joipolloi/json-validation-bundle listens for a FilterControllerEvent (a pre-controller-action hook), and then checks for an annotation that has a path to a schema to check the incoming POST request against.

I've also done it with a simple ParamConverter, where I type-hint a specific object (or specifically named array) that will receive the decoded json (assuming there is json POST content).

Either way, it is decoded from the Request's body content, and put into an action parameter.

Upvotes: -1

Related Questions