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.

Added ability to extend SDK plus improved documentation and tutorial (#13913)

Damian Legawiec3cd0bd79bb2a
diff --git a/docs/developer/customization/api.mdx b/docs/developer/customization/api.mdx
index 8913588c45..81ce80b78f 100644
--- a/docs/developer/customization/api.mdx
+++ b/docs/developer/customization/api.mdx
@@ -1,97 +1,193 @@
---
title: API
description: >-
- This page covers adding new Spree API endpoints and customization of
- existing ones
+ Add new Store API endpoints and customize existing API responses
---
Before you start customizing Spree API endpoints, make sure you reviewed all existing API endpoints in the [Spree API docs](/api-reference).
-## Customizing JSON response
+For a step-by-step walkthrough of adding a complete new resource (model, serializer, controller, routes), see the [Store API tutorial](/developer/tutorial/store-api).
-Spree uses a library called [JSON API serializers](https://github.com/jsonapi-serializer/jsonapi-serializer) to represent data returned by API endpoints.
+## Customizing JSON Responses
-You can easily replace existing Spree serializers with your own thanks to [Spree Dependencies](dependencies). Here's a list of all serializers that you can override:
+Spree uses [Alba](https://github.com/okuramasafumi/alba) serializers to build API v3 responses. You can replace any serializer via [Spree Dependencies](dependencies).
-| Key | Value |
-|------------------------------------------|-----------------------------------------------------|
-| `storefront_address_serializer` | [Spree::V2::Storefront::AddressSerializer](https://github.com/spree/spree/blob/main/api/app/serializers/spree/v2/storefront/address_serializer.rb) |
-| `storefront_cart_serializer` | [Spree::V2::Storefront::CartSerializer](https://github.com/spree/spree/blob/main/api/app/serializers/spree/v2/storefront/cart_serializer.rb) |
-| `storefront_credit_card_serializer` | [Spree::V2::Storefront::CreditCardSerializer](https://github.com/spree/spree/blob/main/api/app/serializers/spree/v2/storefront/credit_card_serializer.rb) |
-| `storefront_country_serializer` | [Spree::V2::Storefront::CountrySerializer](https://github.com/spree/spree/blob/main/api/app/serializers/spree/v2/storefront/country_serializer.rb) |
-| `storefront_user_serializer` | [Spree::V2::Storefront::UserSerializer](https://github.com/spree/spree/blob/main/api/app/serializers/spree/v2/storefront/user_serializer.rb) |
-| `storefront_shipment_serializer` | [Spree::V2::Storefront::ShipmentSerializer](https://github.com/spree/spree/blob/main/api/app/serializers/spree/v2/storefront/shipment_serializer.rb) |
-| `storefront_taxon_serializer` | [Spree::V2::Storefront::TaxonSerializer](https://github.com/spree/spree/blob/main/api/app/serializers/spree/v2/storefront/taxon_serializer.rb) |
-| `storefront_payment_method_serializer` | [Spree::V2::Storefront::PaymentMethodSerializer](https://github.com/spree/spree/blob/main/api/app/serializers/spree/v2/storefront/payment_method_serializer.rb) |
-| `storefront_payment_serializer` | [Spree::V2::Storefront::PaymentSerializer](https://github.com/spree/spree/blob/main/api/app/serializers/spree/v2/storefront/payment_serializer.rb) |
-| `storefront_product_serializer` | [Spree::V2::Storefront::ProductSerializer](https://github.com/spree/spree/blob/main/api/app/serializers/spree/v2/storefront/product_serializer.rb) |
-| `storefront_estimated_shipment_serializer` | [Spree::V2::Storefront::EstimatedShippingRateSerializer](https://github.com/spree/spree/blob/main/api/app/serializers/spree/v2/storefront/estimated_shipping_rate_serializer.rb) |
-| `storefront_store_serializer` | [Spree::V2::Storefront::StoreSerializer](https://github.com/spree/spree/blob/main/api/app/serializers/spree/v2/storefront/store_serializer.rb) |
-| `storefront_order_serializer` | [Spree::V2::Storefront::OrderSerializer](https://github.com/spree/spree/blob/main/api/app/serializers/spree/v2/storefront/order_serializer.rb) |
-| `storefront_variant_serializer` | [Spree::V2::Storefront::VariantSerializer](https://github.com/spree/spree/blob/main/api/app/serializers/spree/v2/storefront/variant_serializer.rb) |
+### Adding Custom Attributes
-### Adding custom attributes
+Let's say you want to add a `my_custom_attribute` column to the Product API response.
-<Note>
-As a rule of thumb it's recommended to use [Properties](/developer/core-concepts/products#product-properties) and [OptionTypes/Option Values](/developer/core-concepts/products#option-types-and-option-values) for custom attributes and not to modify the Spree database schema
-</Note>
+Create a custom serializer that inherits from the core one:
-Let's say you want to customize the Storefront API's [Product serializer](https://github.com/spree/spree/blob/main/api/app/serializers/spree/v2/storefront/product_serializer.rb) to include you custom database column `my_newcustom_attribute` that you've added to the `spree_products` database table.
+```ruby app/serializers/my_app/product_serializer.rb
+module MyApp
+ class ProductSerializer < Spree::Api::V3::ProductSerializer
+ attribute :my_custom_attribute
+ end
+end
+```
-Let's start with creating a new serializer file:
+Register it in `config/initializers/spree.rb`:
-```bash
-mkdir -p app/serializers && touch app/serializers/my_product_serializer.rb
+```ruby
+Spree::Api::Dependencies.product_serializer = 'MyApp::ProductSerializer'
```
-Place the following code in your new serializer file:
+Restart the server and the Product API will include your new attribute.
-```ruby
-class MyProductSerializer < Spree::V2::Storefront::ProductSerializer
- attribute :my_new_custom_attribute
+### Adding an Association
+
+Let's say you've created a `Spree::Brand` model that belongs to `Product` (see the [tutorial](/developer/tutorial/store-api) for the full example).
+
+Create a serializer for the new model:
+
+```ruby app/serializers/spree/api/v3/brand_serializer.rb
+module Spree
+ module Api
+ module V3
+ class BrandSerializer < BaseSerializer
+ typelize name: :string, slug: [:string, nullable: true]
+
+ attributes :name, :slug
+ end
+ end
+ end
end
```
-<Info>
-This serializer will inherit from the `Spree::V2::Storefront::ProductSerializer` serializer, so you don't need to rewrite the whole serializer.
-</Info>
+Then subclass the Product serializer to include the brand association:
-Now let's tell Spree to use this new serializer, in `config/initializers/spree.rb` please set:
+```ruby app/serializers/my_app/product_serializer.rb
+module MyApp
+ class ProductSerializer < Spree::Api::V3::ProductSerializer
+ typelize brand_id: [:string, nullable: true]
-```ruby
-Spree::Api::Dependencies.storefront_product_serializer = 'MyProductSerializer'
+ attribute :brand_id do |product|
+ product.brand&.prefixed_id
+ end
+
+ one :brand,
+ resource: Spree::Api::V3::BrandSerializer,
+ if: proc { expand?('brand') }
+ end
+end
```
-Restart the webserver and hit the [Products API](/api-reference/storefront/products/list-all-products) to notice that the payload now includes your new attribute.
+Register it in `config/initializers/spree.rb`:
-### Adding a new association
+```ruby
+Spree::Api::Dependencies.product_serializer = 'MyApp::ProductSerializer'
+```
-Let's say you've created a new model called `Video` that belongs to `Product` (_Product has multiple Videos_).
+The brand data is available via `?expand=brand`:
-Let's create a new serializer `app/serializers/video_serializer.rb`:
+```
+GET /api/v3/store/products/prod_86Rf07xd4z?expand=brand
+```
-```ruby
-class VideoSerializer < Spree::Api::V2::BaseSerializer
- set_type: :video
-
- attributes :url
+### Serializer Dependency Keys
+
+Here are the most commonly customized v3 serializers:
+
+| Key | Default |
+|-----|---------|
+| `product_serializer` | `Spree::Api::V3::ProductSerializer` |
+| `variant_serializer` | `Spree::Api::V3::VariantSerializer` |
+| `cart_serializer` | `Spree::Api::V3::CartSerializer` |
+| `order_serializer` | `Spree::Api::V3::OrderSerializer` |
+| `line_item_serializer` | `Spree::Api::V3::LineItemSerializer` |
+| `category_serializer` | `Spree::Api::V3::CategorySerializer` |
+| `customer_serializer` | `Spree::Api::V3::CustomerSerializer` |
+| `address_serializer` | `Spree::Api::V3::AddressSerializer` |
+| `payment_serializer` | `Spree::Api::V3::PaymentSerializer` |
+| `fulfillment_serializer` | `Spree::Api::V3::FulfillmentSerializer` |
+
+See `Spree::Api::ApiDependencies` for the full list.
+
+## Adding New Endpoints
+
+### Controller
+
+Inherit from `Spree::Api::V3::Store::ResourceController` for Store API endpoints:
+
+```ruby app/controllers/spree/api/v3/store/brands_controller.rb
+module Spree
+ module Api
+ module V3
+ module Store
+ class BrandsController < ResourceController
+ protected
+
+ def model_class
+ Spree::Brand
+ end
+
+ def serializer_class
+ Spree::Api::V3::BrandSerializer
+ end
+
+ def scope
+ Spree::Brand.all
+ end
+ end
+ end
+ end
+ end
end
```
-Now in your `app/serializers/my_product_serializer.rb`
+The base `ResourceController` provides:
+
+| Feature | How |
+|---------|-----|
+| Pagination | [Pagy](https://github.com/ddnexus/pagy) — `?page=2&limit=25` |
+| Filtering | [Ransack](https://github.com/activerecord-hackery/ransack) — `?q[name_cont]=nike` |
+| Sorting | JSON:API style — `?sort=-name` |
+| Authorization | [CanCanCan](https://github.com/CanCanCommunity/cancancan) |
+| Prefixed IDs | Stripe-style — `brand_k5nR8xLq` |
+
+Override these methods to customize:
+
+| Method | Purpose |
+|--------|---------|
+| `model_class` | ActiveRecord model (required) |
+| `serializer_class` | Alba serializer (required) |
+| `scope` | Base query — add `.where()` to filter |
+| `find_resource` | Custom ID lookup (slug fallback, etc.) |
+| `permitted_params` | Custom strong params |
+| `collection_includes` | Eager loading for `index` |
+
+### Routes
+
+Add routes in your app's `config/routes.rb`:
```ruby
-class MyProductSerializer < Spree::V2::Storefront::ProductSerializer
- attribute :my_new_custom_attribute
-
- has_many :videos, serializer: :video
+Spree::Core::Engine.add_routes do
+ namespace :api, defaults: { format: 'json' } do
+ namespace :v3 do
+ namespace :store do
+ resources :brands, only: [:index, :show]
+ end
+ end
+ end
end
```
-Hitting the Products API you will notice that in the [relationships](https://jsonapi.org/format/#document-resource-object-relationships) key there will be a new key called `videos`
+### Permitted Attributes
-To include Video response in the Product API add `?includes=videos` in the API URL, eg.
+For endpoints that accept writes (create/update), add your attributes:
-```http
-GET https://localhost:3000/api/v2/storefront/products?include=videos
+```ruby config/initializers/spree.rb
+Spree::PermittedAttributes.brand_attributes = [:name, :slug, :description, :logo]
```
+
+Or override `permitted_params` in the controller:
+
+```ruby
+def permitted_params
+ params.permit(:name, :slug, :description, :logo)
+end
+```
+
+## Consuming Custom Endpoints with the SDK
+
+See the [SDK tutorial](/developer/tutorial/sdk) for how to call custom endpoints from TypeScript and extend the generated types.
diff --git a/docs/developer/sdk/extending.mdx b/docs/developer/sdk/extending.mdx
new file mode 100644
index 0000000000..604961237b
--- /dev/null
+++ b/docs/developer/sdk/extending.mdx
@@ -0,0 +1,33 @@
+---
+title: Custom Endpoints
+sidebarTitle: Custom Endpoints
+description: Call custom Store API endpoints using the SDK's built-in request method
+---
+
+The client exposes a `request` method — the same function that powers all built-in resources. Use it to call any Store API endpoint, including ones you've added yourself.
+
+```typescript
+import { createClient } from '@spree/sdk'
+import type { PaginatedResponse } from '@spree/sdk'
+
+const client = createClient({
+ baseUrl: 'https://api.mystore.com',
+ publishableKey: 'pk_YOUR_KEY',
+})
+
+interface Brand {
+ id: string
+ name: string
+ slug: string | null
+ description: string | null
+ logo_url: string | null
+}
+
+// Paths are relative to /api/v3/store
+const brands = await client.request<PaginatedResponse<Brand>>('GET', '/brands')
+const nike = await client.request<Brand>('GET', '/brands/nike')
+```
+
+`client.request` uses the same auth headers, retry logic, and locale/currency defaults as `client.products.list()` or any other built-in resource.
+
+For a complete walkthrough — creating the API endpoints on the backend, defining TypeScript types, filtering, and expanding associations — see the [Store API](/developer/tutorial/store-api) and [SDK](/developer/tutorial/sdk) tutorials.
diff --git a/docs/developer/tutorial/extending-models.mdx b/docs/developer/tutorial/extending-models.mdx
index 7257d0a5a2..f5485b232c 100644
--- a/docs/developer/tutorial/extending-models.mdx
+++ b/docs/developer/tutorial/extending-models.mdx
@@ -389,10 +389,19 @@ Spree::PermittedAttributes.product_attributes << :brand_id
</Tab>
</Tabs>
+## Next Step
+
+Now that Brands are connected to Products, let's expose them through the Store API:
+
+<Card title="6. Store API" icon="code" href="/developer/tutorial/store-api">
+ Create API endpoints for brands and extend the Product API response
+</Card>
+
## Related Documentation
- [Model Tutorial](/developer/tutorial/model) - Creating the Brand model
- [Admin Tutorial](/developer/tutorial/admin) - Building the admin interface
+- [Store API Tutorial](/developer/tutorial/store-api) - Exposing brands through the API
- [Events](/developer/core-concepts/events) - Subscribe to model changes without decorators
- [Webhooks](/developer/core-concepts/webhooks) - HTTP callbacks for external integrations
- [Decorators](/developer/customization/decorators) - Full decorator reference
diff --git a/docs/developer/tutorial/introduction.mdx b/docs/developer/tutorial/introduction.mdx
index 9551c19c63..290c601704 100644
--- a/docs/developer/tutorial/introduction.mdx
+++ b/docs/developer/tutorial/introduction.mdx
@@ -1,10 +1,10 @@
---
title: Tutorial
sidebarTitle: Introduction
-description: Learn how to build a custom feature from scratch, covering models, Admin dashboard, API and Storefront.
+description: Learn how to build a custom feature from scratch, covering models, Admin dashboard and API.
---
-This tutorial walks you through creating a complete Spree feature from scratch, covering models, Admin dashboard and API.
+This tutorial walks you through creating a complete Spree feature from scratch, covering models, Admin dashboard, Store API, and TypeScript SDK integration.
You will also learn how to extend core Spree features to connect them with your new feature.
By the end, you'll understand how to add new manageable features to the Spree platform.
@@ -14,7 +14,8 @@ To fully implement a new feature, you will typically create the following compon
* Database model
* Admin Dashboard controllers and views
-* Storefront views
+* Store API endpoints and serializers
+* TypeScript SDK integration
* Automated tests
## Tutorial Sections
@@ -35,7 +36,13 @@ To fully implement a new feature, you will typically create the following compon
<Card title="5. Extending Core Models" icon="plug" href="/developer/tutorial/extending-models">
Connect Brands to Products using associations
</Card>
- <Card title="7. Testing" icon="flask-vial" href="/developer/tutorial/testing">
+ <Card title="6. Store API" icon="code" href="/developer/tutorial/store-api">
+ Expose Brands through the Store API with serializers, controllers, and routes
+ </Card>
+ <Card title="7. SDK" icon="js" href="/developer/tutorial/sdk">
+ Consume Brand endpoints from TypeScript using the SDK
+ </Card>
+ <Card title="8. Testing" icon="flask-vial" href="/developer/tutorial/testing">
Write automated tests for your feature
</Card>
</CardGroup>
diff --git a/docs/developer/tutorial/sdk.mdx b/docs/developer/tutorial/sdk.mdx
new file mode 100644
index 0000000000..e1cc386b08
--- /dev/null
+++ b/docs/developer/tutorial/sdk.mdx
@@ -0,0 +1,173 @@
+---
+title: SDK
+description: Use the TypeScript SDK to consume your custom Brand endpoints and extended Product data
+---
+
+In this tutorial, we'll use the `@spree/sdk` TypeScript SDK to consume the Brand API endpoints we created in the [Store API tutorial](/developer/tutorial/store-api), and work with the extended Product data that now includes brand information.
+
+<Info>
+ This guide assumes you've completed the [Store API](/developer/tutorial/store-api) tutorial and have the Brand endpoints running.
+</Info>
+
+## What We're Building
+
+By the end of this tutorial, you'll have:
+
+- Typed calls to your custom Brand endpoints using `client.request`
+- Extended Product types that include brand data
+- A working brand page example that ties it all together
+
+## How the SDK Works
+
+The `@spree/sdk` package provides a typed client for the Store API:
+
+```typescript
+import { createClient } from '@spree/sdk'
+
+const client = createClient({
+ baseUrl: 'https://api.mystore.com',
+ publishableKey: 'pk_YOUR_KEY',
+})
+
+// Built-in resources
+const products = await client.products.list()
+const product = await client.products.get('prod_86Rf07xd4z')
+const cart = await client.carts.create()
+```
+
+Under the hood, `createClient()` creates a request function that handles auth headers (`x-spree-api-key`), retries with exponential backoff, and URL building. All requests go through the base path `/api/v3/store`, so `client.products.list()` calls `GET /api/v3/store/products`.
+
+## Calling Custom Endpoints
+
+The client exposes a `request` method — the same function that powers all built-in resources. Use it to call any Store API endpoint, including custom ones:
+
+```typescript
+import { createClient } from '@spree/sdk'
+import type { PaginatedResponse } from '@spree/sdk'
+
+const client = createClient({
+ baseUrl: 'https://api.mystore.com',
+ publishableKey: 'pk_YOUR_KEY',
+})
+
+// Define your Brand type
+interface Brand {
+ id: string
+ name: string
+ slug: string | null
+ description: string | null
+ logo_url: string | null
+}
+
+// Call custom endpoints — paths are relative to /api/v3/store
+const brands = await client.request<PaginatedResponse<Brand>>('GET', '/brands')
+const nike = await client.request<Brand>('GET', '/brands/nike')
+```
+
+`client.request` has the same auth headers, retry logic, and locale/currency defaults as all built-in resources. The type parameter (`<Brand>`, `<PaginatedResponse<Brand>>`) gives you full type safety on the response.
+
+## Step 1: Define Brand Types
+
+Create a types file for your custom Brand resource:
+
+```typescript types/brand.ts
+import type { Product, PaginatedResponse } from '@spree/sdk'
+
+export interface Brand {
+ id: string
+ name: string
+ slug: string | null
+ description: string | null
+ logo_url: string | null
+}
+
+export interface ProductWithBrand extends Product {
+ brand_id: string | null
+ brand?: Brand
+}
+```
+
+## Step 2: Work with Extended Product Responses
+
+The Product serializer now includes `brand_id` and an expandable `brand` association.
+
+### Fetching Products with Brand Data
+
+```typescript
+import type { ProductWithBrand } from './types/brand'
+
+// Without expand — brand_id is included, brand object is not
+const product = await client.products.get('prod_86Rf07xd4z') as ProductWithBrand
+console.log(product.brand_id) // "brand_k5nR8xLq"
+console.log(product.brand) // undefined
+
+// With expand — full brand object included
+const productWithBrand = await client.products.get(
+ 'prod_86Rf07xd4z',
+ { expand: ['brand'] }
+) as ProductWithBrand
+console.log(productWithBrand.brand?.name) // "Nike"
+
+// Multiple expands
+const full = await client.products.get(
+ 'prod_86Rf07xd4z',
+ { expand: ['brand', 'variants', 'categories'] }
+) as ProductWithBrand
+```
+
+### Filtering Products by Brand
+
+Ransack predicates work on whitelisted attributes and associations. The [Store API tutorial](/developer/tutorial/store-api) shows how to register `brand_id` and `brand` via `Spree.ransack` — once that's done, you can filter:
+
+```typescript
+// Products from a specific brand
+const nikeProducts = await client.products.list({
+ brand_id_eq: 'brand_k5nR8xLq',
+})
+
+// Products matching brand name (requires Spree.ransack.add_association)
+const nikeProducts2 = await client.products.list({
+ brand_name_cont: 'nike',
+})
+```
+
+<Info>
+ Ransack predicates like `_eq`, `_cont`, `_gt`, `_lt` work on whitelisted attributes and associations. See [Search & Filtering](/developer/core-concepts/search-filtering) for the full list.
+</Info>
+
+## Complete Example: Brand Page
+
+A real-world example combining everything — fetch a brand by slug and list its products:
+
+```typescript
+import { createClient } from '@spree/sdk'
+import type { PaginatedResponse } from '@spree/sdk'
+import type { Brand, ProductWithBrand } from './types/brand'
+
+const client = createClient({
+ baseUrl: 'https://api.mystore.com',
+ publishableKey: 'pk_YOUR_KEY',
+})
+
+// Fetch brand by slug
+const brand = await client.request<Brand>('GET', '/brands/nike')
+
+// Fetch products for this brand
+const products = await client.products.list({
+ brand_id_eq: brand.id,
+ sort: '-available_on',
+}) as PaginatedResponse<ProductWithBrand>
+
+// Render
+console.log(`${brand.name} — ${brand.description}`)
+console.log(`${products.meta.count} products`)
+products.data.forEach(p => {
+ console.log(` ${p.name} — ${p.price.display}`)
+})
+```
+
+## Related Documentation
+
+- [Store API Tutorial](/developer/tutorial/store-api) - Creating the Brand API endpoints
+- [SDK Overview](/sdk) - Full SDK documentation
+- [Search & Filtering](/developer/core-concepts/search-filtering) - Ransack predicates and sorting
diff --git a/docs/developer/tutorial/store-api.mdx b/docs/developer/tutorial/store-api.mdx
new file mode 100644
index 0000000000..dbed0da3d1
--- /dev/null
+++ b/docs/developer/tutorial/store-api.mdx
@@ -0,0 +1,507 @@
+---
+title: Store API
+description: Expose your Brand model through the Store API with serializers, controllers, and routes
+---
+
+In this tutorial, we'll create Store API endpoints for our Brand model so that storefronts can list and display brands. We'll also extend the existing Product serializer to include brand data.
+
+<Info>
+ This guide assumes you've completed the [Model](/developer/tutorial/model), [Admin](/developer/tutorial/admin), and [Extending Core Models](/developer/tutorial/extending-models) tutorials.
+</Info>
+
+## What We're Building
+
+By the end of this tutorial, you'll have:
+
+- `GET /api/v3/store/brands` — list all brands
+- `GET /api/v3/store/brands/:id` — get a single brand by prefixed ID or slug
+- Brand data included in Product responses via `?expand=brand`
+- Understanding of how to add new API endpoints and extend existing serializers
+
+## How the Store API Works
+
+Every Store API endpoint follows the same pattern:
+
+1. **Controller** inherits from `Spree::Api::V3::Store::ResourceController` which provides CRUD, pagination, Ransack filtering, and authorization out of the box
+2. **Serializer** inherits from `Spree::Api::V3::BaseSerializer` (uses [Alba](https://github.com/okuramasafumi/alba)) and defines which fields to return
+3. **Routes** are added via `Spree::Core::Engine.add_routes`
+4. **Serializer registration** via `Spree::Api::Dependencies` enables dependency injection so serializers can be swapped by extensions or the host app
+
+## Step 1: Prepare the Brand Model for the API
+
+Store API requires two things from models:
+
+1. **Prefixed IDs** — Stripe-style IDs like `brand_k5nR8xLq` instead of raw database IDs
+2. **Slugs** — human-readable URL identifiers like `nike` for `GET /brands/nike`
+
+First, add a `slug` column if you haven't already:
+
+```bash
+bin/rails g migration AddSlugToSpreeBrands slug:string:uniq
+bin/rails db:migrate
+```
+
+Then update the Brand model with `PrefixedId` and `FriendlyId`:
+
+```ruby app/models/spree/brand.rb {3-7}
+module Spree
+ class Brand < Spree::Base
+ include Spree::PrefixedId
+ extend FriendlyId
+
+ has_prefix_id :brand
+ friendly_id :slug_candidates, use: [:slugged, :scoped], scope: spree_base_uniqueness_scope
+
+ has_many :products, class_name: 'Spree::Product', dependent: :nullify
+
+ has_one_attached :logo
+ has_rich_text :description
+
+ validates :name, presence: true
+ end
+end
+```
+
+Now:
+- `Spree::Brand.first.prefixed_id` returns `brand_k5nR8xLq`
+- `Spree::Brand.find_by_prefix_id!('brand_k5nR8xLq')` finds by prefixed ID
+- `Spree::Brand.friendly.find('nike')` finds by slug
+- Slugs are auto-generated from the `name` via `slug_candidates` (inherited from `Spree::Base`)
+
+## Step 2: Create the Serializer
+
+Create a serializer that defines the JSON response shape for brands:
+
+```ruby app/serializers/spree/api/v3/brand_serializer.rb
+module Spree
+ module Api
+ module V3
+ class BrandSerializer < BaseSerializer
+ typelize name: :string,
+ slug: [:string, nullable: true],
+ description: [:string, nullable: true],
+ logo_url: [:string, nullable: true]
+
+ attributes :name, :slug
+
+ attribute :description do |brand|
+ brand.description&.to_plain_text
+ end
+
+ attribute :logo_url do |brand|
+ image_url_for(brand.logo) if brand.logo.attached?
+ end
+ end
+ end
+ end
+end
+```
+
+### Understanding the Serializer
+
+- **`BaseSerializer`** automatically converts `id` to a prefixed ID and provides context helpers (`current_store`, `current_currency`, etc.)
+- **`typelize`** provides type hints used by [Typelizer](https://github.com/skryukov/typelizer) to auto-generate TypeScript types for the SDK
+- **`attributes`** lists database columns to include directly
+- **`attribute ... do`** blocks define computed fields (like stripping HTML from rich text, or generating image URLs)
+
+## Step 3: Create the Controller
+
+Create a controller that inherits from `Store::ResourceController`:
+
+```ruby app/controllers/spree/api/v3/store/brands_controller.rb
+module Spree
+ module Api
+ module V3
+ module Store
+ class BrandsController < ResourceController
+ protected
+
+ def model_class
+ Spree::Brand
+ end
+
+ def serializer_class
+ Spree::Api::V3::BrandSerializer
+ end
+
+ def scope
+ Spree::Brand.all
+ end
+ end
+ end
+ end
+ end
+end
+```
+
+### Understanding the Controller
+
+`ResourceController` gives you `index` and `show` actions automatically. You only need to define:
+
+| Method | Purpose |
+|--------|---------|
+| `model_class` | Which ActiveRecord model to query |
+| `serializer_class` | Which serializer to render responses with |
+| `scope` | Base query scope (add `.where(...)` to filter) |
+
+The base controller handles:
+- **Pagination** via [Pagy](https://github.com/ddnexus/pagy) (`?page=2&limit=25`)
+- **Filtering** via [Ransack](https://github.com/activerecord-hackery/ransack) (`?q[name_cont]=nike`)
+- **Sorting** via JSON:API style (`?sort=-name` for descending)
+- **Authorization** via [CanCanCan](https://github.com/CanCanCommunity/cancancan)
+- **Prefixed ID lookup** for `show` action (`/brands/brand_k5nR8xLq`)
+
+<Info>
+ For core models, controllers use `Spree.api.product_serializer` which looks up the serializer from `Spree::Api::Dependencies`. This allows extensions to swap the serializer. For your own custom models, reference the serializer class directly — the dependency system only supports core injection points.
+</Info>
+
+### Adding Slug Lookup
+
+To also support fetching brands by slug (like products support `/products/blue-t-shirt`), override `find_resource`:
+
+```ruby app/controllers/spree/api/v3/store/brands_controller.rb {12-19}
+module Spree
+ module Api
+ module V3
+ module Store
+ class BrandsController < ResourceController
+ protected
+
+ def model_class
+ Spree::Brand
+ end
+
+ def find_resource
+ id = params[:id]
+ if id.to_s.start_with?('brand_')
+ scope.find_by_prefix_id!(id)
+ else
+ scope.friendly.find(id)
+ end
+ end
+
+ def serializer_class
+ Spree::Api::V3::BrandSerializer
+ end
+
+ def scope
+ Spree::Brand.all
+ end
+ end
+ end
+ end
+ end
+end
+```
+
+## Step 4: Add Routes
+
+Add the routes for your new endpoints:
+
+```ruby config/routes.rb
+Spree::Core::Engine.add_routes do
+ namespace :api, defaults: { format: 'json' } do
+ namespace :v3 do
+ namespace :store do
+ resources :brands, only: [:index, :show]
+ end
+ end
+ end
+end
+```
+
+This creates:
+- `GET /api/v3/store/brands` — paginated list with filtering/sorting
+- `GET /api/v3/store/brands/:id` — single brand by prefixed ID or slug
+
+## Step 5: Test the Endpoints
+
+Restart your server and test:
+
+```bash
+# List brands
+curl -H "X-Spree-API-Key: pk_YOUR_KEY" \
+ http://localhost:3000/api/v3/store/brands
+
+# Get a single brand
+curl -H "X-Spree-API-Key: pk_YOUR_KEY" \
+ http://localhost:3000/api/v3/store/brands/brand_k5nR8xLq
+
+# Filter by name
+curl -H "X-Spree-API-Key: pk_YOUR_KEY" \
+ "http://localhost:3000/api/v3/store/brands?q[name_cont]=nike"
+
+# Sort alphabetically
+curl -H "X-Spree-API-Key: pk_YOUR_KEY" \
+ "http://localhost:3000/api/v3/store/brands?sort=name"
+```
+
+### Response Format
+
+List response:
+
+```json
+{
+ "data": [
+ {
+ "id": "brand_k5nR8xLq",
+ "name": "Nike",
+ "slug": "nike",
+ "description": "Just Do It",
+ "logo_url": "https://cdn.example.com/brands/nike-logo.png"
+ }
+ ],
+ "meta": {
+ "page": 1,
+ "limit": 25,
+ "count": 42,
+ "pages": 2,
+ "from": 1,
+ "to": 25,
+ "in": 25,
+ "previous": null,
+ "next": 2
+ }
+}
+```
+
+## Step 6: Add Brand to Product Responses
+
+Now let's extend the Product serializer so that brand data is included when a storefront requests `?expand=brand`.
+
+### Create a Custom Product Serializer
+
+Subclass the core `ProductSerializer` and add brand fields. Then swap it in via Dependencies:
+
+```ruby app/serializers/my_app/product_serializer.rb
+module MyApp
+ class ProductSerializer < Spree::Api::V3::ProductSerializer
+ typelize brand_id: [:string, nullable: true]
+
+ attribute :brand_id do |product|
+ product.brand&.prefixed_id
+ end
+
+ one :brand,
+ resource: Spree::Api::V3::BrandSerializer,
+ if: proc { expand?('brand') }
+ end
+end
+```
+
+Register it and whitelist the brand association for Ransack filtering in your initializer:
+
+```ruby config/initializers/spree.rb
+# Swap in custom product serializer with brand support
+Spree::Api::Dependencies.product_serializer = 'MyApp::ProductSerializer'
+
+# Allow filtering products by brand (e.g., ?q[brand_name_cont]=nike or ?q[brand_id_eq]=123)
+Spree.ransack.add_attribute(Spree::Product, :brand_id)
+Spree.ransack.add_association(Spree::Product, :brand)
+```
+
+<Warning>
+ Without `Spree.ransack.add_association`, Ransack predicates like `brand_name_cont` will be silently ignored. Spree whitelists ransackable attributes and associations on each model — custom ones must be registered explicitly.
+</Warning>
+
+### Understanding the Serializer
+
+- **`brand_id`** — always included as a flat attribute (prefixed ID string), so storefronts know which brand a product belongs to without expanding
+- **`one :brand`** — conditionally included when the client requests `?expand=brand`, returns the full brand object inline
+- **`expand?('brand')`** — checks if the `expand` query parameter includes `'brand'`
+
+<Info>
+ We subclass and swap via `Spree::Api::Dependencies` rather than using a decorator. This is the recommended pattern for customizing core serializers — it's explicit, easy to test, and other extensions can further subclass your serializer.
+</Info>
+
+### How Expand Works
+
+The expand system keeps responses lean by default and lets clients opt-in to nested data:
+
+```bash
+# Without expand — brand_id only
+GET /api/v3/store/products/prod_86Rf07xd4z
+
+# With expand — full brand object included
+GET /api/v3/store/products/prod_86Rf07xd4z?expand=brand
+
+# Multiple expands
+GET /api/v3/store/products/prod_86Rf07xd4z?expand=brand,variants,categories
+```
+
+Response with `?expand=brand`:
+
+```json
+{
+ "id": "prod_86Rf07xd4z",
+ "name": "Air Max 90",
+ "brand_id": "brand_k5nR8xLq",
+ "brand": {
+ "id": "brand_k5nR8xLq",
+ "name": "Nike",
+ "slug": "nike",
+ "description": "Just Do It",
+ "logo_url": "https://cdn.example.com/brands/nike-logo.png"
+ }
+}
+```
+
+## Extending Core Serializers (General Pattern)
+
+The pattern we used for Product works for any core serializer. Subclass the core serializer, add your fields, and swap it in via `Spree::Api::Dependencies`:
+
+```ruby app/serializers/my_app/product_serializer.rb
+module MyApp
+ class ProductSerializer < Spree::Api::V3::ProductSerializer
+ attribute :my_field do |product|
+ product.my_field
+ end
+ end
+end
+```
+
+```ruby config/initializers/spree.rb
+Spree::Api::Dependencies.product_serializer = 'MyApp::ProductSerializer'
+```
+
+This works for any core serializer registered in Dependencies (see `Spree::Api::ApiDependencies` for the full list). Your subclass inherits all existing attributes and associations, and other extensions can further subclass yours.
+
+## Complete Files
+
+### Brand Model
+
+```ruby app/models/spree/brand.rb
+module Spree
+ class Brand < Spree::Base
+ include Spree::PrefixedId
+ extend FriendlyId
+
+ has_prefix_id :brand
+ friendly_id :slug_candidates, use: [:slugged, :scoped], scope: spree_base_uniqueness_scope
+
+ has_many :products, class_name: 'Spree::Product', dependent: :nullify
+
+ has_one_attached :logo
+ has_rich_text :description
+
+ validates :name, presence: true
+ end
+end
+```
+
+### Brand Serializer
+
+```ruby app/serializers/spree/api/v3/brand_serializer.rb
+module Spree
+ module Api
+ module V3
+ class BrandSerializer < BaseSerializer
+ typelize name: :string,
+ slug: [:string, nullable: true],
+ description: [:string, nullable: true],
+ logo_url: [:string, nullable: true]
+
+ attributes :name, :slug
+
+ attribute :description do |brand|
+ brand.description&.to_plain_text
+ end
+
+ attribute :logo_url do |brand|
+ image_url_for(brand.logo) if brand.logo.attached?
+ end
+ end
+ end
+ end
+end
+```
+
+### Brands Controller
+
+```ruby app/controllers/spree/api/v3/store/brands_controller.rb
+module Spree
+ module Api
+ module V3
+ module Store
+ class BrandsController < ResourceController
+ protected
+
+ def model_class
+ Spree::Brand
+ end
+
+ def find_resource
+ id = params[:id]
+ if id.to_s.start_with?('brand_')
+ scope.find_by_prefix_id!(id)
+ else
+ scope.friendly.find(id)
+ end
+ end
+
+ def serializer_class
+ Spree::Api::V3::BrandSerializer
+ end
+
+ def scope
+ Spree::Brand.all
+ end
+ end
+ end
+ end
+ end
+end
+```
+
+### Custom Product Serializer
+
+```ruby app/serializers/my_app/product_serializer.rb
+module MyApp
+ class ProductSerializer < Spree::Api::V3::ProductSerializer
+ typelize brand_id: [:string, nullable: true]
+
+ attribute :brand_id do |product|
+ product.brand&.prefixed_id
+ end
+
+ one :brand,
+ resource: Spree::Api::V3::BrandSerializer,
+ if: proc { expand?('brand') }
+ end
+end
+```
+
+### Routes
+
+```ruby config/routes.rb
+Spree::Core::Engine.add_routes do
+ namespace :api, defaults: { format: 'json' } do
+ namespace :v3 do
+ namespace :store do
+ resources :brands, only: [:index, :show]
+ end
+ end
+ end
+end
+```
+
+### Initializer
+
+```ruby config/initializers/spree.rb
+# Permit brand_id in product params (from Extending Core Models tutorial)
+Spree::PermittedAttributes.product_attributes << :brand_id
+
+# Swap in custom product serializer with brand support
+Spree::Api::Dependencies.product_serializer = 'MyApp::ProductSerializer'
+
+# Allow filtering products by brand via Ransack
+Spree.ransack.add_attribute(Spree::Product, :brand_id)
+Spree.ransack.add_association(Spree::Product, :brand)
+```
+
+## Related Documentation
+
+- [Extending Core Models](/developer/tutorial/extending-models) - Adding the Brand association to Product
+- [Using Brands with the SDK](/developer/tutorial/sdk) - Consuming brand endpoints from TypeScript
+- [Decorators](/developer/customization/decorators) - Full decorator reference
+- [Dependencies](/developer/customization/dependencies) - Swapping services and serializers
diff --git a/docs/developer/tutorial/testing.mdx b/docs/developer/tutorial/testing.mdx
index 536e7a8c01..99ec6f663e 100644
--- a/docs/developer/tutorial/testing.mdx
+++ b/docs/developer/tutorial/testing.mdx
@@ -5,7 +5,7 @@ Spree uses [RSpec](https://rspec.info), [Factory Bot](https://github.com/thought
We also provide the `spree_dev_tools` gem that helps you write Spree-specific tests.
<Info>
- This guide assumes you've completed all previous tutorials through [Extending Models](/developer/tutorial/extending-models). You should have a complete `Spree::Brand` model with admin features.
+ This guide assumes you've completed all previous tutorials through [Store API](/developer/tutorial/store-api). You should have a complete `Spree::Brand` model with admin features and API endpoints.
</Info>
## Setup
@@ -210,6 +210,164 @@ end
Controller tests verify that your endpoints respond correctly and perform the expected actions.
+### Store API Controller Tests
+
+Test the API endpoints we created in the [Store API tutorial](/developer/tutorial/store-api). Store API tests use the `'API v3 Store'` shared context which sets up a store, publishable API key, and JWT tokens.
+
+```ruby spec/controllers/spree/api/v3/store/brands_controller_spec.rb
+require 'rails_helper'
+
+RSpec.describe Spree::Api::V3::Store::BrandsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Store'
+
+ let!(:brand1) { create(:brand, name: 'Nike') }
+ let!(:brand2) { create(:brand, name: 'Adidas') }
+
+ before do
+ request.headers['X-Spree-Api-Key'] = api_key.token
+ end
+
+ describe 'GET #index' do
+ it 'returns a list of brands' do
+ get :index
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data'].size).to eq(2)
+ end
+
+ it 'returns brand attributes' do
+ get :index
+
+ brand_data = json_response['data'].first
+ expect(brand_data).to include('id', 'name', 'slug')
+ end
+
+ it 'returns prefixed IDs' do
+ get :index
+
+ ids = json_response['data'].map { |b| b['id'] }
+ ids.each { |id| expect(id).to start_with('brand_') }
+ end
+
+ it 'returns pagination metadata' do
+ get :index, params: { page: 1, limit: 1 }
+
+ expect(json_response['data'].size).to eq(1)
+ expect(json_response['meta']).to include(
+ 'page' => 1,
+ 'limit' => 1,
+ 'count' => 2,
+ 'pages' => 2
+ )
+ end
+
+ it 'filters by name' do
+ get :index, params: { q: { name_cont: 'nik' } }
+
+ expect(json_response['data'].size).to eq(1)
+ expect(json_response['data'].first['name']).to eq('Nike')
+ end
+
+ it 'sorts by name' do
+ get :index, params: { sort: 'name' }
+
+ names = json_response['data'].map { |b| b['name'] }
+ expect(names).to eq(%w[Adidas Nike])
+ end
+ end
+
+ describe 'GET #show' do
+ it 'returns a brand by prefixed ID' do
+ get :show, params: { id: brand1.prefixed_id }
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['id']).to eq(brand1.prefixed_id)
+ expect(json_response['name']).to eq('Nike')
+ end
+
+ it 'returns a brand by slug' do
+ get :show, params: { id: brand1.slug }
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['name']).to eq('Nike')
+ end
+
+ it 'returns 404 for non-existent brand' do
+ get :show, params: { id: 'brand_nonexistent' }
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe 'GET #show with logo' do
+ let!(:brand_with_logo) { create(:brand, :with_logo) }
+
+ it 'includes logo_url when logo is attached' do
+ get :show, params: { id: brand_with_logo.prefixed_id }
+
+ expect(json_response['logo_url']).to be_present
+ end
+ end
+end
+```
+
+### Testing the Product Brand Association
+
+Test that the custom Product serializer includes brand data:
+
+```ruby spec/controllers/spree/api/v3/store/products_brand_spec.rb
+require 'rails_helper'
+
+RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Store'
+
+ let(:brand) { create(:brand, name: 'Nike') }
+ let!(:product) { create(:product, brand: brand, stores: [store], status: 'active') }
+
+ before do
+ request.headers['X-Spree-Api-Key'] = api_key.token
+ end
+
+ describe 'GET #show' do
+ it 'includes brand_id' do
+ get :show, params: { id: product.prefixed_id }
+
+ expect(json_response['brand_id']).to eq(brand.prefixed_id)
+ end
+
+ it 'does not include brand object without expand' do
+ get :show, params: { id: product.prefixed_id }
+
+ expect(json_response).not_to have_key('brand')
+ end
+
+ it 'includes brand object with expand=brand' do
+ get :show, params: { id: product.prefixed_id, expand: 'brand' }
+
+ expect(json_response['brand']).to be_present
+ expect(json_response['brand']['id']).to eq(brand.prefixed_id)
+ expect(json_response['brand']['name']).to eq('Nike')
+ end
+ end
+
+ describe 'GET #index' do
+ it 'filters products by brand_id' do
+ other_product = create(:product, stores: [store], status: 'active')
+
+ get :index, params: { q: { brand_id_eq: brand.id } }
+
+ ids = json_response['data'].map { |p| p['id'] }
+ expect(ids).to include(product.prefixed_id)
+ expect(ids).not_to include(other_product.prefixed_id)
+ end
+ end
+end
+```
+
### Admin Controller Tests
```ruby spec/controllers/spree/admin/brands_controller_spec.rb
@@ -479,8 +637,7 @@ After completing this tutorial, your test structure should look like:
spec/
├── factories/
│ └── spree/
-│ ├── brand_factory.rb
-│ └── brands.rb
+│ └── brand_factory.rb
├── models/
│ └── spree/
│ ├── brand_spec.rb
@@ -489,7 +646,11 @@ spec/
│ └── spree/
│ ├── admin/
│ │ └── brands_controller_spec.rb
-│ └── brands_controller_spec.rb
+│ └── api/
+│ └── v3/
+│ └── store/
+│ ├── brands_controller_spec.rb
+│ └── products_brand_spec.rb
├── features/
│ └── spree/
│ └── admin/
@@ -505,6 +666,7 @@ spec/
* [Model Tutorial](/developer/tutorial/model) - Creating the Brand model
* [Admin Tutorial](/developer/tutorial/admin) - Building the admin interface
* [Extending Core Models](/developer/tutorial/extending-models) - Connecting Brands to Products
+* [Store API Tutorial](/developer/tutorial/store-api) - Creating Brand API endpoints
* [RSpec Documentation](https://rspec.info/documentation/) - Official RSpec docs
* [Factory Bot Documentation](https://github.com/thoughtbot/factory_bot/blob/main/GETTING_STARTED.md) - Factory Bot guide
diff --git a/docs/docs.json b/docs/docs.json
index 88e950ed6e..eecec679a5 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -262,6 +262,8 @@
"developer/tutorial/rich-text",
"developer/tutorial/file-uploads",
"developer/tutorial/extending-models",
+ "developer/tutorial/store-api",
+ "developer/tutorial/sdk",
"developer/tutorial/testing"
]
},
@@ -421,7 +423,8 @@
"pages": [
"developer/sdk/quickstart",
"developer/sdk/authentication",
- "developer/sdk/configuration"
+ "developer/sdk/configuration",
+ "developer/sdk/extending"
]
},
{
diff --git a/packages/sdk/.changeset/expose-request-fn.md b/packages/sdk/.changeset/expose-request-fn.md
new file mode 100644
index 0000000000..9dee200069
--- /dev/null
+++ b/packages/sdk/.changeset/expose-request-fn.md
@@ -0,0 +1,10 @@
+---
+"@spree/sdk": patch
+---
+
+Expose `request` method on the client for calling custom API endpoints. Paths are relative to `/api/v3/store` and use the same auth headers, retry logic, and locale/currency defaults as built-in resources.
+
+```ts
+const client = createClient({ baseUrl: '...', publishableKey: '...' })
+const brands = await client.request<PaginatedResponse<Brand>>('GET', '/brands')
+```
diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts
index 11c5281c2c..178f70499c 100644
--- a/packages/sdk/src/index.ts
+++ b/packages/sdk/src/index.ts
@@ -7,7 +7,7 @@ export { StoreClient } from './store-client';
// Request infrastructure (re-export from sdk-core)
export { SpreeError } from '@spree/sdk-core';
-export type { RequestOptions, RetryConfig } from '@spree/sdk-core';
+export type { RequestFn, RequestOptions, RetryConfig } from '@spree/sdk-core';
// All types
export * from './types';
diff --git a/packages/sdk/src/store-client.ts b/packages/sdk/src/store-client.ts
index d16fe6adf7..4d446e93f8 100644
--- a/packages/sdk/src/store-client.ts
+++ b/packages/sdk/src/store-client.ts
@@ -49,7 +49,18 @@ import type {
} from './types';
export class StoreClient {
- private readonly request: RequestFn;
+ /**
+ * Low-level request function for calling custom API endpoints.
+ *
+ * Uses the same auth headers, retry logic, and base URL as all built-in resources.
+ * Paths are relative to `/api/v3/store`.
+ *
+ * @example
+ * ```ts
+ * const brands = await client.request<PaginatedResponse<Brand>>('GET', '/brands')
+ * ```
+ */
+ readonly request: RequestFn;
constructor(request: RequestFn) {
this.request = request;