Skip to content
This repository has been archived by the owner on Apr 19, 2024. It is now read-only.

Latest commit

 

History

History
74 lines (50 loc) · 2.64 KB

api_v2.md

File metadata and controls

74 lines (50 loc) · 2.64 KB
title section order description
API v2
customization
6
This page covers adding new Storefront API endpoints and customization of existing ones

Storefront API

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

{% 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
end

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
end

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
end

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.

GET https://localhost:3000/api/v2/storefront/products?include=videos