Storefront API
This page covers adding new Storefront API endpoints and customization of existing ones

Customizing existing API endpoints

Customizing JSON response

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.

Adding custom attributes

Generally 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 in your project's app/serializers directory, that is app/serializers/my_product_serializer.rb:
1
class MyProductSerializer < Spree::V2::Storefront::ProductSerializer
2
attribute :my_new_custom_attribute
3
end
Copied!
Now let's tell Spree to use this new serializer, in config/initializers/spree.rb please set:
1
Spree::Api::Dependencies.storefront_product_serializer = 'MyProductSerializer'
Copied!
Restart the webserver and hit the Products API to notice that the payload now includes your new attribute. alongside the standard output.

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:
1
class VideoSerializer < Spree::Api::V2::BaseSerializer
2
set_type: :video
3
4
attributes :url
5
end
Copied!
Now in your app/serializers/my_product_serializer.rb
1
class MyProductSerializer < Spree::V2::Storefront::ProductSerializer
2
attribute :my_new_custom_attribute
3
4
has_many :videos, serializer: :video
5
end
Copied!
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.
1
https://localhost:3000/api/v2/storefront/products?include=videos
Copied!
Last modified 3mo ago