Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Ability to expand nested associations, eg. `variant.images` (#13743)

Damian Legawiec343bf83b10d0
diff --git a/docs/api-reference/store-api/querying.mdx b/docs/api-reference/store-api/querying.mdx
index d33ad19552..17c677fed9 100644
--- a/docs/api-reference/store-api/querying.mdx
+++ b/docs/api-reference/store-api/querying.mdx
@@ -236,6 +236,69 @@ curl -G 'http://localhost:3000/api/v3/store/customer/orders' \
</CodeGroup>
+## Expanding Associations
+
+Use the `expand` parameter to include associated resources in the response. Pass a comma-separated list of association names:
+
+<CodeGroup>
+
+```typescript SDK
+const product = await client.store.products.get('spree-tote', {
+ expand: ['variants', 'images'],
+})
+```
+
+```bash cURL
+curl -G 'http://localhost:3000/api/v3/store/products/spree-tote' \
+ -H 'X-Spree-Api-Key: spree_pk_xxx' \
+ -d 'expand=variants,images'
+```
+
+</CodeGroup>
+
+### Nested Expand
+
+Use dot notation to expand nested associations (up to 4 levels deep):
+
+<CodeGroup>
+
+```typescript SDK
+// Expand variants and their images in one request
+const product = await client.store.products.get('spree-tote', {
+ expand: ['variants.images'],
+})
+
+// Multiple nested expands
+const product = await client.store.products.get('spree-tote', {
+ expand: ['variants.images', 'variants.metafields', 'option_types'],
+})
+
+// Taxon with nested children
+const taxon = await client.store.taxons.get('categories/clothing', {
+ expand: ['children.children'], // Two levels of subcategories
+})
+```
+
+```bash cURL
+# Expand variants with their images
+curl -G 'http://localhost:3000/api/v3/store/products/spree-tote' \
+ -H 'X-Spree-Api-Key: spree_pk_xxx' \
+ -d 'expand=variants.images'
+
+# Multiple nested expands
+curl -G 'http://localhost:3000/api/v3/store/products/spree-tote' \
+ -H 'X-Spree-Api-Key: spree_pk_xxx' \
+ -d 'expand=variants.images,variants.metafields,option_types'
+```
+
+</CodeGroup>
+
+### Rules
+
+- Maximum depth is **4 levels** (e.g., `a.b.c.d`)
+- A nested expand automatically includes its parent — `expand=variants.images` expands both `variants` and their `images`
+- Nested expand only applies to conditional associations (those controlled by `expand`)
+
## Field Selection
Use the `fields` parameter to request only specific fields in the response. This reduces payload size for bandwidth-sensitive clients like mobile apps or server-side rendering.
@@ -282,7 +345,7 @@ curl -G 'http://localhost:3000/api/v3/store/products' \
- The `id` field is **always included**, even if not listed in `fields`
- Omitting `fields` returns all fields (default behavior)
- Field selection applies to the top-level resource only — expanded associations always return their full set of fields
-- Combine with `expand` to include associations: `?fields=name,variants&expand=variants`
+- Expanded associations are **always included** in the response regardless of `fields` — `?fields=name&expand=variants` returns `id`, `name`, and `variants`
<Note>
The SDK TypeScript types remain fully typed regardless of field selection. When using `fields`, be aware that only the requested fields will be present at runtime.
diff --git a/docs/developer/sdk/store/products.mdx b/docs/developer/sdk/store/products.mdx
index b999db2297..c3fcd1a615 100644
--- a/docs/developer/sdk/store/products.mdx
+++ b/docs/developer/sdk/store/products.mdx
@@ -52,12 +52,28 @@ const products = await client.store.products.list({
const product = await client.store.products.get('spree-tote', {
fields: ['name', 'slug', 'price'],
- expand: ['images'], // expanded associations return all their fields
+ expand: ['images'], // expanded associations are always included
});
```
`id` is always included. Omit `fields` to return all fields.
+### Nested Expand
+
+Use dot notation to expand nested associations (up to 4 levels):
+
+```typescript
+// Expand variants with their images in one request
+const product = await client.store.products.get('spree-tote', {
+ expand: ['variants.images', 'option_types'],
+});
+
+// Access nested data
+product.variants.forEach(variant => {
+ console.log(variant.images); // Images are included
+});
+```
+
### Get a Product
Fetch a single product by slug or prefix ID:
diff --git a/packages/sdk/.changeset/nested-expand.md b/packages/sdk/.changeset/nested-expand.md
new file mode 100644
index 0000000000..75711ee4ca
--- /dev/null
+++ b/packages/sdk/.changeset/nested-expand.md
@@ -0,0 +1,5 @@
+---
+"@spree/sdk": patch
+---
+
+Added support for nested expand with dot notation. Pass `expand: ['variants.images']` to expand associations up to 4 levels deep. No SDK code changes required — this is a backend feature that works with the existing SDK.
diff --git a/packages/sdk/src/types/index.ts b/packages/sdk/src/types/index.ts
index 5a93a8ac86..51c3552016 100644
--- a/packages/sdk/src/types/index.ts
+++ b/packages/sdk/src/types/index.ts
@@ -67,7 +67,7 @@ export interface ListParams {
limit?: number;
/** Sort order. Prefix with - for descending, e.g. '-created_at', 'name'. Comma-separated for multiple fields. */
sort?: string;
- /** Associations to expand, e.g. ['variants', 'images'] */
+ /** Associations to expand. Supports dot notation for nested expand (max 4 levels), e.g. ['variants', 'variants.images'] */
expand?: string[];
/** Fields to include in response, e.g. ['name', 'slug', 'price']. Omit to return all fields. 'id' is always included. */
fields?: string[];
diff --git a/server/Gemfile.lock b/server/Gemfile.lock
index 4fe5db5b16..278cc6a5eb 100644
--- a/server/Gemfile.lock
+++ b/server/Gemfile.lock
@@ -79,6 +79,7 @@ PATH
rexml
safely_block (~> 0.4)
sqids (~> 0.2)
+ ssrf_filter (~> 1.0)
state_machines-activemodel (~> 0.100)
state_machines-activerecord (~> 0.100)
stringex
@@ -753,6 +754,7 @@ GEM
spree_core (>= 4.2.0.rc3)
spree_extension
sqids (0.2.2)
+ ssrf_filter (1.3.0)
state_machines (0.100.4)
state_machines-activemodel (0.101.0)
activemodel (>= 7.2)
@@ -1131,6 +1133,7 @@ CHECKSUMS
spree_i18n (5.3.2) sha256=03b805235ca156644951f6bc3d07cbe43d0aa01134c4a27e3f3304011956f79b
spree_stripe (1.5.1)
sqids (0.2.2) sha256=c2d31e0dfb6c32d17c10b59df059a299af93bef716d700ff70d77156df702d36
+ ssrf_filter (1.3.0) sha256=66882d7de7d09c019098d6d7372412950ae184ebbc7c51478002058307aba6f2
state_machines (0.100.4) sha256=dd4e555ebb061569dd8fe18a5f39b51d10be6306b89a0c315a9697671d752565
state_machines-activemodel (0.101.0) sha256=6798c6bf5aa4be2b1a00ca633949c999ebee7a148bd4ea8f6858b189e2cdf72d
state_machines-activerecord (0.100.0) sha256=b2213f74f3f32c6d92de5139e8898bc64a0ffb3f048df7d950ce27e28384beb5
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/resource_serializer.rb b/spree/api/app/controllers/concerns/spree/api/v3/resource_serializer.rb
index 648649ccbc..d1ee1ccb54 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/resource_serializer.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/resource_serializer.rb
@@ -51,12 +51,17 @@ module Spree
end
# Filter serialized hash to only include requested fields.
- # The 'id' field is always included.
+ # The 'id' field is always included. Expanded associations are always included.
def filter_fields(hash)
fields = fields_list
return hash unless fields
- hash.select { |key, _| key == 'id' || fields.include?(key) }
+ hash.select { |key, _| key == 'id' || fields.include?(key) || expanded_keys.include?(key) }
+ end
+
+ # Top-level expand keys (e.g., 'variants.images' → 'variants')
+ def expanded_keys
+ @expanded_keys ||= expand_list.map { |e| e.split('.').first }.to_set
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/customer_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/customer_serializer.rb
index a1d5de2dc5..fe030ecc1d 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/customer_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/customer_serializer.rb
@@ -33,7 +33,7 @@ module Spree
many :orders,
resource: Spree.api.admin_order_serializer,
- if: proc { params[:expand]&.include?('orders') }
+ if: proc { expand?('orders') }
# TODO: Add store_credits association when Admin API is implemented
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb
index 0d97822c86..328e4e960d 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb
@@ -36,7 +36,7 @@ module Spree
one :user,
resource: Spree.api.admin_customer_serializer,
- if: proc { params[:expand]&.include?('user') }
+ if: proc { expand?('user') }
# TODO: Add adjustments associations when Admin API is implemented
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/product_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/product_serializer.rb
index 5c2facf867..46005c1e53 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/product_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/product_serializer.rb
@@ -26,20 +26,20 @@ module Spree
# Admin uses admin variant serializer
many :variants,
resource: Spree.api.admin_variant_serializer,
- if: proc { params[:expand]&.include?('variants') }
+ if: proc { expand?('variants') }
one :default_variant,
resource: Spree.api.admin_variant_serializer,
- if: proc { params[:expand]&.include?('default_variant') }
+ if: proc { expand?('default_variant') }
one :master,
key: :master_variant,
resource: Spree.api.admin_variant_serializer,
- if: proc { params[:expand]&.include?('master_variant') }
+ if: proc { expand?('master_variant') }
many :metafields,
resource: Spree.api.admin_metafield_serializer,
- if: proc { params[:expand]&.include?('metafields') }
+ if: proc { expand?('metafields') }
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/taxon_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/taxon_serializer.rb
index c8d92bda1b..a0e32e2f3e 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/taxon_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/taxon_serializer.rb
@@ -12,7 +12,7 @@ module Spree
many :metafields,
resource: Spree.api.admin_metafield_serializer,
- if: proc { params[:expand]&.include?('metafields') }
+ if: proc { expand?('metafields') }
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/taxonomy_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/taxonomy_serializer.rb
index b822865ae5..227f65c94f 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/taxonomy_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/taxonomy_serializer.rb
@@ -7,7 +7,7 @@ module Spree
class TaxonomySerializer < V3::TaxonomySerializer
many :metafields,
resource: Spree.api.admin_metafield_serializer,
- if: proc { params[:expand]&.include?('metafields') }
+ if: proc { expand?('metafields') }
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rb
index 4583518ad0..9773a7b076 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rb
@@ -22,11 +22,11 @@ module Spree
# All prices for this variant (for admin management)
many :prices,
resource: Spree.api.admin_price_serializer,
- if: proc { params[:expand]&.include?('prices') }
+ if: proc { expand?('prices') }
many :metafields,
resource: Spree.api.admin_metafield_serializer,
- if: proc { params[:expand]&.include?('metafields') }
+ if: proc { expand?('metafields') }
# TODO: Add stock_items association when Admin API is implemented
end
diff --git a/spree/api/app/serializers/spree/api/v3/base_serializer.rb b/spree/api/app/serializers/spree/api/v3/base_serializer.rb
index 43e6383e19..1294375af8 100644
--- a/spree/api/app/serializers/spree/api/v3/base_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/base_serializer.rb
@@ -38,8 +38,10 @@ module Spree
end
# Check if an association should be expanded
+ # Supports dot notation: expand?('variants') matches both 'variants' and 'variants.images'
def expand?(name)
- expands.include?(name.to_s)
+ name = name.to_s
+ expands.any? { |e| e == name || e.start_with?("#{name}.") }
end
# Get nested expands for a given parent
@@ -48,9 +50,24 @@ module Spree
expands.select { |i| i.start_with?(prefix) }.map { |i| i.sub(prefix, '') }
end
- # Build nested params for child serializers
- def nested_params(parent = nil)
- params.merge(expand: parent ? nested_expands_for(parent) : [])
+ # Build nested params for child serializers with depth limit (max 4 levels)
+ def nested_params(parent)
+ depth = params.fetch(:_expand_depth, 0)
+ nested = depth < 4 ? nested_expands_for(parent) : []
+ params.merge(expand: nested, _expand_depth: depth + 1)
+ end
+
+ private
+
+ # Override Alba's fetch_attribute to automatically inject nested expand params
+ # into child serializers via nested_params
+ def fetch_attribute(obj, key, attribute)
+ if attribute.is_a?(Alba::Association)
+ nested = nested_params(attribute.name)
+ yield_if_within(attribute.name.to_sym) { |within| attribute.to_h(obj, params: nested, within: within) }
+ else
+ super
+ end
end
# Returns price for a variant using full Price List resolution
diff --git a/spree/api/app/serializers/spree/api/v3/product_serializer.rb b/spree/api/app/serializers/spree/api/v3/product_serializer.rb
index 598fd35472..de4924a90b 100644
--- a/spree/api/app/serializers/spree/api/v3/product_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/product_serializer.rb
@@ -71,37 +71,36 @@ module Spree
many :variant_images,
key: :images,
resource: Spree.api.image_serializer,
- if: proc { params[:expand]&.include?('images') }
+ if: proc { expand?('images') }
many :variants,
resource: Spree.api.variant_serializer,
- if: proc { params[:expand]&.include?('variants') }
+ if: proc { expand?('variants') }
one :default_variant,
resource: Spree.api.variant_serializer,
- if: proc { params[:expand]&.include?('default_variant') }
+ if: proc { expand?('default_variant') }
one :master,
key: :master_variant,
resource: Spree.api.variant_serializer,
- if: proc { params[:expand]&.include?('master_variant') }
+ if: proc { expand?('master_variant') }
many :option_types,
resource: Spree.api.option_type_serializer,
- if: proc { params[:expand]&.include?('option_types') }
+ if: proc { expand?('option_types') }
many :taxons,
proc { |taxons, params|
taxons.select { |t| t.taxonomy.store_id == params[:store].id }
},
resource: Spree.api.taxon_serializer,
- if: proc { params[:expand]&.include?('taxons') },
- params: { expand: [] }
+ if: proc { expand?('taxons') }
many :public_metafields,
key: :metafields,
resource: Spree.api.metafield_serializer,
- if: proc { params[:expand]&.include?('metafields') }
+ if: proc { expand?('metafields') }
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/taxon_serializer.rb b/spree/api/app/serializers/spree/api/v3/taxon_serializer.rb
index 6fcaeebf4e..0c7a574999 100644
--- a/spree/api/app/serializers/spree/api/v3/taxon_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/taxon_serializer.rb
@@ -55,23 +55,20 @@ module Spree
# (e.g., ancestors trying to load their own ancestors)
one :parent,
resource: Spree.api.taxon_serializer,
- if: proc { params[:expand]&.include?('parent') },
- params: { expand: [] }
+ if: proc { expand?('parent') }
many :children,
resource: Spree.api.taxon_serializer,
- if: proc { params[:expand]&.include?('children') },
- params: { expand: [] }
+ if: proc { expand?('children') }
many :ancestors,
resource: Spree.api.taxon_serializer,
- if: proc { params[:expand]&.include?('ancestors') },
- params: { expand: [] }
+ if: proc { expand?('ancestors') }
many :public_metafields,
key: :metafields,
resource: Spree.api.metafield_serializer,
- if: proc { params[:expand]&.include?('metafields') }
+ if: proc { expand?('metafields') }
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/taxonomy_serializer.rb b/spree/api/app/serializers/spree/api/v3/taxonomy_serializer.rb
index 9c6d868e80..5d090189f7 100644
--- a/spree/api/app/serializers/spree/api/v3/taxonomy_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/taxonomy_serializer.rb
@@ -15,18 +15,16 @@ module Spree
# Note: We pass empty expand to nested taxons to prevent infinite recursion
one :root,
resource: Spree.api.taxon_serializer,
- if: proc { params[:expand]&.include?('root') },
- params: { expand: [] }
+ if: proc { expand?('root') }
many :taxons,
resource: Spree.api.taxon_serializer,
- if: proc { params[:expand]&.include?('taxons') },
- params: { expand: [] }
+ if: proc { expand?('taxons') }
many :public_metafields,
key: :metafields,
resource: Spree.api.metafield_serializer,
- if: proc { params[:expand]&.include?('metafields') }
+ if: proc { expand?('metafields') }
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/variant_serializer.rb b/spree/api/app/serializers/spree/api/v3/variant_serializer.rb
index fbc888cbc3..d107c2d2ca 100644
--- a/spree/api/app/serializers/spree/api/v3/variant_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/variant_serializer.rb
@@ -72,14 +72,14 @@ module Spree
# Conditional associations
many :images,
resource: Spree.api.image_serializer,
- if: proc { params[:expand]&.include?('images') }
+ if: proc { expand?('images') }
many :option_values, resource: Spree.api.option_value_serializer
many :public_metafields,
key: :metafields,
resource: Spree.api.metafield_serializer,
- if: proc { params[:expand]&.include?('metafields') }
+ if: proc { expand?('metafields') }
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/wishlist_serializer.rb b/spree/api/app/serializers/spree/api/v3/wishlist_serializer.rb
index a0fdb99147..eccd79039a 100644
--- a/spree/api/app/serializers/spree/api/v3/wishlist_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/wishlist_serializer.rb
@@ -18,7 +18,7 @@ module Spree
many :wished_items,
key: :items,
resource: Spree.api.wished_item_serializer,
- if: proc { params[:expand]&.include?('items') }
+ if: proc { expand?('items') }
end
end
end
diff --git a/spree/api/spec/controllers/concerns/spree/api/v3/field_selection_spec.rb b/spree/api/spec/controllers/concerns/spree/api/v3/field_selection_spec.rb
index a68f9c29e3..05f2e4e69e 100644
--- a/spree/api/spec/controllers/concerns/spree/api/v3/field_selection_spec.rb
+++ b/spree/api/spec/controllers/concerns/spree/api/v3/field_selection_spec.rb
@@ -67,7 +67,7 @@ RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller do
expect(data['variants']).to be_an(Array)
end
- it 'excludes expanded associations when not listed in fields' do
+ it 'always includes expanded associations even when not listed in fields' do
get :show, params: {
id: product.prefixed_id,
fields: 'name',
@@ -75,8 +75,8 @@ RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller do
}
data = JSON.parse(response.body)
- expect(data.keys).to contain_exactly('id', 'name')
- expect(data).not_to have_key('variants')
+ expect(data.keys).to contain_exactly('id', 'name', 'variants')
+ expect(data['variants']).to be_an(Array)
end
end
end
diff --git a/spree/api/spec/controllers/concerns/spree/api/v3/nested_expand_spec.rb b/spree/api/spec/controllers/concerns/spree/api/v3/nested_expand_spec.rb
new file mode 100644
index 0000000000..2e16e081b1
--- /dev/null
+++ b/spree/api/spec/controllers/concerns/spree/api/v3/nested_expand_spec.rb
@@ -0,0 +1,90 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Store'
+
+ let!(:product) { create(:product, stores: [store], status: 'active') }
+
+ before do
+ request.headers['X-Spree-Api-Key'] = api_key.token
+ end
+
+ describe 'nested expand (dot notation)' do
+ describe 'single level expand still works' do
+ it 'expands variants' do
+ get :show, params: { id: product.prefixed_id, expand: 'variants' }
+
+ data = JSON.parse(response.body)
+ expect(data).to have_key('variants')
+ expect(data['variants']).to be_an(Array)
+ end
+
+ it 'does not expand variants when not requested' do
+ get :show, params: { id: product.prefixed_id }
+
+ data = JSON.parse(response.body)
+ expect(data).not_to have_key('variants')
+ end
+ end
+
+ describe 'nested expand with dot notation' do
+ it 'expands variants with nested images' do
+ get :show, params: { id: product.prefixed_id, expand: 'variants.images' }
+
+ data = JSON.parse(response.body)
+ expect(data).to have_key('variants')
+ data['variants'].each do |variant|
+ expect(variant).to have_key('images')
+ end
+ end
+
+ it 'expands variants without images when only variants requested' do
+ get :show, params: { id: product.prefixed_id, expand: 'variants' }
+
+ data = JSON.parse(response.body)
+ expect(data).to have_key('variants')
+ data['variants'].each do |variant|
+ expect(variant).not_to have_key('images')
+ end
+ end
+
+ it 'supports multiple nested expands' do
+ get :show, params: { id: product.prefixed_id, expand: 'variants.images,variants.metafields' }
+
+ data = JSON.parse(response.body)
+ expect(data).to have_key('variants')
+ data['variants'].each do |variant|
+ expect(variant).to have_key('images')
+ expect(variant).to have_key('metafields')
+ end
+ end
+
+ it 'supports mixed top-level and nested expands' do
+ get :show, params: { id: product.prefixed_id, expand: 'variants.images,option_types' }
+
+ data = JSON.parse(response.body)
+ expect(data).to have_key('variants')
+ expect(data).to have_key('option_types')
+ data['variants'].each do |variant|
+ expect(variant).to have_key('images')
+ end
+ end
+ end
+
+ describe 'collection endpoint' do
+ it 'supports nested expand on index' do
+ get :index, params: { expand: 'variants.images' }
+
+ data = JSON.parse(response.body)['data']
+ data.each do |product|
+ expect(product).to have_key('variants')
+ product['variants'].each do |variant|
+ expect(variant).to have_key('images')
+ end
+ end
+ end
+ end
+ end
+end