Spree uses JSON API serializers to represent data returned by API endpoints.
You can easily swap OOTB Spree serializers with your own thanks to Spree Dependencies.
Let's say you want to customize the Storefront API's Product serializer to include you custom database column
my_newcustom_attribute that you've added to the
spree_products database table.
Let's start with creating a new serializer file in your project's
app/serializers directory, that is
class MyProductSerializer < Spree::V2::Storefront::ProductSerializerattribute :my_new_custom_attributeend
Now let's tell Spree to use this new serializer, in
config/initializers/spree.rb please set:
Spree::Api::Dependencies.storefront_product_serializer = 'MyProductSerializer'
Restart the webserver and hit the Products API to notice that the payload now includes your new attribute. alongside the standard output.
Let's say you've created a new model called
Video that belongs to
Product (Product has multiple Videos).
Let's create a new serializer
class VideoSerializer < Spree::Api::V2::BaseSerializerset_type: :videoattributes :urlend
Now in your
class MyProductSerializer < Spree::V2::Storefront::ProductSerializerattribute :my_new_custom_attributehas_many :videos, serializer: :videoend
Hitting the Products API you will notice that in the relationships key there will be a new key called
To include Video response in the Product API add
?includes=videos in the API URL, eg.