API
This page covers adding new Spree API endpoints and customization of existing ones
Before you start customizing Spree API endpoints, make sure you reviewed all existing API endpoints in the Spree API docs.
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
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:
Place the following code in your new serializer file:
This serializer will inherit from the Spree::V2::Storefront::ProductSerializer
serializer, so you don’t need to rewrite the whole serializer.
Now let’s tell Spree to use this new serializer, in config/initializers/spree.rb
please set:
Restart the webserver and hit the Products API to notice that the payload now includes your new attribute.
Adding a new association
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 app/serializers/video_serializer.rb
:
Now in your app/serializers/my_product_serializer.rb
Hitting the Products API you will notice that in the relationships key there will be a new key called videos
To include Video response in the Product API add ?includes=videos
in the API URL, eg.