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:
class MyProductSerializer < Spree::V2::Storefront::ProductSerializer
attribute :my_new_custom_attribute
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.

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:
class VideoSerializer < Spree::Api::V2::BaseSerializer
set_type: :video
attributes :url
Now in your app/serializers/my_product_serializer.rb
class MyProductSerializer < Spree::V2::Storefront::ProductSerializer
attribute :my_new_custom_attribute
has_many :videos, serializer: :video
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.