Search code examples
phpjsonsymfonyfosrestbundle

FOSRestBundle, filtering out object properties in JSON response


I'm building an API for a Symfony2 project using FOSRestBundle, and I often simply return Doctrine objects to be encoded in JSON. Typically this way :

/**
 * @Rest\View()
 */
public function getEventsAction(Request $request)
{
  // security checks

  return $this->getDoctrine()->getRepository('SomeBundle:Event')->findAll();
}

Thing is, this returns all object properties and relationships, and in many cases I don't want that, for example with a User object that contains the hashed password and everything.

Is there a way to set up automatic filters when encoding Doctrine objects in JSON ? Or do I have to create a QueryBuilder only fetching required data ?


Solution

  • I highly recommend using the JMSSerializerBundle, it will give you as many options as you need. Once you have included it in your project, you can configure your entities to only have specific properties serialized. There are quite a few ways to do it, you can see all the different ways in the exclusion strategies part of the documentation.

    You are able to exclude specific properties and much more. Take a look.

    Also, take a look at my other answer for a bit more info on how to use it with FOSRestBundle