Customizing JSON response
Spree uses a library called JSON API serializers to represent data returned by API endpoints. You can easily replace existing Spree serializers with your own thanks to Spree Dependencies. Here’s a list of all serializers that you can override:Key | Value |
---|---|
storefront_address_serializer | Spree::V2::Storefront::AddressSerializer |
storefront_cart_serializer | Spree::V2::Storefront::CartSerializer |
storefront_credit_card_serializer | Spree::V2::Storefront::CreditCardSerializer |
storefront_country_serializer | Spree::V2::Storefront::CountrySerializer |
storefront_user_serializer | Spree::V2::Storefront::UserSerializer |
storefront_shipment_serializer | Spree::V2::Storefront::ShipmentSerializer |
storefront_taxon_serializer | Spree::V2::Storefront::TaxonSerializer |
storefront_payment_method_serializer | Spree::V2::Storefront::PaymentMethodSerializer |
storefront_payment_serializer | Spree::V2::Storefront::PaymentSerializer |
storefront_product_serializer | Spree::V2::Storefront::ProductSerializer |
storefront_estimated_shipment_serializer | Spree::V2::Storefront::EstimatedShippingRateSerializer |
storefront_store_serializer | Spree::V2::Storefront::StoreSerializer |
storefront_order_serializer | Spree::V2::Storefront::OrderSerializer |
storefront_variant_serializer | Spree::V2::Storefront::VariantSerializer |
Adding custom attributes
As a rule of thumb it’s recommended to use Properties and OptionTypes/Option Values for custom attributes and not to modify the Spree database schema
my_newcustom_attribute
that you’ve added to the spree_products
database table.
Let’s start with creating a new serializer file:
This serializer will inherit from the
Spree::V2::Storefront::ProductSerializer
serializer, so you don’t need to rewrite the whole serializer.config/initializers/spree.rb
please set:
Adding a new association
Let’s say you’ve created a new model calledVideo
that belongs to Product
(Product has multiple Videos).
Let’s create a new serializer app/serializers/video_serializer.rb
:
app/serializers/my_product_serializer.rb
videos
To include Video response in the Product API add ?includes=videos
in the API URL, eg.