| title | API v2 |
|---|---|
| section | customization |
| order | 6 |
| description | This page covers customization of both Storefront API and Platform API |
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.
{% hint style="info" %} Generally it's recommended to use Properties and OptionTypes/Option Values for custom attributes and not to modify the Spree database schema {% endhint %}
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
endNow 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 app/serializers/video_serializer.rb:
class VideoSerializer < Spree::Api::V2::BaseSerializer
set_type: :video
attributes :url
endNow in your app/serializers/my_product_serializer.rb
class MyProductSerializer < Spree::V2::Storefront::ProductSerializer
attribute :my_new_custom_attribute
has_many :videos, serializer: :video
endHitting 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.
https://localhost:3000/api/v2/storefront/products?include=videos