Context
I found a lot of questions about the partial API response with FOSRest, and all the answers are based on JMS serializer parameters (exception, inclusion, groups, etc.). It works fine, but I'm trying to achieve something less "static".
Say I have a user with the following attributes: id username firstname lastname age sex
I am extracting this user with the endpoint GET /users/{id} and in the following way:
public function getUserAction(User $user) { return $user; }
The method returns the user with all its attributes.
Now I want to allow something like this: GET /users/{id}?attributes=id,username,sex
Question
Did I miss the functionality of FOSRestBUndle, JMSserializer or SensioFrameworkExtraBundle to achieve this automatically? Annotations, method, keyword in a query, or something else?
Otherwise, what is the best way to achieve it?
The code
I thought of doing something like this:
public function getUserAction(User $user, $attributes) { $groups = $attributes ? explode(",", $attributes) : array("Default"); $view = $this->view($user, 200) ->setSerializationContext(SerializationContext::create()->setGroups($groups)); return $this->handleView($view); }
And create a group for each attribute:
use JMS\Serializer\Annotation\Groups; class User { protected $id; protected $username; protected $firstname;