I have a question about the best approach for representing resource information via our API. Any input welcome.
We have a need to represent resources in slightly different ways depending on the context in which the resource is going to be used. As an extreme example: we have an
Api::Admin::IndexEnterpriseSerializer and an
Api::Admin::EnterpriseSerializer. The index serializer is much simpler and is designed for use on the
admin/enterprises index page which does not require much information about each enterprise in order to render properly. The
Api::Admin::EnterpriseSerializer is used to render
admin/enterprises/:id/edit and necessarily needs much more information to be included for the page to be rendered properly.
We can use the same route and controller action to request these two different representations of an object, and I think this is good. We use a param called
ams_prefix in conjunction with a special controller method
render_as_json to specify which representation we want and to render the json.
My question is: is there are better approach to specifying the set of required attributes? My concern is that if we continue using the existing approach, we risk polluting our list of serializers with single use classes that make only minor modifications to another class. I have seen other platforms use an approach where each attribute that is required by the client is explicitly mentioned in the request. Is that a better practice? It feels like it would lead to much messier client-side code…
Or do we just have a base serializer for each model which serializes some minimal set of attributes and then allows additional attributes to be specified as required. I feel like we are always going to need custom serializers, but perhaps some clever logic could help soak up the need for a whole new serializer when only one or two additional attributes are required?