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.

Add spree api/auth CLI commands for the Admin API

Damian Legawiec32557806183c
diff --git a/docs/api-reference/admin-api/endpoints.mdx b/docs/api-reference/admin-api/endpoints.mdx
new file mode 100644
index 0000000000..932c05fe7d
--- /dev/null
+++ b/docs/api-reference/admin-api/endpoints.mdx
@@ -0,0 +1,348 @@
+---
+title: "Admin API endpoint index"
+sidebarTitle: "Endpoint index"
+description: "Every Spree Admin API v3 endpoint at a glance — method, path, required API key scope, and summary, grouped by resource."
+---
+
+{/* Generated from docs/api-reference/admin.yaml by packages/cli/scripts/generate-endpoints-doc.mjs — do not edit by hand. */}
+
+All 192 Admin API operations, with the [scope](/api-reference/admin-api/authentication) a secret API key needs for each. JWT-authenticated admin users are governed by their roles instead of scopes. The same index is available offline via the CLI: `spree api endpoints`.
+
+Endpoints marked — are exempt from scope checks (authentication and session endpoints) or resolve their scope at request time.
+
+## Admin users
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/admin_users` | `read_settings` | List staff |
+| `GET` | `/admin_users/{id}` | `read_settings` | Show a staff member |
+| `PATCH` | `/admin_users/{id}` | `write_settings` | Update a staff member |
+| `DELETE` | `/admin_users/{id}` | `write_settings` | Remove a staff member from this store |
+
+## Allowed origins
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/allowed_origins` | `read_settings` | List allowed origins |
+| `POST` | `/allowed_origins` | `write_settings` | Create an allowed origin |
+| `GET` | `/allowed_origins/{id}` | `read_settings` | Get an allowed origin |
+| `PATCH` | `/allowed_origins/{id}` | `write_settings` | Update an allowed origin |
+| `DELETE` | `/allowed_origins/{id}` | `write_settings` | Delete an allowed origin |
+
+## Api keys
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/api_keys` | `read_api_keys` | List API keys |
+| `POST` | `/api_keys` | `write_api_keys` | Create an API key |
+| `GET` | `/api_keys/{id}` | `read_api_keys` | Show an API key |
+| `DELETE` | `/api_keys/{id}` | `write_api_keys` | Delete an API key |
+| `PATCH` | `/api_keys/{id}/revoke` | `write_api_keys` | Revoke an API key |
+
+## Auth
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `POST` | `/auth/login` | — | Login |
+| `POST` | `/auth/refresh` | — | Refresh token |
+| `POST` | `/auth/logout` | — | Logout |
+
+## Channels
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/channels` | `read_settings` | List channels |
+| `POST` | `/channels` | `write_settings` | Create a channel |
+| `GET` | `/channels/{id}` | `read_settings` | Get a channel |
+| `PATCH` | `/channels/{id}` | `write_settings` | Update a channel |
+| `DELETE` | `/channels/{id}` | `write_settings` | Delete a channel |
+| `POST` | `/channels/{id}/add_products` | `write_products` | Publish products on a channel |
+| `POST` | `/channels/{id}/remove_products` | `write_products` | Unpublish products from a channel |
+
+## Custom field definitions
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/custom_field_definitions` | `read_settings` | List custom field definitions |
+| `POST` | `/custom_field_definitions` | `write_settings` | Create a custom field definition |
+| `GET` | `/custom_field_definitions/{id}` | `read_settings` | Show a custom field definition |
+| `PATCH` | `/custom_field_definitions/{id}` | `write_settings` | Update a custom field definition |
+| `DELETE` | `/custom_field_definitions/{id}` | `write_settings` | Delete a custom field definition |
+
+## Customer groups
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/customer_groups` | `read_customers` | List customer groups |
+| `POST` | `/customer_groups` | `write_customers` | Create a customer group |
+| `GET` | `/customer_groups/{id}` | `read_customers` | Get a customer group |
+| `PATCH` | `/customer_groups/{id}` | `write_customers` | Update a customer group |
+| `DELETE` | `/customer_groups/{id}` | `write_customers` | Delete a customer group |
+
+## Customers
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/customers/{customer_id}/addresses` | `read_customers` | List customer addresses |
+| `POST` | `/customers/{customer_id}/addresses` | `write_customers` | Create a customer address |
+| `PATCH` | `/customers/{customer_id}/addresses/{id}` | `write_customers` | Update a customer address |
+| `DELETE` | `/customers/{customer_id}/addresses/{id}` | `write_customers` | Delete a customer address |
+| `GET` | `/customers/{customer_id}/credit_cards` | `read_customers` | List customer credit cards |
+| `GET` | `/customers/{customer_id}/credit_cards/{id}` | `read_customers` | Show a customer credit card |
+| `DELETE` | `/customers/{customer_id}/credit_cards/{id}` | `write_customers` | Delete a customer credit card |
+| `GET` | `/customers/{customer_id}/store_credits` | `read_store_credits` | List customer store credits |
+| `POST` | `/customers/{customer_id}/store_credits` | `write_store_credits` | Issue a store credit to a customer |
+| `PATCH` | `/customers/{customer_id}/store_credits/{id}` | `write_store_credits` | Update a store credit |
+| `DELETE` | `/customers/{customer_id}/store_credits/{id}` | `write_store_credits` | Delete a store credit |
+| `GET` | `/customers` | `read_customers` | List customers |
+| `POST` | `/customers` | `write_customers` | Create a customer |
+| `GET` | `/customers/{id}` | `read_customers` | Show a customer |
+| `PATCH` | `/customers/{id}` | `write_customers` | Update a customer |
+| `DELETE` | `/customers/{id}` | `write_customers` | Delete a customer |
+| `POST` | `/customers/bulk_add_to_groups` | `write_customers` | Bulk-add customers to groups |
+| `POST` | `/customers/bulk_remove_from_groups` | `write_customers` | Bulk-remove customers from groups |
+| `POST` | `/customers/bulk_add_tags` | `write_customers` | Bulk-add tags to customers |
+| `POST` | `/customers/bulk_remove_tags` | `write_customers` | Bulk-remove tags from customers |
+
+## Exports
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/exports` | *the read scope of the exported resource* | List exports |
+| `POST` | `/exports` | *the read scope of the exported resource* | Create an export |
+| `GET` | `/exports/{id}` | *the read scope of the exported resource* | Show an export |
+| `DELETE` | `/exports/{id}` | *the read scope of the exported resource* | Delete an export |
+| `GET` | `/exports/{id}/download` | *the read scope of the exported resource* | Download an export |
+
+## Gift card batches
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/gift_card_batches` | `read_gift_cards` | List gift card batches |
+| `POST` | `/gift_card_batches` | `write_gift_cards` | Create a gift card batch |
+| `GET` | `/gift_card_batches/{id}` | `read_gift_cards` | Get a gift card batch |
+
+## Gift cards
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/gift_cards` | `read_gift_cards` | List gift cards |
+| `POST` | `/gift_cards` | `write_gift_cards` | Create a gift card |
+| `GET` | `/gift_cards/{id}` | `read_gift_cards` | Get a gift card |
+| `PATCH` | `/gift_cards/{id}` | `write_gift_cards` | Update a gift card |
+| `DELETE` | `/gift_cards/{id}` | `write_gift_cards` | Delete a gift card |
+
+## Invitations
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/invitations` | `read_settings` | List invitations |
+| `POST` | `/invitations` | `write_settings` | Create an invitation |
+| `DELETE` | `/invitations/{id}` | `write_settings` | Revoke an invitation |
+| `PATCH` | `/invitations/{id}/resend` | `write_settings` | Resend an invitation |
+
+## Markets
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/markets` | `read_settings` | List markets |
+| `POST` | `/markets` | `write_settings` | Create a market |
+| `GET` | `/markets/{id}` | `read_settings` | Get a market |
+| `PATCH` | `/markets/{id}` | `write_settings` | Update a market |
+| `DELETE` | `/markets/{id}` | `write_settings` | Delete a market |
+
+## Me
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/me` | — | Get current admin user and permissions |
+
+## Option types
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/option_types` | `read_products` | List option types |
+| `POST` | `/option_types` | `write_products` | Create an option type |
+| `GET` | `/option_types/{id}` | `read_products` | Get an option type |
+| `PATCH` | `/option_types/{id}` | `write_products` | Update an option type |
+| `DELETE` | `/option_types/{id}` | `write_products` | Delete an option type |
+
+## Orders
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/orders/{order_id}/fulfillments` | `read_fulfillments` | List fulfillments |
+| `GET` | `/orders/{order_id}/fulfillments/{id}` | `read_fulfillments` | Show a shipment |
+| `PATCH` | `/orders/{order_id}/fulfillments/{id}` | `write_fulfillments` | Update a shipment |
+| `PATCH` | `/orders/{order_id}/fulfillments/{id}/fulfill` | `write_fulfillments` | Fulfill a fulfillment |
+| `PATCH` | `/orders/{order_id}/fulfillments/{id}/cancel` | `write_fulfillments` | Cancel a fulfillment |
+| `PATCH` | `/orders/{order_id}/fulfillments/{id}/resume` | `write_fulfillments` | Resume a fulfillment |
+| `PATCH` | `/orders/{order_id}/fulfillments/{id}/split` | `write_fulfillments` | Split a fulfillment |
+| `POST` | `/orders/{order_id}/gift_cards` | `write_gift_cards` | Apply a gift card to an order |
+| `DELETE` | `/orders/{order_id}/gift_cards/{id}` | `write_gift_cards` | Remove a gift card from an order |
+| `GET` | `/orders/{order_id}/items` | `read_orders` | List order items |
+| `POST` | `/orders/{order_id}/items` | `write_orders` | Add an item |
+| `GET` | `/orders/{order_id}/items/{id}` | `read_orders` | Show an item |
+| `PATCH` | `/orders/{order_id}/items/{id}` | `write_orders` | Update an item |
+| `DELETE` | `/orders/{order_id}/items/{id}` | `write_orders` | Remove an item |
+| `POST` | `/orders/{order_id}/store_credits` | `write_store_credits` | Apply customer's store credit to an order |
+| `DELETE` | `/orders/{order_id}/store_credits` | `write_store_credits` | Remove store credit from an order |
+| `GET` | `/orders` | `read_orders` | List orders |
+| `POST` | `/orders` | `write_orders` | Create a draft order |
+| `GET` | `/orders/{id}` | `read_orders` | Show an order |
+| `PATCH` | `/orders/{id}` | `write_orders` | Update an order |
+| `DELETE` | `/orders/{id}` | `write_orders` | Delete a draft order |
+| `PATCH` | `/orders/{id}/complete` | `write_orders` | Complete an order |
+| `PATCH` | `/orders/{id}/cancel` | `write_orders` | Cancel an order |
+| `PATCH` | `/orders/{id}/approve` | `write_orders` | Approve an order |
+| `PATCH` | `/orders/{id}/resume` | `write_orders` | Resume a canceled order |
+| `POST` | `/orders/{id}/resend_confirmation` | `write_orders` | Resend confirmation email |
+| `GET` | `/orders/{order_id}/payments` | `read_payments` | List payments |
+| `POST` | `/orders/{order_id}/payments` | `write_payments` | Create a payment |
+| `GET` | `/orders/{order_id}/payments/{id}` | `read_payments` | Show a payment |
+| `PATCH` | `/orders/{order_id}/payments/{id}/capture` | `write_payments` | Capture a payment |
+| `PATCH` | `/orders/{order_id}/payments/{id}/void` | `write_payments` | Void a payment |
+| `GET` | `/orders/{order_id}/refunds` | `read_refunds` | List refunds |
+| `POST` | `/orders/{order_id}/refunds` | `write_refunds` | Create a refund |
+
+## Payment methods
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/payment_methods` | `read_settings` | List payment methods |
+| `GET` | `/payment_methods/types` | `read_settings` | List available payment provider types |
+| `GET` | `/payment_methods/{id}` | `read_settings` | Show a payment method |
+
+## Price lists
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/price_lists` | `read_products` | List price lists |
+| `POST` | `/price_lists` | `write_products` | Create a price list |
+| `GET` | `/price_lists/{id}` | `read_products` | Get a price list |
+| `PATCH` | `/price_lists/{id}` | `write_products` | Update a price list |
+| `DELETE` | `/price_lists/{id}` | `write_products` | Delete a price list |
+| `PATCH` | `/price_lists/{id}/activate` | `write_products` | Activate a price list |
+| `PATCH` | `/price_lists/{id}/deactivate` | `write_products` | Deactivate a price list |
+
+## Prices
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/prices` | `read_products` | List prices |
+| `POST` | `/prices` | `write_products` | Create a price |
+| `GET` | `/prices/{id}` | `read_products` | Get a price |
+| `PATCH` | `/prices/{id}` | `write_products` | Update a price |
+| `DELETE` | `/prices/{id}` | `write_products` | Delete a price |
+| `POST` | `/prices/bulk_upsert` | `write_products` | Bulk-upsert prices |
+| `DELETE` | `/prices/bulk_destroy` | `write_products` | Bulk-delete prices |
+
+## Products
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/products/{product_id}/custom_fields` | `read_products` | List product custom fields |
+| `POST` | `/products/{product_id}/custom_fields` | `write_products` | Create a product custom field |
+| `GET` | `/products/{product_id}/custom_fields/{id}` | `read_products` | Show a product custom field |
+| `PATCH` | `/products/{product_id}/custom_fields/{id}` | `write_products` | Update a product custom field |
+| `DELETE` | `/products/{product_id}/custom_fields/{id}` | `write_products` | Delete a product custom field |
+| `GET` | `/products` | `read_products` | List products |
+| `POST` | `/products` | `write_products` | Create a product |
+| `GET` | `/products/{id}` | `read_products` | Get a product |
+| `PATCH` | `/products/{id}` | `write_products` | Update a product |
+| `DELETE` | `/products/{id}` | `write_products` | Delete a product |
+| `POST` | `/products/bulk_status_update` | `write_products` | Bulk-update product status |
+| `POST` | `/products/bulk_add_to_categories` | `write_products` | Bulk-add products to categories |
+| `POST` | `/products/bulk_remove_from_categories` | `write_products` | Bulk-remove products from categories |
+| `POST` | `/products/bulk_add_to_channels` | `write_products` | Bulk-add products to channels |
+| `POST` | `/products/bulk_remove_from_channels` | `write_products` | Bulk-remove products from channels |
+| `POST` | `/products/bulk_add_tags` | `write_products` | Bulk-add tags to products |
+| `POST` | `/products/bulk_remove_tags` | `write_products` | Bulk-remove tags from products |
+| `DELETE` | `/products/bulk_destroy` | `write_products` | Bulk-delete products |
+| `GET` | `/products/{product_id}/variants` | `read_products` | List product variants |
+| `POST` | `/products/{product_id}/variants` | `write_products` | Create a variant |
+| `GET` | `/products/{product_id}/variants/{id}` | `read_products` | Get a variant |
+| `PATCH` | `/products/{product_id}/variants/{id}` | `write_products` | Update a variant |
+| `DELETE` | `/products/{product_id}/variants/{id}` | `write_products` | Delete a variant |
+
+## Promotion actions
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/promotion_actions/types` | `read_promotions` | List available promotion action types |
+
+## Promotion rules
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/promotion_rules/types` | `read_promotions` | List available promotion rule types |
+
+## Promotions
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/promotions/{promotion_id}/coupon_codes` | `read_promotions` | List coupon codes for a promotion |
+| `GET` | `/promotions/{promotion_id}/promotion_actions` | `read_promotions` | List actions for a promotion |
+| `POST` | `/promotions/{promotion_id}/promotion_actions` | `write_promotions` | Create an action on a promotion |
+| `DELETE` | `/promotions/{promotion_id}/promotion_actions/{id}` | `write_promotions` | Delete an action from a promotion |
+| `GET` | `/promotions/{promotion_id}/promotion_rules` | `read_promotions` | List rules for a promotion |
+| `POST` | `/promotions/{promotion_id}/promotion_rules` | `write_promotions` | Create a rule on a promotion |
+| `PATCH` | `/promotions/{promotion_id}/promotion_rules/{id}` | `write_promotions` | Update a rule's preferences |
+| `DELETE` | `/promotions/{promotion_id}/promotion_rules/{id}` | `write_promotions` | Delete a rule from a promotion |
+| `GET` | `/promotions` | `read_promotions` | List promotions |
+| `POST` | `/promotions` | `write_promotions` | Create a promotion |
+| `GET` | `/promotions/{id}` | `read_promotions` | Show a promotion |
+| `PATCH` | `/promotions/{id}` | `write_promotions` | Update a promotion |
+| `DELETE` | `/promotions/{id}` | `write_promotions` | Delete a promotion |
+
+## Roles
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/roles` | `read_settings` | List roles |
+
+## Stock locations
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/stock_locations` | `read_stock` | List stock locations |
+| `POST` | `/stock_locations` | `write_stock` | Create a stock location |
+| `GET` | `/stock_locations/{id}` | `read_stock` | Get a stock location |
+| `PATCH` | `/stock_locations/{id}` | `write_stock` | Update a stock location |
+| `DELETE` | `/stock_locations/{id}` | `write_stock` | Delete a stock location |
+
+## Store
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/store` | `read_settings` | Get the current store |
+| `PATCH` | `/store` | `write_settings` | Update the current store |
+
+## Store credit categories
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/store_credit_categories` | `read_settings` | List store credit categories |
+| `GET` | `/store_credit_categories/{id}` | `read_settings` | Get a store credit category |
+
+## Tags
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/tags` | — | List tags |
+
+## Webhook endpoints
+
+| Method | Path | Required scope | Summary |
+|---|---|---|---|
+| `GET` | `/webhook_endpoints/{webhook_endpoint_id}/deliveries` | `read_webhooks` | List webhook deliveries |
+| `GET` | `/webhook_endpoints/{webhook_endpoint_id}/deliveries/{id}` | `read_webhooks` | Get a webhook delivery |
+| `POST` | `/webhook_endpoints/{webhook_endpoint_id}/deliveries/{id}/redeliver` | `write_webhooks` | Redeliver a webhook delivery |
+| `GET` | `/webhook_endpoints` | `read_webhooks` | List webhook endpoints |
+| `POST` | `/webhook_endpoints` | `write_webhooks` | Create a webhook endpoint |
+| `GET` | `/webhook_endpoints/{id}` | `read_webhooks` | Get a webhook endpoint |
+| `PATCH` | `/webhook_endpoints/{id}` | `write_webhooks` | Update a webhook endpoint |
+| `DELETE` | `/webhook_endpoints/{id}` | `write_webhooks` | Delete a webhook endpoint |
+| `POST` | `/webhook_endpoints/{id}/send_test` | `write_webhooks` | Send a test delivery |
+| `PATCH` | `/webhook_endpoints/{id}/enable` | `write_webhooks` | Re-enable a webhook endpoint |
+| `PATCH` | `/webhook_endpoints/{id}/disable` | `write_webhooks` | Disable a webhook endpoint |
diff --git a/docs/developer/cli/admin-api.mdx b/docs/developer/cli/admin-api.mdx
new file mode 100644
index 0000000000..3271d0aa93
--- /dev/null
+++ b/docs/developer/cli/admin-api.mdx
@@ -0,0 +1,107 @@
+---
+title: "Call the Admin API from the CLI"
+sidebarTitle: "Admin API"
+description: "Use spree api to call the Spree Admin API with gh api-style generic verbs, schema introspection, and zero-config credentials — built for scripts and AI agents."
+---
+
+The `spree api` command group turns the CLI into a first-class Admin API client: generic HTTP verbs against any endpoint, schema introspection without leaving the terminal, and credentials that resolve automatically — from a local dev project to a production store profile. It works against any Spree 5.5+ instance and is designed to be driven by both humans and AI coding agents.
+
+```bash
+spree api get /products -q status_eq=active --sort -created_at --limit 10
+spree api get /orders/ord_x8k2J9aQ --expand items,payments
+spree api post /products -d '{"name":"Classic Tee"}'
+spree api patch /orders/ord_x8k2J9aQ/cancel
+spree api endpoints --resource orders
+spree api schema "POST /orders/{id}/refunds"
+spree api status
+```
+
+## Credentials
+
+Credentials resolve through four layers — first match wins:
+
+| Layer | How |
+|---|---|
+| Flags | `--base-url` / `--api-key` (and `--profile`, which selects a saved profile explicitly) |
+| Environment | `SPREE_BASE_URL` + `SPREE_API_KEY` — the path for CI and agents |
+| Project | Inside a Spree project with the dev stack running, the CLI mints a **read-only** key on first use and stores it in `.spree/credentials.json` (gitignored) |
+| Profile | `~/.config/spree/config.json`, written by `spree auth login` |
+
+Zero configuration is needed for local development — the first `spree api get` inside your project just works:
+
+```bash
+cd my-store
+spree api get /products
+# No credentials found — minting a read-only API key via the dev stack...
+# Saved to .spree/credentials.json (scopes: read_all)
+```
+
+Auto-minted keys carry `read_all` only. Writes always require an explicitly created key:
+
+```bash
+spree api-key create --type secret --scopes read_orders,write_products
+```
+
+For remote stores, create a secret key in the admin under **Settings → API Keys** and save it as a profile — the key is read from a prompt, never from a flag:
+
+```bash
+spree auth login --profile prod --base-url https://store.example.com
+spree api get /orders --profile prod -q "status_eq=complete"
+spree auth status
+spree auth logout --profile prod
+```
+
+## Reading data
+
+`-q` takes [Ransack](/api-reference/admin-api/querying) predicates as repeatable `key=value` pairs; sorting, pagination, and shaping flags pass through under the Admin API conventions:
+
+```bash
+spree api get /products -q name_cont=shirt -q status_eq=active
+spree api get /orders --sort -created_at --page 2 --limit 50
+spree api get /products/prod_86Rf07xd --expand variants,variants.prices
+spree api get /customers --fields id,email --format table
+```
+
+Output is pretty-printed JSON on stdout — pipe it straight into `jq`. `--format table` renders collections for humans.
+
+## Writing data
+
+Request bodies are flat JSON (no root wrapping), inline, from a file, or from stdin:
+
+```bash
+spree api post /products -d '{"name":"Classic Tee","price":29.99}'
+spree api post /orders/ord_x8k2J9aQ/refunds -d @refund.json
+cat prices.json | spree api post /prices/bulk_upsert -d -
+spree api delete /products/prod_86Rf07xd
+```
+
+Mutations automatically carry an `Idempotency-Key`, so retries are safe.
+
+## Discovering endpoints and schemas
+
+The CLI bundles a snapshot of the Admin API OpenAPI spec, so discovery works offline:
+
+```bash
+spree api endpoints --resource orders # methods, paths, required scopes
+spree api endpoints --search "gift card"
+spree api schema "POST /orders" # parameters + request/response schema
+spree api status # resolved credentials + server reachability
+```
+
+`spree api endpoints` shows the `read_*` / `write_*` scope each endpoint requires (see [Authentication](/api-reference/admin-api/authentication)) — useful for deciding what to grant a new key.
+
+## Errors and exit codes
+
+API errors print the error envelope to stderr and exit `1`; usage and configuration problems exit `2`. A scope denial includes the exact remediation:
+
+```text
+access_denied: API key lacks scope: write_products
+{
+ "details": { "required_scope": "write_products" }
+}
+Hint: mint a key carrying this scope — spree api-key create --type secret --scopes write_products
+```
+
+## Using it with AI agents
+
+Agents with shell access (Claude Code, Cursor, and similar) can drive a Spree back office through `spree api` with no extra configuration: inside a project the credentials self-provision read-only, and for remote stores two environment variables (`SPREE_BASE_URL`, `SPREE_API_KEY`) are the whole contract. The `endpoints`/`schema` commands give agents request shapes on demand instead of loading the entire API surface up front, and error messages name the missing scope so agents can self-correct.
diff --git a/docs/developer/cli/quickstart.mdx b/docs/developer/cli/quickstart.mdx
index dfbffaa841..e4d502bcd6 100644
--- a/docs/developer/cli/quickstart.mdx
+++ b/docs/developer/cli/quickstart.mdx
@@ -164,16 +164,39 @@ spree user create --email [email protected] --password secret123
### `spree api-key`
-Manage Store and Admin API keys.
+Manage Store and Admin API keys. Secret keys carry [scopes](/api-reference/admin-api/authentication) and require at least one.
```bash
spree api-key list # List all keys
spree api-key create # Interactive
-spree api-key create --name "Storefront" --type publishable # Store API key
-spree api-key create --name "Admin" --type secret # Admin API key
+spree api-key create --name "Storefront" --type publishable # Store API key
+spree api-key create --name "Admin" --type secret --scopes read_all # Admin API key
spree api-key revoke <id> # Revoke a key
```
+### `spree api`
+
+Call the Admin API with `gh api`-style generic verbs — zero-config inside a project (a read-only key is minted on first use), env vars or profiles for remote stores. See [Admin API from the CLI](/developer/cli/admin-api) for the full guide.
+
+```bash
+spree api get /products -q status_eq=active --limit 10
+spree api post /products -d '{"name":"Classic Tee"}'
+spree api endpoints --resource orders # endpoints + required scopes, offline
+spree api schema "POST /orders" # request/response schema, offline
+spree api status
+```
+
+### `spree auth`
+
+Save Admin API credentials for remote stores as named profiles.
+
+```bash
+spree auth login --profile prod --base-url https://store.example.com
+spree api get /orders --profile prod
+spree auth status
+spree auth logout --profile prod
+```
+
## Dev workflow commands
These mirror the Rails commands you'd run if you were running the app directly on your host — but each is routed through `docker compose exec` against the running stack.
diff --git a/docs/developer/sdk/admin/resources.mdx b/docs/developer/sdk/admin/resources.mdx
index f420a71736..67f7c222d5 100644
--- a/docs/developer/sdk/admin/resources.mdx
+++ b/docs/developer/sdk/admin/resources.mdx
@@ -6,6 +6,8 @@ description: "Reference for every @spree/admin-sdk resource — products, orders
Every Admin API resource is exposed as a property on the client (`client.orders`, `client.products`, …). Collection resources follow a consistent CRUD shape — `list`, `get`, `create`, `update`, `delete` — plus resource-specific actions. Nested resources take the **parent ID as the first argument**:
+For the underlying HTTP surface — every endpoint with the API key scope it requires — see the [Admin API endpoint index](/api-reference/admin-api/endpoints).
+
```typescript
// Top-level
const order = await client.orders.get('order_xxx')
diff --git a/docs/docs.json b/docs/docs.json
index c1e07b4e15..78b71e9418 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -522,7 +522,8 @@
{
"group": "CLI",
"pages": [
- "developer/cli/quickstart"
+ "developer/cli/quickstart",
+ "developer/cli/admin-api"
]
}
]
@@ -602,7 +603,8 @@
"api-reference/admin-api/introduction",
"api-reference/admin-api/authentication",
"api-reference/admin-api/errors",
- "api-reference/admin-api/querying"
+ "api-reference/admin-api/querying",
+ "api-reference/admin-api/endpoints"
]
},
{
diff --git a/docs/plans/5.5-admin-api-cli.md b/docs/plans/5.5-admin-api-cli.md
index ed5f842ea5..f22f0ca93d 100644
--- a/docs/plans/5.5-admin-api-cli.md
+++ b/docs/plans/5.5-admin-api-cli.md
@@ -1,6 +1,6 @@
# `spree api` — Admin API command group in `@spree/cli`
-**Status:** Draft
+**Status:** In Progress
**Target:** Spree 5.5.x (CLI minor + one core patch)
**Depends on:** `5.5-admin-api-key-scopes.md` (shipped), `6.0-admin-api.md` (conventions), `5.5-agent-skills.md` (distribution of the companion skill)
**Author:** Damian Legawiec (`[email protected]`)
@@ -120,11 +120,20 @@ One new `spree-cli` skill in `github.com/spree/agent-skills` (per that plan's co
All steps are additive; no breaking changes anywhere.
-1. **Core 5.5.x patch** (`spree/core`): `SCOPES` env on `spree:cli:create_api_key` (fixes secret-key minting), `read_promotions`/`write_promotions` in `Spree::ApiKey::SCOPES`. Specs for both.
-2. **`@spree/cli` minor**: add `@spree/admin-sdk` dependency; new `src/config.ts` (resolution chain + credential files); `src/commands/auth.ts` and `src/commands/api.ts` following the existing `registerXCommand` pattern; `--scopes` flag on `api-key create`; a build step copying `docs/api-reference/admin.yaml` into the package as the versioned snapshot; Changesets entry.
-3. **Scaffolding**: `create-spree-app` (and the spree-starter template repo) add `.spree/` to `.gitignore`.
-4. **agent-skills**: `spree-cli` skill PR to `spree/agent-skills`.
-5. **Docs**: a page under `docs/developer/` covering the command group, credential layers, and agent usage (Claude Code snippet with the two env vars).
+1. **Core 5.5.x patch** (`spree/core`) — ✅ **shipped (PR #14166)**: `SCOPES` env on `spree:cli:create_api_key` (fixes secret-key minting), `read_promotions`/`write_promotions` in `Spree::ApiKey::SCOPES` (plus the broader scope cleanup: dedicated `api_keys`/`webhooks` scopes, `stock` covering inventory, exports gated by the exported resource). Specs for all.
+2. **`@spree/cli` minor** — ✅ **done**: `@spree/admin-sdk` dependency; `src/config.ts` (paired-layer resolution + credential files); `src/commands/auth.ts` + `src/commands/api.ts`; helper modules under `src/api/` (`params`, `body`, `output`, `ping`, `spec`); `--scopes` flag on `api-key create`; `scripts/bundle-spec.mjs` slims `admin.yaml` → `src/generated/admin-spec.json` at build time (via the `yaml` package); Changesets entries.
+3. **Scaffolding** — ✅ **partial**: `create-spree-app` adds `.spree/` to its `.gitignore`; the auto-mint flow also writes a self-ignoring `.spree/.gitignore` so any project (regardless of scaffold vintage) is covered. *Pending:* the same `.gitignore` line in the `spree/spree-starter` template repo (separate repo PR).
+4. **agent-skills** — ⏳ **open**: `spree-cli` skill PR to `spree/agent-skills`.
+5. **Docs** — ✅ **done**: `docs/developer/cli/admin-api.mdx` (command group + credential layers + agent usage), `docs/api-reference/admin-api/endpoints.mdx` (generated endpoint index), README + quickstart sections.
+
+### As-built surface (beyond the original sketch)
+
+- **Commands**: `spree api get|post|patch|delete <path>`, `spree api endpoints` (`--resource`, `--search`, `--format`), `spree api schema <operation>`, `spree api status`; `spree auth login|status|logout|list` (`logout --project` removes `.spree/credentials.json`).
+- **Credential resolution is paired-per-source, not per-field.** The API key anchors each layer; host and key resolve together so a saved/minted key is never silently sent to a host from `SPREE_BASE_URL` alone. An explicit `--base-url`/`--api-key` flag is the only sanctioned cross-source override. Auto-mint is suppressed when an explicit `--base-url` targets a non-project host.
+- **Profile schema** persisted at `~/.config/spree/config.json` (0600): `{ defaultProfile, profiles: { <name>: { baseUrl, token } } }`. A corrupt file is backed up to `config.json.bak` rather than silently emptied.
+- **Schema snapshot**: a slimmed (examples-stripped) JSON copy of `admin.yaml` bundled in the package; `spree api schema` resolves `$ref`s inline and prefers exact literal paths over `{id}` templates.
+- **Exit codes**: 0 success, 1 API error (envelope to stderr), 2 usage/configuration error (bad flag, invalid `-q`/`--page`/`--limit`, no credentials, unreachable host). 403 scope denials print the full mint-and-wire remediation.
+- **Deferred**: a true server-vs-snapshot version-skew warning needs an Admin API endpoint exposing the Spree version (none exists yet); `spree api status` notes the snapshot may lag the live server instead.
## Constraints on Current Work
diff --git a/packages/cli/.changeset/admin-api-commands.md b/packages/cli/.changeset/admin-api-commands.md
new file mode 100644
index 0000000000..ee53e110c9
--- /dev/null
+++ b/packages/cli/.changeset/admin-api-commands.md
@@ -0,0 +1,13 @@
+---
+"@spree/cli": minor
+---
+
+New `spree api` and `spree auth` command groups — a gh api-style Admin API client built into the CLI:
+
+- `spree api get|post|patch|delete <path>` — generic verbs with Ransack `-q` filters, `--sort`/`--page`/`--limit`/`--expand`/`--fields`, and JSON bodies from inline/`@file`/stdin
+- `spree api endpoints` / `spree api schema` — offline schema introspection over a bundled OpenAPI snapshot, including each endpoint's required scope
+- `spree api status` — resolved credentials + server reachability
+- `spree auth login|status|logout|list` — named profiles in `~/.config/spree/config.json`
+- Zero-config credentials inside a project: a read-only key is minted via the dev stack on first use and stored in `.spree/credentials.json`; remote stores use profiles or `SPREE_BASE_URL`/`SPREE_API_KEY`
+
+Works against any Spree 5.5+ instance.
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 0586f7ad91..0f9e2f6913 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -112,9 +112,11 @@ spree api-key create
# Non-interactive
spree api-key create --name "My Storefront" --type publishable
-spree api-key create --name "Admin Integration" --type secret
+spree api-key create --name "Admin Integration" --type secret --scopes read_orders,write_products
```
+Secret keys require at least one scope (`read_all` for a read-only key, `write_all` for full access, or granular `read_*`/`write_*` pairs).
+
**Important:** Secret key tokens are displayed only once at creation time and cannot be retrieved later. Save them immediately.
### `spree api-key list`
@@ -133,6 +135,36 @@ Revoke an API key by its token (publishable) or token prefix (secret).
spree api-key revoke pk_abc123def456...
```
+### `spree api`
+
+Call the Admin API directly with `gh api`-style generic verbs. Works against any Spree 5.5+ instance — inside a project it self-provisions a **read-only** key via the dev stack on first use (saved to `.spree/credentials.json`, gitignored); remote stores use `SPREE_BASE_URL`/`SPREE_API_KEY` env vars or saved profiles.
+
+```bash
+spree api get /products -q status_eq=active --sort -created_at --limit 10
+spree api get /orders/ord_x8k2J9aQ --expand items,payments
+spree api post /products -d '{"name":"Classic Tee"}'
+spree api patch /orders/ord_x8k2J9aQ/cancel
+spree api delete /products/prod_86Rf07xd
+
+spree api endpoints --resource orders # endpoints + required scopes (offline)
+spree api schema "POST /orders" # request/response schema (offline)
+spree api status # resolved credentials + server check
+```
+
+Output is JSON on stdout (pipes into `jq`); `--format table` renders collections for humans. API errors exit `1` with the error envelope on stderr — scope denials include the exact `--scopes` remediation.
+
+### `spree auth`
+
+Manage saved Admin API credentials for remote stores (profiles in `~/.config/spree/config.json`).
+
+```bash
+spree auth login --profile prod --base-url https://store.example.com # key read from a prompt
+spree api get /orders --profile prod
+spree auth status
+spree auth list
+spree auth logout --profile prod
+```
+
### `spree seed`
Run database seeds.
diff --git a/packages/cli/biome.json b/packages/cli/biome.json
index aa61cf8253..a5a6ee10d1 100644
--- a/packages/cli/biome.json
+++ b/packages/cli/biome.json
@@ -3,6 +3,6 @@
"root": false,
"extends": ["../../biome.json"],
"files": {
- "includes": ["src/**", "tests/**"]
+ "includes": ["src/**", "tests/**", "!src/generated"]
}
}
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 6a0436f5de..1141137c32 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -12,7 +12,7 @@
"LICENSE"
],
"scripts": {
- "build": "tsup",
+ "build": "node scripts/bundle-spec.mjs && tsup",
"dev": "tsup --watch",
"test": "vitest run",
"typecheck": "tsc --noEmit",
@@ -23,7 +23,8 @@
"prepublishOnly": "npm run build",
"changeset": "changeset",
"version": "changeset version",
- "release": "npm run build && changeset publish"
+ "release": "npm run build && changeset publish",
+ "generate:spec": "node scripts/bundle-spec.mjs"
},
"keywords": [
"spree",
@@ -46,6 +47,7 @@
},
"dependencies": {
"@clack/prompts": "^1.3.0",
+ "@spree/admin-sdk": "workspace:^",
"commander": "^14.0.3",
"console-table-printer": "^2.15.0",
"execa": "^9.6.1",
@@ -57,7 +59,8 @@
"@types/node": "^25.6.0",
"tsup": "^8.5.1",
"typescript": "^6.0.3",
- "vitest": "^4.1.5"
+ "vitest": "^4.1.5",
+ "yaml": "^2.8.4"
},
"engines": {
"node": ">=20"
diff --git a/packages/cli/scripts/bundle-spec.mjs b/packages/cli/scripts/bundle-spec.mjs
new file mode 100644
index 0000000000..1e86725cc8
--- /dev/null
+++ b/packages/cli/scripts/bundle-spec.mjs
@@ -0,0 +1,57 @@
+/**
+ * Bundles a slimmed snapshot of the Admin API OpenAPI spec into the package.
+ *
+ * Usage: node scripts/bundle-spec.mjs
+ *
+ * Reads: docs/api-reference/admin.yaml (rswag-generated — never hand-edit)
+ * Writes: src/generated/admin-spec.json (committed; regenerated by `pnpm build`)
+ *
+ * The snapshot keeps what `spree api endpoints` / `spree api schema` need —
+ * operation metadata, parameters, request/response schemas, the scope lines
+ * rswag writes into descriptions, and component schemas for $ref resolution —
+ * and strips examples and code samples, which dominate the YAML's size.
+ */
+
+import * as fs from 'node:fs'
+import * as path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { parse } from 'yaml'
+
+const here = path.dirname(fileURLToPath(import.meta.url))
+const SPEC_PATH = path.resolve(here, '../../../docs/api-reference/admin.yaml')
+const OUT_PATH = path.resolve(here, '../src/generated/admin-spec.json')
+
+function stripExamples(node) {
+ if (Array.isArray(node)) {
+ for (const item of node) stripExamples(item)
+ return
+ }
+ if (node && typeof node === 'object') {
+ delete node.example
+ delete node.examples
+ delete node['x-codeSamples']
+ for (const value of Object.values(node)) stripExamples(value)
+ }
+}
+
+const spec = parse(fs.readFileSync(SPEC_PATH, 'utf-8'))
+stripExamples(spec)
+
+const slim = {
+ info: spec.info,
+ paths: spec.paths,
+ components: { schemas: spec.components?.schemas ?? {} },
+}
+
+fs.mkdirSync(path.dirname(OUT_PATH), { recursive: true })
+fs.writeFileSync(OUT_PATH, JSON.stringify(slim))
+
+const HTTP_METHODS = new Set(['get', 'post', 'put', 'patch', 'delete'])
+const size = (fs.statSync(OUT_PATH).size / 1024).toFixed(0)
+const operations = Object.values(slim.paths ?? {}).reduce(
+ (n, methods) => n + Object.keys(methods).filter((m) => HTTP_METHODS.has(m)).length,
+ 0,
+)
+console.log(
+ `admin-spec.json written: ${size} KB, ${Object.keys(slim.paths ?? {}).length} paths, ${operations} operations`,
+)
diff --git a/packages/cli/scripts/generate-endpoints-doc.mjs b/packages/cli/scripts/generate-endpoints-doc.mjs
new file mode 100644
index 0000000000..18e8f69970
--- /dev/null
+++ b/packages/cli/scripts/generate-endpoints-doc.mjs
@@ -0,0 +1,92 @@
+/**
+ * Generates the Admin API endpoint index page for the docs site.
+ *
+ * Usage: node packages/cli/scripts/generate-endpoints-doc.mjs
+ *
+ * Reads: docs/api-reference/admin.yaml (rswag-generated)
+ * Writes: docs/api-reference/admin-api/endpoints.mdx
+ *
+ * One row per operation — method, path, required scope, summary — grouped by
+ * resource. The same data backs `spree api endpoints`; regenerate this page
+ * whenever the Admin API surface or scope annotations change.
+ */
+
+import * as fs from 'node:fs'
+import * as path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { parse } from 'yaml'
+
+const here = path.dirname(fileURLToPath(import.meta.url))
+const SPEC_PATH = path.resolve(here, '../../../docs/api-reference/admin.yaml')
+const OUT_PATH = path.resolve(here, '../../../docs/api-reference/admin-api/endpoints.mdx')
+
+const HTTP_METHODS = ['get', 'post', 'put', 'patch', 'delete']
+
+const spec = parse(fs.readFileSync(SPEC_PATH, 'utf-8'))
+
+function requiredScope(operation) {
+ const match = operation.description?.match(
+ /\*\*Required scope:\*\* (.+?) \(for API-key authentication\)\./s,
+ )
+ if (!match) return '—'
+ const raw = match[1].replace(/\n/g, ' ').trim()
+ const token = raw.match(/^`([a-z_]+)`$/)
+ if (token) return `\`${token[1]}\``
+ // Free-form note (e.g. exports resolve their scope per type) — keep it short.
+ return `*${raw.replaceAll('`', '').split(' — ')[0]}*`
+}
+
+const groups = new Map()
+for (const [specPath, methods] of Object.entries(spec.paths)) {
+ const shortPath = specPath.replace('/api/v3/admin', '') || '/'
+ const resource = shortPath.split('/')[1] || 'root'
+ for (const method of HTTP_METHODS) {
+ const operation = methods[method]
+ if (!operation) continue
+ if (!groups.has(resource)) groups.set(resource, [])
+ groups.get(resource).push({
+ method: method.toUpperCase(),
+ path: shortPath,
+ scope: requiredScope(operation),
+ summary: operation.summary ?? '',
+ })
+ }
+}
+
+function title(resource) {
+ return resource.replaceAll('_', ' ').replace(/^./, (c) => c.toUpperCase())
+}
+
+const sections = [...groups.entries()]
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([resource, rows]) => {
+ const table = [
+ '| Method | Path | Required scope | Summary |',
+ '|---|---|---|---|',
+ ...rows.map(
+ (r) =>
+ `| \`${r.method}\` | \`${r.path}\` | ${r.scope} | ${r.summary.replaceAll('|', '\\|')} |`,
+ ),
+ ].join('\n')
+ return `## ${title(resource)}\n\n${table}`
+ })
+
+const total = [...groups.values()].reduce((n, rows) => n + rows.length, 0)
+
+const page = `---
+title: "Admin API endpoint index"
+sidebarTitle: "Endpoint index"
+description: "Every Spree Admin API v3 endpoint at a glance — method, path, required API key scope, and summary, grouped by resource."
+---
+
+{/* Generated from docs/api-reference/admin.yaml by packages/cli/scripts/generate-endpoints-doc.mjs — do not edit by hand. */}
+
+All ${total} Admin API operations, with the [scope](/api-reference/admin-api/authentication) a secret API key needs for each. JWT-authenticated admin users are governed by their roles instead of scopes. The same index is available offline via the CLI: \`spree api endpoints\`.
+
+Endpoints marked — are exempt from scope checks (authentication and session endpoints) or resolve their scope at request time.
+
+${sections.join('\n\n')}
+`
+
+fs.writeFileSync(OUT_PATH, page)
+console.log(`endpoints.mdx written: ${total} operations, ${groups.size} resource groups`)
diff --git a/packages/cli/src/api/body.ts b/packages/cli/src/api/body.ts
new file mode 100644
index 0000000000..5e04e05ac2
--- /dev/null
+++ b/packages/cli/src/api/body.ts
@@ -0,0 +1,54 @@
+import fs from 'node:fs'
+import pc from 'picocolors'
+
+/** Sentinel for "no body was given" — distinct from a body that is literally `null`. */
+export const NO_BODY = Symbol('no-body')
+
+/**
+ * Reads the request body for write verbs, gh-api style:
+ * -d '{"name":"Tee"}' inline JSON
+ * -d @payload.json from a file
+ * -d - from stdin
+ *
+ * Returns {@link NO_BODY} when no `-d` was passed. A literal `null`/`false`/`0`
+ * body is preserved (not conflated with absence) so the request still carries it.
+ */
+export async function readBody(data: string | undefined): Promise<unknown> {
+ if (data === undefined) return NO_BODY
+
+ let raw: string
+ if (data === '-') {
+ raw = await readStdin()
+ } else if (data.startsWith('@')) {
+ const file = data.slice(1)
+ try {
+ raw = fs.readFileSync(file, 'utf-8')
+ } catch {
+ throw new Error(`Request body file not found: ${file}`)
+ }
+ } else {
+ raw = data
+ }
+
+ try {
+ return JSON.parse(raw)
+ } catch {
+ const where = data === '-' ? ' (from stdin)' : data.startsWith('@') ? ` (${data.slice(1)})` : ''
+ throw new Error(`Request body is not valid JSON${where}`)
+ }
+}
+
+async function readStdin(): Promise<string> {
+ // Without this, `-d -` on an interactive terminal hangs with no indication
+ // that it's waiting for input.
+ if (process.stdin.isTTY) {
+ process.stderr.write(
+ `${pc.dim('Reading request body from stdin — paste JSON and press Ctrl-D...')}\n`,
+ )
+ }
+ const chunks: Buffer[] = []
+ for await (const chunk of process.stdin) {
+ chunks.push(chunk as Buffer)
+ }
+ return Buffer.concat(chunks).toString('utf-8')
+}
diff --git a/packages/cli/src/api/output.ts b/packages/cli/src/api/output.ts
new file mode 100644
index 0000000000..4f933aba3d
--- /dev/null
+++ b/packages/cli/src/api/output.ts
@@ -0,0 +1,98 @@
+import { SpreeError } from '@spree/admin-sdk'
+import { printTable } from 'console-table-printer'
+import pc from 'picocolors'
+import { CredentialError } from '../config.js'
+
+export type OutputFormat = 'json' | 'table'
+
+/**
+ * Prints an API result. JSON (pretty, stdout) is the default so output pipes
+ * cleanly into `jq`; `--format table` renders collections for humans.
+ */
+export function printResult(result: unknown, format: OutputFormat = 'json'): void {
+ if (result === undefined || result === null) return
+
+ if (format === 'table') {
+ const rows = collectionRows(result)
+ if (rows) {
+ printTable(rows.map(flattenScalars))
+ return
+ }
+ const record = flattenScalars(result as Record<string, unknown>)
+ printTable(Object.entries(record).map(([field, value]) => ({ field, value })))
+ return
+ }
+
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`)
+}
+
+function collectionRows(result: unknown): Record<string, unknown>[] | null {
+ if (Array.isArray(result)) return result as Record<string, unknown>[]
+ if (result && typeof result === 'object' && Array.isArray((result as { data?: unknown }).data)) {
+ return (result as { data: Record<string, unknown>[] }).data
+ }
+ return null
+}
+
+/** Keeps scalar fields; collapses nested objects/arrays so tables stay readable. */
+function flattenScalars(row: Record<string, unknown>): Record<string, unknown> {
+ const flat: Record<string, unknown> = {}
+ for (const [key, value] of Object.entries(row)) {
+ if (value === null || ['string', 'number', 'boolean'].includes(typeof value)) {
+ flat[key] = value
+ } else if (Array.isArray(value)) {
+ flat[key] = `[${value.length}]`
+ } else {
+ flat[key] = '{…}'
+ }
+ }
+ return flat
+}
+
+/**
+ * Maps failures to the documented exit codes: 1 for API errors (the
+ * Stripe-style error envelope goes to stderr), 2 for usage/configuration
+ * problems. Scope denials get the remediation hint — that text is what
+ * agents read to self-correct.
+ */
+export function handleApiError(error: unknown, context: { baseUrl?: string } = {}): never {
+ if (error instanceof SpreeError) {
+ const details = error.details ? `\n${JSON.stringify({ details: error.details }, null, 2)}` : ''
+ process.stderr.write(`${pc.red(`${error.code}:`)} ${error.message}${details}\n`)
+
+ const requiredScope = (error.details as Record<string, unknown> | undefined)?.required_scope
+ if (typeof requiredScope === 'string') {
+ // Complete the agent self-correction loop: mint the key AND wire it in.
+ process.stderr.write(
+ `${pc.dim(`Hint: this key lacks \`${requiredScope}\`. Create one that has it and use it:`)}\n` +
+ `${pc.dim(` spree api-key create --type secret --scopes ${requiredScope}`)}\n` +
+ `${pc.dim(' then pass it via --api-key <sk_...> or export SPREE_API_KEY=<sk_...>')}\n`,
+ )
+ }
+ process.exit(1)
+ }
+
+ if (error instanceof CredentialError) {
+ process.stderr.write(`${pc.red('error:')} ${error.message}\n`)
+ process.exit(2)
+ }
+
+ // A fetch TypeError ("fetch failed") hides the real cause (ECONNREFUSED,
+ // DNS failure, TLS) in error.cause — surface it with the target URL.
+ if (error instanceof TypeError && /fetch failed/i.test(error.message)) {
+ const cause = (error as { cause?: unknown }).cause
+ const causeMessage = cause instanceof Error ? cause.message : cause ? String(cause) : ''
+ const target = context.baseUrl ? ` (${context.baseUrl})` : ''
+ process.stderr.write(
+ `${pc.red('error:')} could not reach the server${target}${causeMessage ? `: ${causeMessage}` : ''}\n`,
+ )
+ process.stderr.write(
+ `${pc.dim('Hint: check the URL, or run `spree api status` to diagnose reachability and credentials.')}\n`,
+ )
+ process.exit(2)
+ }
+
+ const message = error instanceof Error ? error.message : String(error)
+ process.stderr.write(`${pc.red('error:')} ${message}\n`)
+ process.exit(2)
+}
diff --git a/packages/cli/src/api/params.ts b/packages/cli/src/api/params.ts
new file mode 100644
index 0000000000..73875da638
--- /dev/null
+++ b/packages/cli/src/api/params.ts
@@ -0,0 +1,80 @@
+/** Query-param assembly for `spree api get` — Ransack `-q` plus passthroughs. */
+
+export interface QueryFlags {
+ query?: string[]
+ sort?: string
+ page?: string
+ limit?: string
+ expand?: string
+ fields?: string
+}
+
+export type RequestParams = Record<
+ string,
+ string | number | boolean | (string | number)[] | undefined
+>
+
+/**
+ * Turns repeatable `-q key=value` expressions into Ransack `q[...]` params and
+ * passes the pagination/shaping flags through under the Admin API conventions
+ * (`?sort=-created_at`, `?expand=variants`, `?fields=id,name`).
+ *
+ * A repeated predicate becomes an array param keyed `q[id_in][]` — the `[]`
+ * suffix is required, otherwise the query serializes as `q[id_in]=a&q[id_in]=b`
+ * and Rack's nested-query parser keeps only the last value (silently dropping
+ * the rest).
+ */
+export function buildParams(flags: QueryFlags): RequestParams {
+ // Collect values per predicate first, then key them with or without `[]`
+ // depending on whether the predicate repeated.
+ const values = new Map<string, string[]>()
+ for (const expression of flags.query ?? []) {
+ const eq = expression.indexOf('=')
+ if (eq <= 0) {
+ throw new Error(
+ `Invalid -q expression "${expression}" — expected key=value (e.g. -q status_eq=active)`,
+ )
+ }
+ const predicate = expression.slice(0, eq)
+ const value = expression.slice(eq + 1)
+ const existing = values.get(predicate)
+ if (existing) existing.push(value)
+ else values.set(predicate, [value])
+ }
+
+ const params: RequestParams = {}
+ for (const [predicate, vals] of values) {
+ if (vals.length > 1) {
+ params[`q[${predicate}][]`] = vals
+ } else {
+ params[`q[${predicate}]`] = vals[0]
+ }
+ }
+
+ if (flags.sort) params.sort = flags.sort
+ if (flags.page !== undefined) params.page = parsePositiveInt(flags.page, '--page')
+ if (flags.limit !== undefined) params.limit = parsePositiveInt(flags.limit, '--limit')
+ if (flags.expand) params.expand = flags.expand
+ if (flags.fields) params.fields = flags.fields
+
+ return params
+}
+
+function parsePositiveInt(value: string, flag: string): number {
+ if (!/^[1-9]\d*$/.test(value)) {
+ throw new Error(`Invalid ${flag} "${value}" — expected a positive integer`)
+ }
+ return Number(value)
+}
+
+/**
+ * Normalizes the user-supplied path: a leading slash is optional, and pasting
+ * a full `/api/v3/admin/...` path (e.g. from docs or logs) just works.
+ */
+export function normalizePath(input: string): string {
+ let path = input.startsWith('/') ? input : `/${input}`
+ if (path.startsWith('/api/v3/admin')) {
+ path = path.slice('/api/v3/admin'.length) || '/'
+ }
+ return path
+}
diff --git a/packages/cli/src/api/ping.ts b/packages/cli/src/api/ping.ts
new file mode 100644
index 0000000000..b9995a2f48
--- /dev/null
+++ b/packages/cli/src/api/ping.ts
@@ -0,0 +1,40 @@
+import { createAdminClient, SpreeError } from '@spree/admin-sdk'
+
+export type PingStatus = 'connected' | 'forbidden' | 'unauthorized' | 'unreachable'
+
+export interface PingResult {
+ status: PingStatus
+ /** Present when the key can read store settings. */
+ storeName?: string
+ message?: string
+}
+
+/**
+ * Validates a credential pair with one cheap call. `GET /store` needs
+ * `read_settings`, so a 403 still proves the key authenticates — it just
+ * lacks that scope; only a 401 means the key itself is invalid.
+ */
+export async function pingCredentials(baseUrl: string, apiKey: string): Promise<PingResult> {
+ const client = createAdminClient({ baseUrl, secretKey: apiKey, retry: false })
+
+ try {
+ const store = await client.request<{ name?: string }>('GET', '/store', {})
+ return { status: 'connected', storeName: store?.name }
+ } catch (error) {
+ if (error instanceof SpreeError) {
+ // 401 = bad key; 403 = valid key, just lacks read_settings. Any other
+ // status means the key authenticated but the server errored — report it
+ // distinctly rather than claiming a clean connection.
+ if (error.status === 401) return { status: 'unauthorized', message: error.message }
+ if (error.status === 403) return { status: 'forbidden' }
+ return {
+ status: 'unreachable',
+ message: `server responded HTTP ${error.status}: ${error.message}`,
+ }
+ }
+ // A non-SpreeError here is a transport failure or a non-JSON response body
+ // (e.g. an HTML error page from a proxy) that the SDK couldn't parse.
+ const message = error instanceof Error ? error.message : String(error)
+ return { status: 'unreachable', message }
+ }
+}
diff --git a/packages/cli/src/api/spec.ts b/packages/cli/src/api/spec.ts
new file mode 100644
index 0000000000..3ca4273280
--- /dev/null
+++ b/packages/cli/src/api/spec.ts
@@ -0,0 +1,189 @@
+/**
+ * Schema introspection over the bundled Admin API OpenAPI snapshot
+ * (src/generated/admin-spec.json, regenerated per release by
+ * scripts/bundle-spec.mjs). Powers `spree api endpoints` / `spree api schema`.
+ */
+
+import adminSpecJson from '../generated/admin-spec.json' with { type: 'json' }
+
+export interface OpenApiOperation {
+ summary?: string
+ description?: string
+ tags?: string[]
+ parameters?: Array<Record<string, unknown>>
+ requestBody?: Record<string, unknown>
+ responses?: Record<string, unknown>
+}
+
+export interface AdminSpec {
+ info?: { title?: string; version?: string }
+ paths: Record<string, Record<string, OpenApiOperation>>
+ components: { schemas: Record<string, unknown> }
+}
+
+export interface EndpointRow {
+ method: string
+ path: string
+ scope: string
+ summary: string
+}
+
+const HTTP_METHODS = new Set(['get', 'post', 'put', 'patch', 'delete'])
+
+export function loadBundledSpec(): AdminSpec {
+ return adminSpecJson as unknown as AdminSpec
+}
+
+/**
+ * Extracts the `**Required scope:** ...` line rswag writes into operation
+ * descriptions. Free-form notes (e.g. exports — gated by the exported
+ * resource) come through verbatim.
+ */
+export function requiredScope(operation: OpenApiOperation): string {
+ const match = operation.description?.match(
+ /\*\*Required scope:\*\* (.+?) \(for API-key authentication\)\./,
+ )
+ if (!match) return '—'
+ return match[1].replaceAll('`', '')
+}
+
+export function listEndpoints(
+ spec: AdminSpec,
+ filter: { resource?: string; search?: string } = {},
+): EndpointRow[] {
+ const rows: EndpointRow[] = []
+
+ for (const [specPath, methods] of Object.entries(spec.paths)) {
+ const shortPath = specPath.replace('/api/v3/admin', '') || '/'
+
+ for (const [method, operation] of Object.entries(methods)) {
+ if (!HTTP_METHODS.has(method)) continue
+
+ if (filter.resource) {
+ const segment = shortPath.split('/')[1] ?? ''
+ if (segment !== filter.resource && !segment.startsWith(filter.resource)) continue
+ }
+
+ const summary = operation.summary ?? ''
+ if (filter.search) {
+ const haystack = `${method} ${shortPath} ${summary}`.toLowerCase()
+ if (!haystack.includes(filter.search.toLowerCase())) continue
+ }
+
+ rows.push({
+ method: method.toUpperCase(),
+ path: shortPath,
+ scope: requiredScope(operation),
+ summary,
+ })
+ }
+ }
+
+ return rows
+}
+
+export interface SchemaResult {
+ method: string
+ path: string
+ summary?: string
+ description?: string
+ parameters?: unknown
+ requestBody?: unknown
+ responses?: unknown
+}
+
+/**
+ * Returns the full operation schema for `METHOD /path` (method optional when
+ * the path has exactly one operation), with `$ref`s resolved inline so the
+ * output is self-contained. Matching tolerates the `/api/v3/admin` prefix and
+ * concrete IDs in place of `{id}` placeholders.
+ */
+export function getSchema(spec: AdminSpec, target: string): SchemaResult[] {
+ const parts = target.trim().split(/\s+/)
+ const method = parts.length > 1 ? parts[0].toLowerCase() : undefined
+ const rawPath = parts.length > 1 ? parts[1] : parts[0]
+
+ let lookupPath = rawPath.startsWith('/') ? rawPath : `/${rawPath}`
+ if (lookupPath.startsWith('/api/v3/admin')) {
+ lookupPath = lookupPath.slice('/api/v3/admin'.length) || '/'
+ }
+
+ // Router precedence: an exact literal path wins over a `{id}` template, so
+ // `/payment_methods/types` resolves to itself and not to `/payment_methods/{id}`.
+ const exact = collectMatches(spec, method, (specPath) => specPath === lookupPath)
+ if (exact.length > 0) return exact
+ return collectMatches(spec, method, (specPath) => pathMatches(specPath, lookupPath))
+}
+
+function collectMatches(
+ spec: AdminSpec,
+ method: string | undefined,
+ pathMatcher: (shortPath: string) => boolean,
+): SchemaResult[] {
+ const matches: SchemaResult[] = []
+ for (const [specPath, methods] of Object.entries(spec.paths)) {
+ const shortPath = specPath.replace('/api/v3/admin', '') || '/'
+ if (!pathMatcher(shortPath)) continue
+
+ for (const [specMethod, operation] of Object.entries(methods)) {
+ if (!HTTP_METHODS.has(specMethod)) continue
+ if (method && specMethod !== method) continue
+
+ matches.push({
+ method: specMethod.toUpperCase(),
+ path: shortPath,
+ summary: operation.summary,
+ description: operation.description,
+ parameters: resolveRefs(operation.parameters, spec),
+ requestBody: resolveRefs(operation.requestBody, spec),
+ responses: resolveRefs(operation.responses, spec),
+ })
+ }
+ }
+
+ return matches
+}
+
+/** `/orders/{id}` matches `/orders/{id}` and `/orders/ord_x8k2J9aQ`. */
+function pathMatches(specPath: string, lookupPath: string): boolean {
+ if (specPath === lookupPath) return true
+
+ const specSegments = specPath.split('/')
+ const lookupSegments = lookupPath.split('/')
+ if (specSegments.length !== lookupSegments.length) return false
+
+ return specSegments.every((segment, i) => {
+ if (segment.startsWith('{') && segment.endsWith('}')) return lookupSegments[i].length > 0
+ return segment === lookupSegments[i]
+ })
+}
+
+const MAX_REF_DEPTH = 8
+
+/**
+ * Inlines `$ref` pointers (only `#/components/schemas/*` appears in rswag
+ * output). Depth-limited and cycle-safe: a re-entered or too-deep ref stays
+ * as the raw pointer string.
+ */
+export function resolveRefs(node: unknown, spec: AdminSpec, seen: string[] = []): unknown {
+ if (Array.isArray(node)) {
+ return node.map((item) => resolveRefs(item, spec, seen))
+ }
+ if (!node || typeof node !== 'object') return node
+
+ const record = node as Record<string, unknown>
+ const ref = record.$ref
+ if (typeof ref === 'string') {
+ const name = ref.replace('#/components/schemas/', '')
+ if (seen.includes(name) || seen.length >= MAX_REF_DEPTH || !(name in spec.components.schemas)) {
+ return { $ref: ref }
+ }
+ return resolveRefs(spec.components.schemas[name], spec, [...seen, name])
+ }
+
+ const resolved: Record<string, unknown> = {}
+ for (const [key, value] of Object.entries(record)) {
+ resolved[key] = resolveRefs(value, spec, seen)
+ }
+ return resolved
+}
diff --git a/packages/cli/src/commands/api.ts b/packages/cli/src/commands/api.ts
new file mode 100644
index 0000000000..238b783b30
--- /dev/null
+++ b/packages/cli/src/commands/api.ts
@@ -0,0 +1,227 @@
+import { createAdminClient } from '@spree/admin-sdk'
+import { type Command, Option } from 'commander'
+import { printTable } from 'console-table-printer'
+import pc from 'picocolors'
+import { NO_BODY, readBody } from '../api/body.js'
+import { handleApiError, type OutputFormat, printResult } from '../api/output.js'
+import { buildParams, normalizePath } from '../api/params.js'
+import { pingCredentials } from '../api/ping.js'
+import { getSchema, listEndpoints, loadBundledSpec } from '../api/spec.js'
+import { type ResolvedCredentials, resolveCredentials } from '../config.js'
+
+interface SharedFlags {
+ profile?: string
+ baseUrl?: string
+ apiKey?: string
+ storeId?: string
+ format?: OutputFormat
+}
+
+interface VerbFlags extends SharedFlags {
+ query: string[]
+ sort?: string
+ page?: string
+ limit?: string
+ expand?: string
+ fields?: string
+ data?: string
+}
+
+function collect(value: string, previous: string[]): string[] {
+ return [...previous, value]
+}
+
+/** Credential flags shared by every subcommand that hits the API. */
+function withCredentialFlags(command: Command): Command {
+ return command
+ .option('--profile <name>', 'use a saved profile (see `spree auth`)')
+ .option('--base-url <url>', 'store URL (overrides profile/env/project)')
+ .option(
+ '--api-key <key>',
+ 'secret API key (prefer SPREE_API_KEY — flags leak into shell history)',
+ )
+ .option('--store-id <id>', 'X-Spree-Store-Id for hosts serving multiple stores')
+}
+
+/** Credential flags plus `--format` for verbs that render a response. */
+function withSharedFlags(command: Command): Command {
+ return withCredentialFlags(command).addOption(
+ new Option('--format <format>', 'output format').choices(['json', 'table']).default('json'),
+ )
+}
+
+async function clientFor(
+ flags: SharedFlags,
+): Promise<{ client: ReturnType<typeof createAdminClient>; credentials: ResolvedCredentials }> {
+ const credentials = await resolveCredentials({
+ baseUrl: flags.baseUrl,
+ apiKey: flags.apiKey,
+ profile: flags.profile,
+ })
+ const client = createAdminClient({
+ baseUrl: credentials.baseUrl,
+ secretKey: credentials.apiKey,
+ ...(flags.storeId ? { storeId: flags.storeId } : {}),
+ })
+ return { client, credentials }
+}
+
+export function registerApiCommand(program: Command): void {
+ const api = program
+ .command('api')
+ .description('Call the Admin API directly (gh api-style generic verbs)')
+
+ // --- Read verb -----------------------------------------------------------
+
+ withSharedFlags(
+ api
+ .command('get <path>')
+ .description('GET an Admin API path, e.g. `spree api get /products -q status_eq=active`')
+ .option('-q, --query <expr>', 'Ransack predicate key=value (repeatable)', collect, [])
+ .option('--sort <fields>', 'sort, e.g. -created_at')
+ .option('--page <n>', 'page number')
+ .option('--limit <n>', 'page size (max 100)')
+ .option('--expand <relations>', 'expand relations, e.g. variants,variants.prices')
+ .option('--fields <fields>', 'sparse fields, e.g. id,name'),
+ ).action(async (path: string, flags: VerbFlags) => {
+ let baseUrl: string | undefined
+ try {
+ // Build params before touching credentials so a typo'd -q fails fast
+ // (exit 2) without triggering project key-minting.
+ const params = buildParams(flags)
+ const { client, credentials } = await clientFor(flags)
+ baseUrl = credentials.baseUrl
+ const result = await client.request('GET', normalizePath(path), { params })
+ printResult(result, flags.format)
+ } catch (error) {
+ handleApiError(error, { baseUrl })
+ }
+ })
+
+ // --- Write verbs ---------------------------------------------------------
+
+ for (const method of ['post', 'patch', 'delete'] as const) {
+ withSharedFlags(
+ api
+ .command(`${method} <path>`)
+ .description(`${method.toUpperCase()} an Admin API path`)
+ .option('-d, --data <json>', "request body: inline JSON, @file, or '-' for stdin"),
+ ).action(async (path: string, flags: VerbFlags) => {
+ let baseUrl: string | undefined
+ try {
+ // Read+parse the body before resolving credentials, so invalid JSON or
+ // a missing file fails fast without minting a project key.
+ const body = await readBody(flags.data)
+ const { client, credentials } = await clientFor(flags)
+ baseUrl = credentials.baseUrl
+ const result = await client.request(method.toUpperCase(), normalizePath(path), {
+ ...(body === NO_BODY ? {} : { body }),
+ })
+ printResult(result, flags.format)
+ } catch (error) {
+ handleApiError(error, { baseUrl })
+ }
+ })
+ }
+
+ // --- Schema introspection (bundled OpenAPI snapshot) ----------------------
+
+ api
+ .command('endpoints')
+ .description('List Admin API endpoints with their required scopes')
+ .option('--resource <name>', 'filter by first path segment, e.g. orders')
+ .option('--search <term>', 'filter by method, path, or summary')
+ .addOption(
+ new Option('--format <format>', 'output format').choices(['json', 'table']).default('json'),
+ )
+ .action((flags: { resource?: string; search?: string; format: OutputFormat }) => {
+ const rows = listEndpoints(loadBundledSpec(), {
+ resource: flags.resource,
+ search: flags.search,
+ })
+ if (rows.length === 0) {
+ process.stderr.write('No endpoints match.\n')
+ process.exitCode = 1
+ return
+ }
+ if (flags.format === 'table') {
+ printTable(
+ rows.map((row) => ({
+ Method: row.method,
+ Path: row.path,
+ Scope: row.scope,
+ Summary: row.summary,
+ })),
+ )
+ return
+ }
+ printResult(rows, 'json')
+ })
+
+ api
+ .command('schema <operation>')
+ .description(
+ 'Show the request/response schema for an operation, e.g. `spree api schema "POST /products"`',
+ )
+ .action((operation: string) => {
+ const matches = getSchema(loadBundledSpec(), operation)
+ if (matches.length === 0) {
+ process.stderr.write(
+ `No operation matches "${operation}". Try \`spree api endpoints --search ${operation.split(/\s+/).pop()}\`.\n`,
+ )
+ process.exitCode = 1
+ return
+ }
+ // A fully-qualified "METHOD /path" matches at most one operation → emit
+ // the bare object; an ambiguous lookup always emits an array so the
+ // shape is predictable for scripts.
+ const fullyQualified = /\s/.test(operation.trim())
+ printResult(fullyQualified && matches.length === 1 ? matches[0] : matches, 'json')
+ })
+
+ // --- Connection check ----------------------------------------------------
+
+ withCredentialFlags(
+ api
+ .command('status')
+ .description('Show resolved credentials, server reachability, and the bundled spec version'),
+ ).action(async (flags: SharedFlags) => {
+ try {
+ const credentials = await resolveCredentials(
+ { baseUrl: flags.baseUrl, apiKey: flags.apiKey, profile: flags.profile },
+ { allowMint: false },
+ )
+ const ping = await pingCredentials(credentials.baseUrl, credentials.apiKey)
+ const spec = loadBundledSpec()
+
+ const serverLine = {
+ connected: pc.green(`connected${ping.storeName ? ` (${ping.storeName})` : ''}`),
+ forbidden:
+ pc.green('connected') + pc.dim(' (key valid; lacks read_settings for store details)'),
+ unauthorized: pc.red('key rejected (401)'),
+ unreachable: pc.red(`unreachable — ${ping.message}`),
+ }[ping.status]
+
+ const lines = [
+ `${pc.bold('Base URL:')} ${credentials.baseUrl}`,
+ `${pc.bold('Credentials:')} ${credentials.source}${credentials.profileName ? ` (${credentials.profileName})` : ''}, key ${credentials.tokenPrefix}${pc.dim('…')}`,
+ ]
+ // Scopes are known only for project-minted keys; profile/env/flag keys
+ // are opaque (we never see the granted scope list for them).
+ if (credentials.scopes?.length) {
+ lines.push(`${pc.bold('Scopes:')} ${credentials.scopes.join(', ')}`)
+ }
+ lines.push(`${pc.bold('Server:')} ${serverLine}`)
+ lines.push(
+ `${pc.bold('Bundled spec:')} ${spec.info?.version ?? 'unknown'} ${pc.dim('(spree api endpoints/schema reflect this snapshot, not the live server)')}`,
+ )
+ process.stdout.write(`${lines.join('\n')}\n`)
+
+ if (ping.status === 'unauthorized' || ping.status === 'unreachable') {
+ process.exitCode = 1
+ }
+ } catch (error) {
+ handleApiError(error, { baseUrl: flags.baseUrl })
+ }
+ })
+}
diff --git a/packages/cli/src/commands/auth.ts b/packages/cli/src/commands/auth.ts
new file mode 100644
index 0000000000..c1ebadf76d
--- /dev/null
+++ b/packages/cli/src/commands/auth.ts
@@ -0,0 +1,207 @@
+import * as p from '@clack/prompts'
+import type { Command } from 'commander'
+import { printTable } from 'console-table-printer'
+import pc from 'picocolors'
+import { handleApiError } from '../api/output.js'
+import { pingCredentials } from '../api/ping.js'
+import {
+ configPath,
+ projectCredentialsPath,
+ readConfig,
+ resolveCredentials,
+ tokenPrefix,
+ writeConfig,
+} from '../config.js'
+import { detectProject } from '../context.js'
+
+export function registerAuthCommand(program: Command): void {
+ const auth = program
+ .command('auth')
+ .description('Manage Admin API credentials (profiles in ~/.config/spree)')
+
+ auth
+ .command('login')
+ .description('Save a secret API key as a named profile')
+ .option('--profile <name>', 'profile name', 'default')
+ .option('--base-url <url>', 'store URL, e.g. https://store.example.com')
+ .action(async (flags: { profile: string; baseUrl?: string }) => {
+ // `login` is interactive (the key is prompted, never a flag, so it can't
+ // leak into shell history). In a non-TTY there's nothing to prompt —
+ // fail loudly with the non-interactive alternative rather than hang or
+ // exit 0 having saved nothing.
+ if (!process.stdin.isTTY) {
+ process.stderr.write(
+ `${pc.red('error:')} \`spree auth login\` is interactive. For non-interactive use, set ` +
+ 'SPREE_BASE_URL + SPREE_API_KEY (or pass --base-url/--api-key to `spree api`).\n',
+ )
+ process.exit(2)
+ }
+
+ let baseUrl = flags.baseUrl
+ if (!baseUrl) {
+ const result = await p.text({
+ message: 'Store URL:',
+ placeholder: 'https://store.example.com',
+ validate(value) {
+ if (!value) return 'URL is required'
+ if (!/^https?:\/\//.test(value)) return 'Must start with http:// or https://'
+ return undefined
+ },
+ })
+ if (p.isCancel(result)) {
+ p.cancel('Cancelled.')
+ process.exit(130)
+ }
+ baseUrl = result
+ }
+ baseUrl = baseUrl.replace(/\/$/, '')
+
+ // The key is read from an interactive prompt, never a flag — flags leak
+ // into shell history and process lists. Create the key in the admin
+ // under Settings → API Keys.
+ const keyResult = await p.password({
+ message: 'Secret API key (sk_...):',
+ validate(value) {
+ if (!value) return 'Key is required'
+ if (!value.startsWith('sk_')) return 'Admin API keys start with sk_'
+ return undefined
+ },
+ })
+ if (p.isCancel(keyResult)) {
+ p.cancel('Cancelled.')
+ process.exit(130)
+ }
+ const token = keyResult
+
+ const s = p.spinner()
+ s.start('Validating credentials...')
+ const ping = await pingCredentials(baseUrl, token)
+ if (ping.status === 'unauthorized') {
+ s.stop(pc.red('The server rejected this key (401). Check the key and try again.'))
+ process.exit(2)
+ }
+ if (ping.status === 'unreachable') {
+ s.stop(pc.red(`Could not reach ${baseUrl}: ${ping.message}`))
+ process.exit(2)
+ }
+ s.stop(
+ ping.storeName
+ ? `Connected to ${pc.bold(ping.storeName)}.`
+ : 'Credentials accepted (key lacks read_settings, so the store name is hidden — that is fine).',
+ )
+
+ const config = readConfig()
+ config.profiles[flags.profile] = { baseUrl, token }
+ config.defaultProfile ||= flags.profile
+ writeConfig(config)
+
+ p.note(
+ [
+ `${pc.bold('Profile:')} ${flags.profile}${config.defaultProfile === flags.profile ? pc.dim(' (default)') : ''}`,
+ `${pc.bold('Base URL:')} ${baseUrl}`,
+ `${pc.bold('Key:')} ${tokenPrefix(token)}${pc.dim('…')}`,
+ '',
+ pc.dim(`Saved to ${configPath()}`),
+ ].join('\n'),
+ 'Logged in',
+ )
+ })
+
+ auth
+ .command('status')
+ .description('Show which credentials `spree api` would use, and verify them')
+ .option('--profile <name>', 'check a specific profile')
+ .action(async (flags: { profile?: string }) => {
+ let credentials: Awaited<ReturnType<typeof resolveCredentials>>
+ try {
+ credentials = await resolveCredentials({ profile: flags.profile }, { allowMint: false })
+ } catch (error) {
+ // Maps CredentialError → exit 2 with the lowercase `error:` prefix,
+ // matching the `spree api` verbs.
+ handleApiError(error)
+ }
+
+ const s = p.spinner()
+ s.start('Checking server...')
+ const ping = await pingCredentials(credentials.baseUrl, credentials.apiKey)
+ s.stop('')
+
+ const statusLine = {
+ connected: pc.green(`connected${ping.storeName ? ` (${ping.storeName})` : ''}`),
+ forbidden:
+ pc.green('connected') + pc.dim(' (key valid; lacks read_settings for store details)'),
+ unauthorized: pc.red('key rejected (401)'),
+ unreachable: pc.red(`unreachable — ${ping.message}`),
+ }[ping.status]
+
+ p.note(
+ [
+ `${pc.bold('Source:')} ${credentials.source}${credentials.profileName ? ` (${credentials.profileName})` : ''}`,
+ `${pc.bold('Base URL:')} ${credentials.baseUrl}`,
+ `${pc.bold('Key:')} ${credentials.tokenPrefix}${pc.dim('…')}`,
+ ...(credentials.scopes
+ ? [`${pc.bold('Scopes:')} ${credentials.scopes.join(', ')}`]
+ : []),
+ `${pc.bold('Server:')} ${statusLine}`,
+ ].join('\n'),
+ 'Auth status',
+ )
+ })
+
+ auth
+ .command('logout')
+ .description('Remove a saved profile (or the project credentials)')
+ .option('--profile <name>', 'profile to remove', 'default')
+ .option('--project', 'remove .spree/credentials.json from the current project instead')
+ .action(async (flags: { profile: string; project?: boolean }) => {
+ if (flags.project) {
+ const { projectDir } = detectProject()
+ const fs = await import('node:fs')
+ fs.rmSync(projectCredentialsPath(projectDir), { force: true })
+ p.log.success(
+ 'Removed project credentials. The next `spree api` call mints a fresh read-only key.',
+ )
+ return
+ }
+
+ const config = readConfig()
+ if (!config.profiles[flags.profile]) {
+ const names = Object.keys(config.profiles)
+ const available = names.length
+ ? ` Saved profiles: ${names.join(', ')}.`
+ : ' No profiles are saved.'
+ process.stderr.write(
+ `${pc.red('error:')} no profile named "${flags.profile}".${available}\n`,
+ )
+ process.exit(2)
+ }
+ delete config.profiles[flags.profile]
+ if (config.defaultProfile === flags.profile) {
+ config.defaultProfile = Object.keys(config.profiles)[0]
+ }
+ writeConfig(config)
+ p.log.success(
+ `Removed profile "${flags.profile}". The key itself stays active — revoke it with \`spree api-key revoke\` or in the admin.`,
+ )
+ })
+
+ auth
+ .command('list')
+ .description('List saved profiles')
+ .action(() => {
+ const config = readConfig()
+ const names = Object.keys(config.profiles)
+ if (names.length === 0) {
+ p.log.info('No profiles saved. Run `spree auth login` to add one.')
+ return
+ }
+
+ printTable(
+ names.map((name) => ({
+ Profile: config.defaultProfile === name ? `${name} *` : name,
+ 'Base URL': config.profiles[name].baseUrl,
+ Key: `${tokenPrefix(config.profiles[name].token)}…`,
+ })),
+ )
+ })
+}
diff --git a/packages/cli/src/config.ts b/packages/cli/src/config.ts
new file mode 100644
index 0000000000..3eceba548d
--- /dev/null
+++ b/packages/cli/src/config.ts
@@ -0,0 +1,329 @@
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import pc from 'picocolors'
+import { detectProject } from './context.js'
+import { rakeTask } from './docker.js'
+
+/**
+ * Credential resolution for `spree api` / `spree auth`.
+ *
+ * The API key anchors a layer: host and key resolve together per source, so a
+ * saved/minted secret key is never paired with a host from another source. An
+ * explicit `--base-url` (or `--api-key`) flag overrides the resolved field —
+ * the only sanctioned cross-source mix, since the user typed it deliberately.
+ *
+ * 1. flags --base-url / --api-key (and --profile, which selects a
+ * saved profile explicitly and then outranks env)
+ * 2. env SPREE_API_KEY (+ SPREE_BASE_URL); SPREE_BASE_URL alone
+ * never pairs with a lower-layer key
+ * 3. project .spree/credentials.json next to docker-compose.yml,
+ * auto-minted (read_all) on first use via the dev stack
+ * 4. profile ~/.config/spree/config.json, default profile
+ */
+
+export interface CredentialFlags {
+ baseUrl?: string
+ apiKey?: string
+ profile?: string
+}
+
+export type CredentialSource = 'flags' | 'env' | 'project' | 'profile'
+
+export interface ResolvedCredentials {
+ baseUrl: string
+ apiKey: string
+ source: CredentialSource
+ profileName?: string
+ /** First 12 chars of the key — safe to display. */
+ tokenPrefix: string
+ /** Known only for project-minted keys (profiles store the key opaquely). */
+ scopes?: string[]
+}
+
+export interface ProfileEntry {
+ baseUrl: string
+ token: string
+}
+
+export interface CliConfig {
+ defaultProfile?: string
+ profiles: Record<string, ProfileEntry>
+}
+
+export interface ProjectCredentials {
+ baseUrl: string
+ token: string
+ scopes: string[]
+ mintedAt: string
+}
+
+/** Thrown for resolution/usage problems — mapped to exit code 2. */
+export class CredentialError extends Error {}
+
+export function configDir(): string {
+ return process.env.XDG_CONFIG_HOME
+ ? path.join(process.env.XDG_CONFIG_HOME, 'spree')
+ : path.join(os.homedir(), '.config', 'spree')
+}
+
+export function configPath(): string {
+ return path.join(configDir(), 'config.json')
+}
+
+export function readConfig(): CliConfig {
+ let raw: string
+ try {
+ raw = fs.readFileSync(configPath(), 'utf-8')
+ } catch {
+ // No config file yet — first run.
+ return { profiles: {} }
+ }
+
+ try {
+ const parsed = JSON.parse(raw) as Partial<CliConfig>
+ return { ...parsed, profiles: parsed.profiles ?? {} }
+ } catch {
+ // The file exists but is corrupt. Back it up rather than silently
+ // returning an empty config — otherwise the next `writeConfig` would
+ // overwrite (and destroy) whatever profiles were in there.
+ const backup = `${configPath()}.bak`
+ try {
+ fs.renameSync(configPath(), backup)
+ } catch {
+ // best effort
+ }
+ process.stderr.write(
+ `${pc.yellow(`warning: ${configPath()} was not valid JSON; moved it to ${backup} and starting fresh.`)}\n`,
+ )
+ return { profiles: {} }
+ }
+}
+
+export function writeConfig(config: CliConfig): void {
+ fs.mkdirSync(configDir(), { recursive: true, mode: 0o700 })
+ writeFilePrivate(configPath(), `${JSON.stringify(config, null, 2)}\n`)
+}
+
+/**
+ * Writes a file readable only by the owner. `mode` on writeFileSync is
+ * ignored when the file already exists, so chmod unconditionally afterward to
+ * tighten any pre-existing (possibly world-readable) credential file.
+ */
+function writeFilePrivate(file: string, contents: string): void {
+ fs.writeFileSync(file, contents, { mode: 0o600 })
+ fs.chmodSync(file, 0o600)
+}
+
+export function projectCredentialsPath(projectDir: string): string {
+ return path.join(projectDir, '.spree', 'credentials.json')
+}
+
+export function readProjectCredentials(projectDir: string): ProjectCredentials | null {
+ try {
+ return JSON.parse(
+ fs.readFileSync(projectCredentialsPath(projectDir), 'utf-8'),
+ ) as ProjectCredentials
+ } catch {
+ return null
+ }
+}
+
+export function writeProjectCredentials(projectDir: string, credentials: ProjectCredentials): void {
+ const file = projectCredentialsPath(projectDir)
+ const dir = path.dirname(file)
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
+ // Make the directory self-ignoring so the minted key never gets committed,
+ // independent of the project's own .gitignore vintage (the create-spree-app
+ // entry only covers freshly scaffolded projects).
+ const gitignore = path.join(dir, '.gitignore')
+ if (!fs.existsSync(gitignore)) {
+ fs.writeFileSync(gitignore, '*\n')
+ }
+ writeFilePrivate(file, `${JSON.stringify(credentials, null, 2)}\n`)
+}
+
+export function tokenPrefix(token: string): string {
+ return token.slice(0, 12)
+}
+
+/**
+ * Auto-mints a read-only secret key through the project's dev stack and
+ * persists it in `.spree/credentials.json` (gitignored). Write scopes are
+ * never minted implicitly — `spree api-key create --scopes write_...` is the
+ * explicit path.
+ */
+async function mintProjectCredentials(
+ projectDir: string,
+ port: number,
+): Promise<ProjectCredentials> {
+ process.stderr.write(
+ `${pc.dim('No credentials found — minting a read-only API key via the dev stack...')}\n`,
+ )
+
+ let stdout: string
+ try {
+ stdout = await rakeTask('spree:cli:create_api_key', projectDir, {
+ NAME: '@spree/cli (auto)',
+ KEY_TYPE: 'secret',
+ SCOPES: 'read_all',
+ })
+ } catch (error) {
+ const detail = error instanceof Error ? error.message.split('\n')[0] : String(error)
+ throw new CredentialError(
+ `Could not mint an API key via the dev stack. Is it running? Start it with \`spree dev\`.\n${pc.dim(detail)}`,
+ )
+ }
+
+ const match = stdout.match(/sk_[A-Za-z0-9_-]+/)
+ if (!match) {
+ throw new CredentialError(
+ 'Could not mint an API key via the dev stack. Is it running? Start it with `spree dev`.',
+ )
+ }
+
+ const credentials: ProjectCredentials = {
+ baseUrl: `http://localhost:${port}`,
+ token: match[0],
+ scopes: ['read_all'],
+ mintedAt: new Date().toISOString(),
+ }
+ writeProjectCredentials(projectDir, credentials)
+ process.stderr.write(`${pc.dim(`Saved to .spree/credentials.json (scopes: read_all)`)}\n`)
+ return credentials
+}
+
+export interface ResolveOptions {
+ /** Mint a project key when inside a project with no credentials (default true). */
+ allowMint?: boolean
+ /** Working directory for project detection (tests). */
+ cwd?: string
+}
+
+export async function resolveCredentials(
+ flags: CredentialFlags,
+ options: ResolveOptions = {},
+): Promise<ResolvedCredentials> {
+ const { allowMint = true, cwd = process.cwd() } = options
+ const config = readConfig()
+
+ // The KEY anchors a layer: each layer (other than flags) contributes its
+ // token together with its own base URL, so a saved/minted secret key is
+ // never paired with a host from a different trust domain. The only
+ // sanctioned cross-layer mix is an explicit `--base-url`/`--api-key` flag,
+ // which the user typed on purpose; those override whatever a layer resolved.
+ const flagBaseUrl = flags.baseUrl
+ const flagApiKey = flags.apiKey
+
+ let resolved:
+ | {
+ baseUrl?: string
+ apiKey: string
+ source: CredentialSource
+ profileName?: string
+ scopes?: string[]
+ }
+ | undefined
+
+ // Layer 1 — explicit --api-key flag.
+ if (flagApiKey) {
+ resolved = { apiKey: flagApiKey, source: 'flags' }
+ }
+
+ // --profile is an explicit selection of a saved profile; it outranks env.
+ if (!resolved && flags.profile) {
+ const profile = config.profiles[flags.profile]
+ if (!profile) {
+ throw new CredentialError(
+ `Unknown profile "${flags.profile}". Run \`spree auth login --profile ${flags.profile}\` to create it.`,
+ )
+ }
+ resolved = {
+ baseUrl: profile.baseUrl,
+ apiKey: profile.token,
+ source: 'profile',
+ profileName: flags.profile,
+ }
+ }
+
+ // Layer 2 — environment. The pair is anchored on SPREE_API_KEY; SPREE_BASE_URL
+ // alone never pairs with a lower-layer key (that was the exfiltration path).
+ if (!resolved && process.env.SPREE_API_KEY) {
+ resolved = {
+ baseUrl: process.env.SPREE_BASE_URL,
+ apiKey: process.env.SPREE_API_KEY,
+ source: 'env',
+ }
+ }
+
+ // Layer 3 — project credentials (auto-minted on first use). Skipped when an
+ // explicit --base-url points somewhere other than this project, so a remote
+ // command never silently mints a local key.
+ if (!resolved) {
+ let projectDir: string | undefined
+ let port = 0
+ try {
+ const ctx = detectProject(cwd)
+ projectDir = ctx.projectDir
+ port = ctx.port
+ } catch {
+ // not a Spree project directory — fall through
+ }
+
+ if (projectDir) {
+ const projectUrl = `http://localhost:${port}`
+ const targetsThisProject = !flagBaseUrl || flagBaseUrl.replace(/\/$/, '') === projectUrl
+ let credentials = readProjectCredentials(projectDir)
+ if (!credentials && allowMint && targetsThisProject) {
+ credentials = await mintProjectCredentials(projectDir, port)
+ }
+ if (credentials) {
+ resolved = {
+ baseUrl: credentials.baseUrl,
+ apiKey: credentials.token,
+ source: 'project',
+ scopes: credentials.scopes,
+ }
+ }
+ }
+ }
+
+ // Layer 4 — default profile.
+ if (!resolved && config.defaultProfile) {
+ const profile = config.profiles[config.defaultProfile]
+ if (profile) {
+ resolved = {
+ baseUrl: profile.baseUrl,
+ apiKey: profile.token,
+ source: 'profile',
+ profileName: config.defaultProfile,
+ }
+ }
+ }
+
+ // An explicit --base-url always wins (re-point a key at staging, etc.); a
+ // flag pairing is the user's deliberate cross-layer mix.
+ const baseUrl = flagBaseUrl ?? resolved?.baseUrl
+ const apiKey = resolved?.apiKey
+
+ if (!baseUrl || !apiKey) {
+ throw new CredentialError(
+ [
+ 'No Admin API credentials found. Provide them via one of (host and key resolve together per source):',
+ ' - flags: --base-url <url> --api-key <sk_...>',
+ ' - env: SPREE_BASE_URL + SPREE_API_KEY',
+ ' - project: run inside a Spree project with the dev stack up (auto-mints a read-only key)',
+ ' - profile: spree auth login --profile <name>',
+ ].join('\n'),
+ )
+ }
+
+ return {
+ baseUrl,
+ apiKey,
+ source: resolved?.source ?? 'flags',
+ profileName: resolved?.profileName,
+ tokenPrefix: tokenPrefix(apiKey),
+ scopes: resolved?.scopes,
+ }
+}
diff --git a/packages/cli/src/generated/admin-spec.json b/packages/cli/src/generated/admin-spec.json
new file mode 100644
index 0000000000..3870987913
--- /dev/null
+++ b/packages/cli/src/generated/admin-spec.json
@@ -0,0 +1 @@
+{"info":{"title":"Admin API","contact":{"name":"Spree Commerce","url":"https://spreecommerce.org","email":"[email protected]"},"description":"Spree Admin API v3 - Administrative API for managing products, orders, and store settings.\n\n## Authentication\n\nThe Admin API requires a secret API key passed in the `x-spree-api-key` header.\nSecret API keys can be generated in the Spree admin dashboard.\n\n## Response Format\n\nAll responses are JSON. List endpoints return paginated responses with `data` and `meta` keys.\nSingle resource endpoints return a flat JSON object.\n\n## Resource IDs\n\nEvery resource is identified by an opaque string ID (e.g. `prod_86Rf07xd4z`,\n`variant_k5nR8xLq`, `or_UkLWZg9DAJ`). Use these IDs everywhere — URL paths,\nrequest bodies, and Ransack filters all accept them directly.\n\n## Error Handling\n\nErrors return a consistent format:\n```json\n{\n \"error\": {\n \"code\": \"validation_error\",\n \"message\": \"Validation failed\",\n \"details\": { \"name\": [\"can't be blank\"] }\n }\n}\n```\n","version":"v3"},"paths":{"/api/v3/admin/auth/login":{"post":{"summary":"Login","tags":["Authentication"],"security":[{"api_key":[]}],"description":"Authenticates an admin user and returns a short-lived JWT access token.\nThe rotatable refresh token is set in an HttpOnly cookie — it is not\nincluded in the response body.\n\nDispatches by the `provider` field to a strategy registered in\n`Spree.admin_authentication_strategies`. When `provider` is omitted it\ndefaults to `email`, which uses the built-in email/password strategy.\n\nTo plug in a third-party identity provider (Okta, Azure AD, Google\nWorkspace SSO, a custom JWT issuer, SAML, etc.), register a\n`Spree::Authentication::Strategies::BaseStrategy` subclass under a\nprovider key, then send `{ \"provider\": \"<your_key>\", ... }` with the\nfields your strategy requires. The endpoint returns the same Spree-issued\nJWT regardless of which strategy authenticated the request.\n","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"login successful","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AuthResponse"}}}},"401":{"description":"invalid credentials","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"oneOf":[{"title":"EmailPasswordLogin","description":"Built-in email/password authentication (default when `provider` is omitted).","type":"object","properties":{"provider":{"type":"string","enum":["email"],"default":"email"},"email":{"type":"string","format":"email"},"password":{"type":"string"}},"required":["email","password"]},{"title":"ProviderLogin","description":"Provider-dispatched login. The `provider` key selects a registered\nstrategy class; the remaining fields are forwarded to the strategy's\n`authenticate` method. Required fields depend on the registered strategy\n— consult its documentation.\n","type":"object","properties":{"provider":{"type":"string","description":"Registered provider key (anything other than `email`).","not":{"enum":["email"]}}},"required":["provider"],"additionalProperties":true}]}}}}}},"/api/v3/admin/auth/refresh":{"post":{"summary":"Refresh token","tags":["Authentication"],"security":[{"api_key":[]}],"description":"Exchanges the HttpOnly refresh-token cookie for a new access JWT and a\nrotated refresh token cookie. No request body or Authorization header\nis required — the cookie alone authenticates the call.\n","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"refresh successful","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AuthResponse"}}}},"401":{"description":"missing or invalid refresh-token cookie","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/api/v3/admin/auth/logout":{"post":{"summary":"Logout","tags":["Authentication"],"security":[{"api_key":[]}],"description":"Revokes the refresh-token cookie, effectively logging the admin out.","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"204":{"description":"logout successful"}}}},"/api/v3/admin/me":{"get":{"summary":"Get current admin user and permissions","tags":["Authentication"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns the current admin user profile and a serialized list of permissions (CanCanCan rules). The SPA uses these to drive UI permission checks.","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}}],"responses":{"200":{"description":"current admin user and permissions","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MeResponse"}}}},"401":{"description":"unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/api/v3/admin/allowed_origins":{"get":{"summary":"List allowed origins","tags":["Allowed Origins"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns the CORS allowlist for the current store. Each entry is a\nbare `scheme://host[:port]` permitted to call the admin API from a\nbrowser. Backs the `Rack::Cors` allowlist and the CSRF boundary of\nthe admin cookie session (see\n`docs/plans/5.5-admin-auth-cookie-refresh.md`).\n\n\n**Required scope:** `read_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"page","in":"query","required":false,"description":"Page number","schema":{"type":"integer"}},{"name":"limit","in":"query","required":false,"description":"Number of records per page","schema":{"type":"integer"}},{"name":"q[origin_cont]","in":"query","required":false,"description":"Filter by origin (contains)","schema":{"type":"string"}},{"name":"sort","in":"query","required":false,"description":"Sort by field. Prefix with `-` for descending (e.g., `-created_at`).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include. id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"allowed origins found","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/AllowedOrigin"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"required":["data","meta"]}}}},"401":{"description":"unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}},"post":{"summary":"Create an allowed origin","tags":["Allowed Origins"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Adds an origin to the admin CORS allowlist. The value must be a bare\n`scheme://host[:port]` (no path, query, or fragment) and use `http` or\n`https`.\n\n\n**Required scope:** `write_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}}],"responses":{"201":{"description":"allowed origin created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AllowedOrigin"}}}},"422":{"description":"validation error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"origin":{"type":"string"}},"required":["origin"]}}}}}},"/api/v3/admin/allowed_origins/{id}":{"parameters":[{"name":"id","in":"path","required":true,"description":"Allowed origin ID","schema":{"type":"string"}}],"get":{"summary":"Get an allowed origin","tags":["Allowed Origins"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns a single allowed origin by prefixed ID.\n\n**Required scope:** `read_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include. id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"allowed origin found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AllowedOrigin"}}}},"404":{"description":"allowed origin not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}},"patch":{"summary":"Update an allowed origin","tags":["Allowed Origins"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Updates an existing allowed origin.\n\n**Required scope:** `write_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}}],"responses":{"200":{"description":"allowed origin updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AllowedOrigin"}}}},"422":{"description":"validation error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"origin":{"type":"string"}}}}}}},"delete":{"summary":"Delete an allowed origin","tags":["Allowed Origins"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Removes an origin from the admin CORS allowlist. After deletion the\nadmin SPA running at that origin will no longer be able to call the\nadmin API from a browser.\n\n\n**Required scope:** `write_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}}],"responses":{"204":{"description":"allowed origin deleted"}}}},"/api/v3/admin/api_keys":{"get":{"summary":"List API keys","tags":["API Keys"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns publishable and secret API keys for the current store. Secret keys are listed by `token_prefix` only — the plaintext token is delivered exactly once on create.\n\n**Required scope:** `read_api_keys` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"API keys found","content":{"application/json":{}}}}},"post":{"summary":"Create an API key","tags":["API Keys"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Creates a publishable or secret API key. The plaintext token is included in the response **once** for secret keys; publishable keys expose their token on every read since they are intended for client-side use.\n\n**Required scope:** `write_api_keys` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"201":{"description":"secret key created — plaintext token returned once","content":{"application/json":{}}},"422":{"description":"validation error","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["name","key_type"],"properties":{"name":{"type":"string"},"key_type":{"type":"string","enum":["publishable","secret"]},"scopes":{"type":"array","items":{"type":"string"}}}}}}}}},"/api/v3/admin/api_keys/{id}":{"get":{"summary":"Show an API key","tags":["API Keys"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"**Required scope:** `read_api_keys` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"API key found","content":{"application/json":{}}}}},"delete":{"summary":"Delete an API key","tags":["API Keys"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"**Required scope:** `write_api_keys` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"204":{"description":"API key deleted"}}}},"/api/v3/admin/api_keys/{id}/revoke":{"patch":{"summary":"Revoke an API key","tags":["API Keys"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Marks the key revoked. Future requests using its token will fail; the row is preserved for audit.\n\n**Required scope:** `write_api_keys` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"API key revoked","content":{"application/json":{}}}}}},"/api/v3/admin/channels":{"get":{"summary":"List channels","tags":["Channels"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns the channels configured for the current store.\n\n**Required scope:** `read_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"page","in":"query","required":false,"schema":{"type":"integer"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer"}}],"responses":{"200":{"description":"channels found","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Channel"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"required":["data","meta"]}}}}}},"post":{"summary":"Create a channel","tags":["Channels"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Creates a new channel on the current store. `code` is normalized to a\nURL-safe slug (`Point of Sale` → `point-of-sale`); when omitted it's\nderived from `name`.\n\n\n**Required scope:** `write_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"201":{"description":"channel created","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["name"],"properties":{"name":{"type":"string"},"code":{"type":"string","description":"Slug — auto-derived from `name` when blank."},"active":{"type":"boolean","default":true}}}}}}}},"/api/v3/admin/channels/{id}":{"parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"get":{"summary":"Get a channel","tags":["Channels"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"**Required scope:** `read_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"channel found","content":{"application/json":{}}}}},"patch":{"summary":"Update a channel","tags":["Channels"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"**Required scope:** `write_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"channel updated","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string"},"code":{"type":"string"},"active":{"type":"boolean"}}}}}}},"delete":{"summary":"Delete a channel","tags":["Channels"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"**Required scope:** `write_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"204":{"description":"channel deleted"}}}},"/api/v3/admin/channels/{id}/add_products":{"parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"post":{"summary":"Publish products on a channel","tags":["Channels"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Publishes the listed products on this channel. Idempotent — re-publishing\nan already-published product updates its publication window. Products from\nsibling stores are silently dropped.\n\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"products published","content":{"application/json":{"schema":{"type":"object","properties":{"product_count":{"type":"integer"}}}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["product_ids"],"properties":{"product_ids":{"type":"array","items":{"type":"string"}},"published_at":{"type":"string","format":"date-time","nullable":true,"description":"When the publications go live. `null` means immediately."},"unpublished_at":{"type":"string","format":"date-time","nullable":true,"description":"When the publications come down. `null` means never."}}}}}}}},"/api/v3/admin/channels/{id}/remove_products":{"parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"post":{"summary":"Unpublish products from a channel","tags":["Channels"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Unpublishes the listed products from this channel.\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"products unpublished","content":{"application/json":{"schema":{"type":"object","properties":{"product_count":{"type":"integer"}}}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["product_ids"],"properties":{"product_ids":{"type":"array","items":{"type":"string"}}}}}}}}},"/api/v3/admin/custom_field_definitions":{"get":{"summary":"List custom field definitions","tags":["Custom Fields"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns all defined custom fields. Filter by `?q[resource_type_eq]=Spree::Product` to narrow to one parent type.\n\n**Required scope:** `read_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand. Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., key,label,field_type). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"definitions returned","content":{"application/json":{}}}}},"post":{"summary":"Create a custom field definition","tags":["Custom Fields"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"**Required scope:** `write_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"201":{"description":"definition created","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["key","field_type","resource_type"],"properties":{"namespace":{"type":"string","description":"Defaults to `custom`"},"key":{"type":"string"},"label":{"type":"string","description":"Human-readable name; defaults to titleized `key`"},"field_type":{"type":"string","description":"Custom field type identifier (one of the registered field-type class names)."},"resource_type":{"type":"string","description":"Owner class, e.g. `Spree::Product`"},"storefront_visible":{"type":"boolean","description":"When false, definition is admin-only (was `display_on: back_end`)"}}}}}}}},"/api/v3/admin/custom_field_definitions/{id}":{"get":{"summary":"Show a custom field definition","tags":["Custom Fields"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"**Required scope:** `read_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand. Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., key,label,field_type). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"definition found","content":{"application/json":{}}}}},"patch":{"summary":"Update a custom field definition","tags":["Custom Fields"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"**Required scope:** `write_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"definition updated","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"label":{"type":"string"},"storefront_visible":{"type":"boolean"}}}}}}},"delete":{"summary":"Delete a custom field definition","tags":["Custom Fields"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Deletes the definition and cascades to all custom field values referencing it.\n\n**Required scope:** `write_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"204":{"description":"definition deleted"}}}},"/api/v3/admin/customer_groups":{"get":{"summary":"List customer groups","tags":["Customer Groups"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns the customer groups configured for the current store. Groups\nsegment customers for targeted promotions (see the `customer_group`\npromotion rule) and reporting. The list endpoint never embeds the\nmember list — fetch a single group with `?expand=customers` if you\nneed them inline, or query `/admin/customers?customer_group_id_in=…`\nfor paginated membership.\n\n\n**Required scope:** `read_customers` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"page","in":"query","required":false,"description":"Page number","schema":{"type":"integer"}},{"name":"limit","in":"query","required":false,"description":"Number of records per page","schema":{"type":"integer"}},{"name":"q[name_cont]","in":"query","required":false,"description":"Filter by name (contains)","schema":{"type":"string"}},{"name":"sort","in":"query","required":false,"description":"Sort by field. Prefix with `-` for descending (e.g., `-created_at`).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include. id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"customer groups found","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/CustomerGroup"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"required":["data","meta"]}}}},"401":{"description":"unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}},"post":{"summary":"Create a customer group","tags":["Customer Groups"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Creates a customer group in the current store. `customer_ids` is\noptional; when present, customers are attached at create time.\nPass prefixed IDs (e.g. `cus_…`) — the server decodes them\nautomatically.\n\n\n**Required scope:** `write_customers` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"201":{"description":"customer group created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CustomerGroup"}}}},"422":{"description":"validation error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["name"],"properties":{"name":{"type":"string"},"description":{"type":"string","nullable":true},"customer_ids":{"type":"array","items":{"type":"string"}}}}}}}}},"/api/v3/admin/customer_groups/{id}":{"parameters":[{"name":"id","in":"path","required":true,"description":"Customer group prefixed ID","schema":{"type":"string"}}],"get":{"summary":"Get a customer group","tags":["Customer Groups"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns a single customer group. Pass `?expand=customers` to embed\nthe full member list inline (recommended only for single-record\nreads — embed cost scales with membership size).\n\n\n**Required scope:** `read_customers` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to embed. Supported: `customers`.","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include. id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"customer group with embedded customers","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CustomerGroup"}}}},"404":{"description":"customer group not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}},"patch":{"summary":"Update a customer group","tags":["Customer Groups"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Updates name, description, or membership. `customer_ids` is a\nfull-set replacement — the server reconciles the membership to\nmatch the array, adding new IDs and removing ones not present.\nSend `customer_ids: []` to clear all members.\n\n\n**Required scope:** `write_customers` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"customer group updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CustomerGroup"}}}},"422":{"description":"validation error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string"},"description":{"type":"string","nullable":true},"customer_ids":{"type":"array","items":{"type":"string"}}}}}}}},"delete":{"summary":"Delete a customer group","tags":["Customer Groups"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Soft-deletes the group. Member users are not deleted; their `customer_group_users` rows are dropped.\n\n**Required scope:** `write_customers` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"204":{"description":"customer group deleted"}}}},"/api/v3/admin/customers/{customer_id}/addresses":{"get":{"summary":"List customer addresses","tags":["Customers"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns the customer's saved addresses.\n\n**Required scope:** `read_customers` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"customer_id","in":"path","required":true,"schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand (e.g., country, state). Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., first_name,last_name,address1,city). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"addresses found","content":{"application/json":{}}}}},"post":{"summary":"Create a customer address","tags":["Customers"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Adds a new address to the customer's address book. Pass `is_default_billing: true` or `is_default_shipping: true` to set as the default — the previous default loses its flag in the same transaction.\n\n**Required scope:** `write_customers` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"customer_id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"201":{"description":"address created","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"first_name":{"type":"string"},"last_name":{"type":"string"},"address1":{"type":"string"},"address2":{"type":"string"},"city":{"type":"string"},"postal_code":{"type":"string"},"country_iso":{"type":"string","description":"ISO-2 country code (e.g. US)"},"state_abbr":{"type":"string","description":"State/province abbreviation (e.g. NY)"},"phone":{"type":"string"},"company":{"type":"string"},"label":{"type":"string"},"is_default_billing":{"type":"boolean"},"is_default_shipping":{"type":"boolean"}}}}}}}},"/api/v3/admin/customers/{customer_id}/addresses/{id}":{"patch":{"summary":"Update a customer address","tags":["Customers"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Updates a customer address.\n\n**Required scope:** `write_customers` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"customer_id","in":"path","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"address updated","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"city":{"type":"string"},"is_default_billing":{"type":"boolean"},"is_default_shipping":{"type":"boolean"}}}}}}},"delete":{"summary":"Delete a customer address","tags":["Customers"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Deletes the address. If it was a default, the customer loses that default (no auto-promotion).\n\n**Required scope:** `write_customers` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"customer_id","in":"path","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"204":{"description":"address deleted"}}}},"/api/v3/admin/customers/{customer_id}/credit_cards":{"get":{"summary":"List customer credit cards","tags":["Customers"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns the customer's saved credit cards. Useful for off-session admin charges via `POST /admin/orders/:id/payments { source_id }`.\n\n**Required scope:** `read_customers` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"customer_id","in":"path","required":true,"schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand (e.g., payment_method). Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., brand,last4,month,year). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"credit cards found","content":{"application/json":{}}}}}},"/api/v3/admin/customers/{customer_id}/credit_cards/{id}":{"get":{"summary":"Show a customer credit card","tags":["Customers"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns a saved credit card by ID.\n\n**Required scope:** `read_customers` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"customer_id","in":"path","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand (e.g., payment_method). Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., brand,last4,month,year). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"credit card found","content":{"application/json":{}}}}},"delete":{"summary":"Delete a customer credit card","tags":["Customers"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Deletes a saved credit card.\n\n**Required scope:** `write_customers` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"customer_id","in":"path","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"204":{"description":"credit card deleted"}}}},"/api/v3/admin/customers/{customer_id}/store_credits":{"get":{"summary":"List customer store credits","tags":["Customers"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns store credits issued to the customer.\n\n**Required scope:** `read_store_credits` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"customer_id","in":"path","required":true,"schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand (e.g., category, store, created_by). Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., amount,amount_used,memo,currency). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"store credits found","content":{"application/json":{}}}}},"post":{"summary":"Issue a store credit to a customer","tags":["Customers"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"`created_by` is set automatically from the authenticated admin.\n\n**Required scope:** `write_store_credits` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"customer_id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"201":{"description":"store credit created","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["amount","currency","category_id"],"properties":{"amount":{"type":"number"},"currency":{"type":"string"},"category_id":{"type":"string","description":"StoreCreditCategory ID"},"memo":{"type":"string"}}}}}}}},"/api/v3/admin/customers/{customer_id}/store_credits/{id}":{"patch":{"summary":"Update a store credit","tags":["Customers"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Update memo / category / amount. The amount can only be changed if `amount_used == 0`.\n\n**Required scope:** `write_store_credits` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"customer_id","in":"path","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"store credit updated","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"amount":{"type":"number"},"category_id":{"type":"string"},"memo":{"type":"string"}}}}}}},"delete":{"summary":"Delete a store credit","tags":["Customers"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Deletes an unused store credit (amount_used == 0). Returns 422 otherwise.\n\n**Required scope:** `write_store_credits` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"customer_id","in":"path","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"204":{"description":"store credit deleted"}}}},"/api/v3/admin/customers":{"get":{"summary":"List customers","tags":["Customers"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns a paginated list of customers. Supports Ransack search/filters.\n\n**Required scope:** `read_customers` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"page","in":"query","required":false,"schema":{"type":"integer"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer"}},{"name":"q[search]","in":"query","required":false,"description":"Email + name full-text-ish search","schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand (e.g., addresses, store_credits). Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., email,first_name,last_name). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"customers found","content":{"application/json":{}}}}},"post":{"summary":"Create a customer","tags":["Customers"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Creates a customer. No welcome email is sent automatically.\n\n**Required scope:** `write_customers` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"201":{"description":"customer created","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["email"],"properties":{"email":{"type":"string"},"first_name":{"type":"string"},"last_name":{"type":"string"},"phone":{"type":"string"},"accepts_email_marketing":{"type":"boolean"},"internal_note":{"type":"string"},"tags":{"type":"array","items":{"type":"string"}},"metadata":{"type":"object"}}}}}}}},"/api/v3/admin/customers/{id}":{"get":{"summary":"Show a customer","tags":["Customers"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns full customer details including computed order stats (orders_count, total_spent, last_order_completed_at).\n\n**Required scope:** `read_customers` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Customer ID","schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations: addresses, orders, store_credits, default_billing_address, default_shipping_address","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., email,first_name,last_name). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"customer found","content":{"application/json":{}}}}},"patch":{"summary":"Update a customer","tags":["Customers"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Updates customer attributes. `tags` replaces the full set.\n\n**Required scope:** `write_customers` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"customer updated","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"email":{"type":"string"},"first_name":{"type":"string"},"last_name":{"type":"string"},"phone":{"type":"string"},"accepts_email_marketing":{"type":"boolean"},"internal_note":{"type":"string"},"tags":{"type":"array","items":{"type":"string"}},"metadata":{"type":"object"}}}}}}},"delete":{"summary":"Delete a customer","tags":["Customers"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Deletes a customer. Returns 422 if the customer has any orders.\n\n**Required scope:** `write_customers` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"204":{"description":"customer deleted"}}}},"/api/v3/admin/customers/bulk_add_to_groups":{"post":{"summary":"Bulk-add customers to groups","tags":["Customers"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Attaches each customer in `ids` to every group in `customer_group_ids`.\nIdempotent — customers already in a group are skipped server-side.\nGroups from sibling stores are silently ignored. Returns counts of\ncustomers and groups that were processed (post store-scoping).\n\n\n**Required scope:** `write_customers` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"customers added to groups","content":{"application/json":{"schema":{"type":"object","properties":{"customer_count":{"type":"integer"},"customer_group_count":{"type":"integer"}}}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["ids","customer_group_ids"],"properties":{"ids":{"type":"array","items":{"type":"string"}},"customer_group_ids":{"type":"array","items":{"type":"string"}}}}}}}}},"/api/v3/admin/customers/bulk_remove_from_groups":{"post":{"summary":"Bulk-remove customers from groups","tags":["Customers"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Detaches each customer in `ids` from every group in `customer_group_ids`.\nNo-op for non-members. Groups from sibling stores are silently ignored.\n\n\n**Required scope:** `write_customers` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"customers removed from groups","content":{"application/json":{"schema":{"type":"object","properties":{"customer_count":{"type":"integer"},"customer_group_count":{"type":"integer"}}}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["ids","customer_group_ids"],"properties":{"ids":{"type":"array","items":{"type":"string"}},"customer_group_ids":{"type":"array","items":{"type":"string"}}}}}}}}},"/api/v3/admin/customers/bulk_add_tags":{"post":{"summary":"Bulk-add tags to customers","tags":["Customers"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Adds each tag name in `tags` to every customer in `ids`. Tags are\nupserted by name; re-adding an existing tag is a no-op.\n\n\n**Required scope:** `write_customers` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"tags added","content":{"application/json":{"schema":{"type":"object","properties":{"customer_count":{"type":"integer"},"tag_count":{"type":"integer"}}}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["ids","tags"],"properties":{"ids":{"type":"array","items":{"type":"string"}},"tags":{"type":"array","items":{"type":"string"}}}}}}}}},"/api/v3/admin/customers/bulk_remove_tags":{"post":{"summary":"Bulk-remove tags from customers","tags":["Customers"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Removes each tag name in `tags` from every customer in `ids`. No-op\nfor customers that don't carry the tag.\n\n\n**Required scope:** `write_customers` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"tags removed","content":{"application/json":{"schema":{"type":"object","properties":{"customer_count":{"type":"integer"},"tag_count":{"type":"integer"}}}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["ids","tags"],"properties":{"ids":{"type":"array","items":{"type":"string"}},"tags":{"type":"array","items":{"type":"string"}}}}}}}}},"/api/v3/admin/exports":{"get":{"summary":"List exports","tags":["Exports"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns CSV exports queued or completed for the current store. Polled by the admin SPA to detect when an export finishes (`done: true`).\n\n**Required scope:** the read scope of the exported resource — `read_products` for product exports, `read_customers` for customer exports, etc. (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"exports found","content":{"application/json":{}}}}},"post":{"summary":"Create an export","tags":["Exports"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Queues a CSV export. The `type` selects the dataset; `search_params` is an\noptional Ransack query (same shape used by the `q[...]` params on list endpoints)\nthat filters which records are exported. Pass `record_selection: \"all\"` to\nclear the filter server-side and export everything in scope.\n\nGeneration is asynchronous. Poll `GET /admin/exports/{id}` until `done` is `true`,\nthen redirect the browser to `download_url` to fetch the file.\n\n\n**Required scope:** the read scope of the exported resource — `read_products` for product exports, `read_customers` for customer exports, etc. (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"201":{"description":"export queued","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["type"],"properties":{"type":{"type":"string","enum":["Spree::Exports::Products","Spree::Exports::Orders","Spree::Exports::Customers","Spree::Exports::ProductTranslations","Spree::Exports::GiftCards","Spree::Exports::CouponCodes","Spree::Exports::NewsletterSubscribers"]},"record_selection":{"type":"string","enum":["filtered","all"],"description":"Set to \"all\" to ignore search_params and export everything in scope."},"search_params":{"type":"object","description":"Ransack query hash. Same predicates accepted by the list endpoint.","additionalProperties":true}}}}}}}},"/api/v3/admin/exports/{id}":{"get":{"summary":"Show an export","tags":["Exports"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns export status. While `done` is `false`, the SPA continues polling.\n\n**Required scope:** the read scope of the exported resource — `read_products` for product exports, `read_customers` for customer exports, etc. (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"export found","content":{"application/json":{}}}}},"delete":{"summary":"Delete an export","tags":["Exports"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Removes the export and purges its attachment.\n\n**Required scope:** the read scope of the exported resource — `read_products` for product exports, `read_customers` for customer exports, etc. (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"204":{"description":"export deleted"}}}},"/api/v3/admin/exports/{id}/download":{"get":{"summary":"Download an export","tags":["Exports"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Streams the exported CSV with `Content-Disposition: attachment`. Returns 422 with `code: export_not_ready` while `done` is still `false`. The endpoint is JWT/API-key protected, so SPA clients must fetch it (with `Authorization` header) and trigger the browser download via a Blob URL — a top-level navigation cannot carry the JWT.\n\n**Required scope:** the read scope of the exported resource — `read_products` for product exports, `read_customers` for customer exports, etc. (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"CSV file","content":{"application/json":{},"text/csv":{"schema":{"type":"string","format":"binary"}}}}}}},"/api/v3/admin/orders/{order_id}/fulfillments":{"get":{"summary":"List fulfillments","tags":["Fulfillments"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns all shipments for an order.\n\n**Required scope:** `read_fulfillments` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"order_id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand (e.g., inventory_units, stock_location, shipping_rates). Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., number,status,tracking,cost). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"fulfillments found","content":{"application/json":{}}}}}},"/api/v3/admin/orders/{order_id}/fulfillments/{id}":{"get":{"summary":"Show a shipment","tags":["Fulfillments"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns details of a specific shipment.\n\n**Required scope:** `read_fulfillments` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"order_id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Fulfillment ID","schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand (e.g., inventory_units, stock_location, shipping_rates). Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., number,status,tracking,cost). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"shipment found","content":{"application/json":{}}}}},"patch":{"summary":"Update a shipment","tags":["Fulfillments"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Updates a shipment (tracking, shipping rate).\n\n**Required scope:** `write_fulfillments` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"order_id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Fulfillment ID","schema":{"type":"string"}}],"responses":{"200":{"description":"shipment updated","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"tracking":{"type":"string"},"selected_shipping_rate_id":{"type":"string"}}}}}}}},"/api/v3/admin/orders/{order_id}/fulfillments/{id}/fulfill":{"patch":{"summary":"Fulfill a fulfillment","tags":["Fulfillments"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Marks a fulfillment as fulfilled.\n\n**Required scope:** `write_fulfillments` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"order_id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Fulfillment ID","schema":{"type":"string"}}],"responses":{"200":{"description":"fulfillment fulfilled","content":{"application/json":{}}}}}},"/api/v3/admin/orders/{order_id}/fulfillments/{id}/cancel":{"patch":{"summary":"Cancel a fulfillment","tags":["Fulfillments"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Cancels a fulfillment.\n\n**Required scope:** `write_fulfillments` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"order_id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Fulfillment ID","schema":{"type":"string"}}],"responses":{"200":{"description":"fulfillment canceled","content":{"application/json":{}}}}}},"/api/v3/admin/orders/{order_id}/fulfillments/{id}/resume":{"patch":{"summary":"Resume a fulfillment","tags":["Fulfillments"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Resumes a canceled fulfillment.\n\n**Required scope:** `write_fulfillments` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"order_id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Fulfillment ID","schema":{"type":"string"}}],"responses":{"200":{"description":"fulfillment resumed","content":{"application/json":{}}}}}},"/api/v3/admin/orders/{order_id}/fulfillments/{id}/split":{"patch":{"summary":"Split a fulfillment","tags":["Fulfillments"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Transfers items from this shipment to a new shipment at a different stock location.\n\n**Required scope:** `write_fulfillments` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"order_id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Fulfillment ID","schema":{"type":"string"}}],"responses":{"200":{"description":"fulfillment split","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["variant_id","quantity"],"properties":{"variant_id":{"type":"string","description":"Variant ID"},"quantity":{"type":"integer"},"stock_location_id":{"type":"string","description":"Target stock location ID"}}}}}}}},"/api/v3/admin/gift_card_batches":{"get":{"summary":"List gift card batches","tags":["Gift Cards"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns the gift card batches issued by the current store. Each batch\ngroups the cards generated together for a campaign or bulk-issuance\n— the cards themselves live under `/admin/gift_cards` and reference\nthe batch via `gift_card_batch_id`.\n\n\n**Required scope:** `read_gift_cards` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"page","in":"query","required":false,"description":"Page number","schema":{"type":"integer"}},{"name":"limit","in":"query","required":false,"description":"Records per page","schema":{"type":"integer"}},{"name":"q[prefix_cont]","in":"query","required":false,"description":"Filter by prefix (contains)","schema":{"type":"string"}},{"name":"sort","in":"query","required":false,"description":"Sort by field. Prefix with `-` for descending.","schema":{"type":"string"}}],"responses":{"200":{"description":"gift card batches found","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/GiftCardBatch"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"required":["data","meta"]}}}}}},"post":{"summary":"Create a gift card batch","tags":["Gift Cards"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Issues a batch of gift cards in a single call. The server generates\n`codes_count` cards inline for small batches (configurable via\n`Spree.config.gift_card_batch_web_limit`, default 500) or enqueues\na background job for larger ones. Each card's code is the batch\n`prefix` followed by random hex.\n\n\n**Required scope:** `write_gift_cards` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"201":{"description":"gift card batch created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/GiftCardBatch"}}}},"422":{"description":"validation error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["prefix","amount","codes_count"],"properties":{"prefix":{"type":"string","description":"Lowercased and prepended to every generated code."},"amount":{"type":"string","description":"Decimal amount per card, greater than zero."},"currency":{"type":"string","description":"ISO 4217 currency code. Defaults to the store currency."},"codes_count":{"type":"integer","description":"Number of cards to generate. Capped at `gift_card_batch_limit`."},"expires_at":{"type":"string","nullable":true}}}}}}}},"/api/v3/admin/gift_card_batches/{id}":{"parameters":[{"name":"id","in":"path","required":true,"description":"Gift card batch prefixed ID","schema":{"type":"string"}}],"get":{"summary":"Get a gift card batch","tags":["Gift Cards"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns a single batch.\n\n**Required scope:** `read_gift_cards` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"gift card batch found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/GiftCardBatch"}}}},"404":{"description":"gift card batch not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/api/v3/admin/gift_cards":{"get":{"summary":"List gift cards","tags":["Gift Cards"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns the gift cards issued by the current store. Filter by\n`q[code_cont]` for code search, `q[user_id_eq]` for cards issued\nto a specific customer, or `q[state_eq]` for status filtering.\n\n\n**Required scope:** `read_gift_cards` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"page","in":"query","required":false,"description":"Page number","schema":{"type":"integer"}},{"name":"limit","in":"query","required":false,"description":"Number of records per page","schema":{"type":"integer"}},{"name":"q[code_cont]","in":"query","required":false,"description":"Filter by gift card code (contains)","schema":{"type":"string"}},{"name":"q[state_eq]","in":"query","required":false,"description":"Filter by status (active, redeemed, partially_redeemed, canceled)","schema":{"type":"string"}},{"name":"sort","in":"query","required":false,"description":"Sort by field. Prefix with `-` for descending (e.g., `-created_at`).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include. id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"gift cards found","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/GiftCard"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"required":["data","meta"]}}}},"401":{"description":"unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}},"post":{"summary":"Create a gift card","tags":["Gift Cards"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Issues a gift card scoped to the current store. The code is\nauto-generated when omitted. `currency` defaults to the store's\nconfigured currency. Pass `user_id` (prefixed ID) to attach the\ncard to a specific customer.\n\n\n**Required scope:** `write_gift_cards` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"201":{"description":"gift card created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/GiftCard"}}}},"422":{"description":"validation error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["amount"],"properties":{"amount":{"type":"string","description":"Decimal amount, greater than zero."},"currency":{"type":"string","description":"ISO 4217 currency code. Defaults to the store currency."},"code":{"type":"string","description":"Optional caller-supplied code. Auto-generated when omitted."},"expires_at":{"type":"string","description":"ISO 8601 date.","nullable":true},"user_id":{"type":"string","description":"Optional customer prefixed ID.","nullable":true}}}}}}}},"/api/v3/admin/gift_cards/{id}":{"parameters":[{"name":"id","in":"path","required":true,"description":"Gift card prefixed ID","schema":{"type":"string"}}],"get":{"summary":"Get a gift card","tags":["Gift Cards"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns a single gift card.\n\n**Required scope:** `read_gift_cards` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include. id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"gift card found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/GiftCard"}}}},"404":{"description":"gift card not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}},"patch":{"summary":"Update a gift card","tags":["Gift Cards"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Updates an active gift card's editable attributes. Redeemed or\npartially-redeemed cards cannot be edited.\n\n\n**Required scope:** `write_gift_cards` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"gift card updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/GiftCard"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"amount":{"type":"string"},"expires_at":{"type":"string","nullable":true},"user_id":{"type":"string","nullable":true}}}}}}},"delete":{"summary":"Delete a gift card","tags":["Gift Cards"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Deletes an unused gift card. Cards that have been redeemed or\npartially redeemed cannot be deleted and return 422.\n\n\n**Required scope:** `write_gift_cards` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"204":{"description":"gift card deleted"},"422":{"description":"redeemed gift card cannot be deleted","content":{"application/json":{}}}}}},"/api/v3/admin/markets":{"get":{"summary":"List markets","tags":["Markets"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns the markets configured for the current store. Markets are\nstore-scoped and ordered by `position` (an `acts_as_list` column —\nupdate the order via `PATCH /markets/{id}` with `position`).\n\n\n**Required scope:** `read_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"page","in":"query","required":false,"schema":{"type":"integer"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer"}},{"name":"q[name_cont]","in":"query","required":false,"schema":{"type":"string"}},{"name":"sort","in":"query","required":false,"schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to embed. Supported: `countries`.","schema":{"type":"string"}}],"responses":{"200":{"description":"markets found","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Market"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"required":["data","meta"]}}}}}},"post":{"summary":"Create a market","tags":["Markets"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Creates a new market for the current store.\n\n- `country_isos` accepts 2-letter ISO country codes (e.g. `[\"DE\", \"FR\"]`);\n the market must contain at least one country. Unknown codes are\n silently dropped.\n- `supported_locales` accepts an array of locale codes; the\n `default_locale` is always implicitly included.\n- Setting `default: true` automatically demotes the previous default\n market in the store.\n\n\n**Required scope:** `write_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"201":{"description":"market created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Market"}}}},"422":{"description":"validation error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string"},"currency":{"type":"string","description":"ISO 4217 currency code."},"default_locale":{"type":"string","description":"IETF locale tag used as the market default."},"supported_locales":{"type":"array","items":{"type":"string"},"description":"Locale codes available in this market. The default is always implicitly included."},"tax_inclusive":{"type":"boolean","default":false,"description":"Display prices with tax included."},"default":{"type":"boolean","default":false,"description":"Setting to true demotes the previous default."},"position":{"type":"integer","description":"Sort order within the store; lower = first."},"country_isos":{"type":"array","items":{"type":"string"},"description":"2-letter ISO country codes assigned to this market. At least one is required."}},"required":["name","currency","default_locale","country_isos"]}}}}}},"/api/v3/admin/markets/{id}":{"parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"get":{"summary":"Get a market","tags":["Markets"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"**Required scope:** `read_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"schema":{"type":"string"}}],"responses":{"200":{"description":"market found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Market"}}}},"404":{"description":"market not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}},"patch":{"summary":"Update a market","tags":["Markets"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Updates an existing market. Pass `country_isos` to replace the\nmarket's country list (full-set update), `supported_locales` to\nreplace the supported locales, or `position` to reorder the market\nwithin the store.\n\nSetting `default: true` automatically demotes the previous default.\n\n\n**Required scope:** `write_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"market updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Market"}}}},"422":{"description":"validation error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string"},"currency":{"type":"string"},"default_locale":{"type":"string"},"supported_locales":{"type":"array","items":{"type":"string"}},"tax_inclusive":{"type":"boolean"},"default":{"type":"boolean"},"position":{"type":"integer"},"country_isos":{"type":"array","items":{"type":"string"}}}}}}}},"delete":{"summary":"Delete a market","tags":["Markets"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Soft-deletes the market (sets `deleted_at`). The default market and\nthe last remaining market in a store cannot be deleted — both return\n422 with a `validation_error`.\n\n\n**Required scope:** `write_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"204":{"description":"market deleted"},"422":{"description":"cannot delete default or last market","content":{"application/json":{}}}}}},"/api/v3/admin/option_types":{"get":{"summary":"List option types","tags":["Option Types"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns a paginated list of option types.\n\n**Required scope:** `read_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"page","in":"query","required":false,"description":"Page number","schema":{"type":"integer"}},{"name":"limit","in":"query","required":false,"description":"Number of records per page","schema":{"type":"integer"}},{"name":"q[name_cont]","in":"query","required":false,"description":"Filter by name (contains)","schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand (e.g., option_values). Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., name,label,position). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"option types found","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/OptionType"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"required":["data","meta"]}}}},"401":{"description":"unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}},"post":{"summary":"Create an option type","tags":["Option Types"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Creates a new option type. Supports nested option values.\n\nOption values can be provided inline and will be created or updated by name.\n\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}}],"responses":{"201":{"description":"option type created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OptionType"}}}},"422":{"description":"validation error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string"},"label":{"type":"string"},"position":{"type":"integer"},"filterable":{"type":"boolean"},"option_values":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"label":{"type":"string"},"position":{"type":"integer"}}}}},"required":["name","label"]}}}}}},"/api/v3/admin/option_types/{id}":{"get":{"summary":"Get an option type","tags":["Option Types"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns a single option type by ID, including its option values.\n\n**Required scope:** `read_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Option type ID","schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand (e.g., option_values). Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., name,label,position). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"option type found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OptionType"}}}},"404":{"description":"option type not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}},"patch":{"summary":"Update an option type","tags":["Option Types"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Updates an option type. Supports updating nested option values.\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Option type ID","schema":{"type":"string"}}],"responses":{"200":{"description":"option type updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OptionType"}}}},"422":{"description":"validation error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string"},"label":{"type":"string"},"position":{"type":"integer"},"filterable":{"type":"boolean"},"option_values":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","description":"Existing option value ID to update"},"name":{"type":"string"},"label":{"type":"string"},"position":{"type":"integer"}}}}}}}}}},"delete":{"summary":"Delete an option type","tags":["Option Types"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Deletes an option type.\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Option type ID","schema":{"type":"string"}}],"responses":{"204":{"description":"option type deleted"}}}},"/api/v3/admin/orders/{order_id}/gift_cards":{"post":{"summary":"Apply a gift card to an order","tags":["Orders"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Applies a gift card by code to the order. Returns the gift card.\n\n**Required scope:** `write_gift_cards` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"order_id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}}],"responses":{"201":{"description":"gift card applied","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["code"],"properties":{"code":{"type":"string","description":"Gift card code"}}}}}}}},"/api/v3/admin/orders/{order_id}/gift_cards/{id}":{"delete":{"summary":"Remove a gift card from an order","tags":["Orders"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Removes the gift card from the order.\n\n**Required scope:** `write_gift_cards` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"order_id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Gift card ID","schema":{"type":"string"}}],"responses":{"204":{"description":"gift card removed"}}}},"/api/v3/admin/orders/{order_id}/items":{"get":{"summary":"List order items","tags":["Orders"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns all line items for an order.\n\n**Required scope:** `read_orders` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"order_id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand (e.g., variant, variant.product). Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., quantity,price,total). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"items found","content":{"application/json":{}}}}},"post":{"summary":"Add an item","tags":["Orders"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Adds a new line item to the order.\n\n**Required scope:** `write_orders` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"order_id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}}],"responses":{"201":{"description":"item added","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["variant_id"],"properties":{"variant_id":{"type":"string","description":"Prefixed variant ID"},"quantity":{"type":"integer","default":1}}}}}}}},"/api/v3/admin/orders/{order_id}/items/{id}":{"get":{"summary":"Show an item","tags":["Orders"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns details of a specific line item.\n\n**Required scope:** `read_orders` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"order_id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Item ID","schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand (e.g., variant, variant.product). Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., quantity,price,total). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"item found","content":{"application/json":{}}}}},"patch":{"summary":"Update an item","tags":["Orders"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Updates an order item quantity or metadata.\n\n**Required scope:** `write_orders` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"order_id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Item ID","schema":{"type":"string"}}],"responses":{"200":{"description":"item updated","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"quantity":{"type":"integer"}}}}}}},"delete":{"summary":"Remove an item","tags":["Orders"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Removes an item from the order.\n\n**Required scope:** `write_orders` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"order_id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Item ID","schema":{"type":"string"}}],"responses":{"204":{"description":"line item removed"}}}},"/api/v3/admin/orders/{order_id}/store_credits":{"post":{"summary":"Apply customer's store credit to an order","tags":["Orders"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Applies the order customer's available store credit. When `amount` is omitted, applies up to the order outstanding balance.\n\n**Required scope:** `write_store_credits` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"order_id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}}],"responses":{"201":{"description":"store credit applied","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"amount":{"type":"number","description":"Optional explicit amount; defaults to order outstanding balance"}}}}}}},"delete":{"summary":"Remove store credit from an order","tags":["Orders"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Removes any applied store credit from the order.\n\n**Required scope:** `write_store_credits` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"order_id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}}],"responses":{"204":{"description":"store credit removed"}}}},"/api/v3/admin/orders":{"get":{"summary":"List orders","tags":["Orders"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns a paginated list of orders for the current store.\n\n**Required scope:** `read_orders` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"page","in":"query","required":false,"description":"Page number","schema":{"type":"integer"}},{"name":"limit","in":"query","required":false,"description":"Number of records per page","schema":{"type":"integer"}},{"name":"sort","in":"query","required":false,"description":"Sort field (e.g., created_at, -created_at, completed_at)","schema":{"type":"string"}},{"name":"q[state_eq]","in":"query","required":false,"description":"Filter by state (cart, address, delivery, payment, confirm, complete, canceled)","schema":{"type":"string"}},{"name":"q[email_cont]","in":"query","required":false,"description":"Filter by email (contains)","schema":{"type":"string"}},{"name":"q[number_eq]","in":"query","required":false,"description":"Filter by order number","schema":{"type":"string"}},{"name":"q[completed_at_gt]","in":"query","required":false,"description":"Filter by completed after date","schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand (e.g., items, fulfillments, payments, customer, discounts, billing_address, shipping_address). Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., number,total,status,completed_at). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"orders found","content":{"application/json":{}}},"401":{"description":"unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}},"post":{"summary":"Create a draft order","tags":["Orders"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Creates a new draft order in one shot. Customer, items, addresses, currency,\nmarket, channel, locale, notes, metadata, and a coupon code can all be\nprovided inline.\n\nSetting `preferred_stock_location_id` pins the order's preferred fulfillment\nlocation — Order Routing's built-in `PreferredLocation` rule consumes it\nwhen picking which stock location ships each shipment.\n\nInvalid coupon codes are non-fatal — the order is created and the failure\nis reported on the service result (not in the API response body for now).\n\n\n**Required scope:** `write_orders` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}}],"responses":{"201":{"description":"order created with preferred_stock_location_id","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"email":{"type":"string"},"customer_id":{"type":"string","description":"Customer ID. Alias: user_id (legacy)."},"use_customer_default_address":{"type":"boolean","description":"When true with customer_id, copies the customer's saved billing/shipping addresses onto the order."},"currency":{"type":"string"},"market_id":{"type":"string","description":"Market ID"},"channel_id":{"type":"string","description":"Channel ID. Defaults to the store primary channel when omitted."},"preferred_stock_location_id":{"type":"string","description":"Stock Location ID to prefer for fulfillment. Order Routing's built-in PreferredLocation rule reads this and ranks the location first; routing falls back to the next rule when the preferred location can't cover the cart."},"locale":{"type":"string"},"customer_note":{"type":"string","description":"Public, customer-visible note"},"internal_note":{"type":"string","description":"Staff-only note"},"metadata":{"type":"object","description":"Arbitrary key/value metadata"},"shipping_address":{"type":"object","properties":{"first_name":{"type":"string"},"last_name":{"type":"string"},"address1":{"type":"string"},"city":{"type":"string"},"postal_code":{"type":"string"},"country_iso":{"type":"string"},"state_abbr":{"type":"string"},"phone":{"type":"string"}}},"shipping_address_id":{"type":"string","description":"Existing customer address ID"},"billing_address":{"type":"object","properties":{"first_name":{"type":"string"},"last_name":{"type":"string"},"address1":{"type":"string"},"city":{"type":"string"},"postal_code":{"type":"string"},"country_iso":{"type":"string"},"state_abbr":{"type":"string"},"phone":{"type":"string"}}},"billing_address_id":{"type":"string","description":"Existing customer address ID"},"items":{"type":"array","items":{"type":"object","required":["variant_id","quantity"],"properties":{"variant_id":{"type":"string","description":"Variant ID"},"quantity":{"type":"integer"},"metadata":{"type":"object"}}}},"coupon_code":{"type":"string","description":"Optional. Applied non-fatally; invalid codes do not block creation."}}}}}}}},"/api/v3/admin/orders/{id}":{"get":{"summary":"Show an order","tags":["Orders"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns full order details including admin-only fields.\n\n**Required scope:** `read_orders` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Order ID (e.g., or_xxx)","schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand (e.g., items, fulfillments, payments, customer, discounts, billing_address, shipping_address). Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., number,total,status,completed_at). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"order found","content":{"application/json":{}}},"404":{"description":"order not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}},"patch":{"summary":"Update an order","tags":["Orders"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Updates an order. Supports updating email, addresses, special instructions, and line items.\n\n**Required scope:** `write_orders` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}}],"responses":{"200":{"description":"order updated","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"email":{"type":"string"},"special_instructions":{"type":"string"},"internal_note":{"type":"string"},"channel_id":{"type":"string","description":"Channel ID"},"preferred_stock_location_id":{"type":"string","description":"Stock Location ID to prefer for fulfillment. Re-runs Order Routing's PreferredLocation rule on subsequent shipment rebuilds."},"ship_address":{"type":"object","properties":{"firstname":{"type":"string"},"lastname":{"type":"string"},"address1":{"type":"string"},"city":{"type":"string"},"zipcode":{"type":"string"},"country_iso":{"type":"string"},"state_abbr":{"type":"string"},"phone":{"type":"string"}}},"bill_address":{"type":"object","properties":{"firstname":{"type":"string"},"lastname":{"type":"string"},"address1":{"type":"string"},"city":{"type":"string"},"zipcode":{"type":"string"},"country_iso":{"type":"string"},"state_abbr":{"type":"string"},"phone":{"type":"string"}}},"items":{"type":"array","items":{"type":"object","required":["variant_id"],"properties":{"variant_id":{"type":"string","description":"Variant ID"},"quantity":{"type":"integer"},"metadata":{"type":"object"}}}}}}}}}},"delete":{"summary":"Delete a draft order","tags":["Orders"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Deletes a draft order. Completed orders cannot be deleted.\n\n**Required scope:** `write_orders` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}}],"responses":{"204":{"description":"order deleted"}}}},"/api/v3/admin/orders/{id}/complete":{"patch":{"summary":"Complete an order","tags":["Orders"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Completes an order in the `confirm` state, marking it as placed.\n\nSet `notify_customer: true` to send the order confirmation email.\n\n\n**Required scope:** `write_orders` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}}],"responses":{"200":{"description":"order completed","content":{"application/json":{}}},"422":{"description":"order cannot be completed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"notify_customer":{"type":"boolean","description":"Send the order confirmation email after completion."}}}}}}}},"/api/v3/admin/orders/{id}/cancel":{"patch":{"summary":"Cancel an order","tags":["Orders"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Cancels a completed order.\n\n**Required scope:** `write_orders` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}}],"responses":{"200":{"description":"order canceled","content":{"application/json":{}}}}}},"/api/v3/admin/orders/{id}/approve":{"patch":{"summary":"Approve an order","tags":["Orders"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Approves an order (e.g., for fraud review).\n\n**Required scope:** `write_orders` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}}],"responses":{"200":{"description":"order approved","content":{"application/json":{}}}}}},"/api/v3/admin/orders/{id}/resume":{"patch":{"summary":"Resume a canceled order","tags":["Orders"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Resumes a previously canceled order.\n\n**Required scope:** `write_orders` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}}],"responses":{"200":{"description":"order resumed","content":{"application/json":{}}}}}},"/api/v3/admin/orders/{id}/resend_confirmation":{"post":{"summary":"Resend confirmation email","tags":["Orders"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Publishes the order.completed event to trigger confirmation email delivery.\n\n**Required scope:** `write_orders` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}}],"responses":{"200":{"description":"confirmation resent","content":{"application/json":{}}}}}},"/api/v3/admin/payment_methods":{"get":{"summary":"List payment methods","tags":["Payment Methods"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns the store's configured payment methods. Use `source_required: true` to know which methods need a saved source.\n\n**Required scope:** `read_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand. Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., name,type,active). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"payment methods found","content":{"application/json":{}}}}}},"/api/v3/admin/payment_methods/types":{"get":{"summary":"List available payment provider types","tags":["Payment Methods"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns the registered Spree::PaymentMethod subclasses that can be used to create new payment methods. Useful for populating a \"Provider\" dropdown in admin UIs.\n\n**Required scope:** `read_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"provider types found","content":{"application/json":{}}}}}},"/api/v3/admin/payment_methods/{id}":{"get":{"summary":"Show a payment method","tags":["Payment Methods"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns a payment method by ID.\n\n**Required scope:** `read_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand. Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., name,type,active). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"payment method found","content":{"application/json":{}}}}}},"/api/v3/admin/orders/{order_id}/payments":{"get":{"summary":"List payments","tags":["Payments"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns all payments for an order.\n\n**Required scope:** `read_payments` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"order_id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand (e.g., payment_method, source). Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., amount,status,number,response_code). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"payments found","content":{"application/json":{}}}}},"post":{"summary":"Create a payment","tags":["Payments"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Creates a new payment for the order.\n\n**Required scope:** `write_payments` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"order_id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}}],"responses":{"201":{"description":"payment created","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["payment_method_id"],"properties":{"payment_method_id":{"type":"string","description":"Payment method ID"},"amount":{"type":"number"},"source_id":{"type":"string","description":"Payment source ID"}}}}}}}},"/api/v3/admin/orders/{order_id}/payments/{id}":{"get":{"summary":"Show a payment","tags":["Payments"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns details of a specific payment.\n\n**Required scope:** `read_payments` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"order_id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Payment ID","schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand (e.g., payment_method, source). Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., amount,status,number,response_code). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"payment found","content":{"application/json":{}}}}}},"/api/v3/admin/orders/{order_id}/payments/{id}/capture":{"patch":{"summary":"Capture a payment","tags":["Payments"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Captures a pending payment.\n\n**Required scope:** `write_payments` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"order_id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Payment ID","schema":{"type":"string"}}],"responses":{"200":{"description":"payment captured","content":{"application/json":{}}},"422":{"description":"capture failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/api/v3/admin/orders/{order_id}/payments/{id}/void":{"patch":{"summary":"Void a payment","tags":["Payments"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Voids a payment.\n\n**Required scope:** `write_payments` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"order_id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Payment ID","schema":{"type":"string"}}],"responses":{"200":{"description":"payment voided","content":{"application/json":{}}}}}},"/api/v3/admin/price_lists":{"get":{"summary":"List price lists","tags":["Pricing"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns the price lists configured for the current store.\n\n**Required scope:** `read_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"page","in":"query","required":false,"schema":{"type":"integer"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer"}},{"name":"q[name_cont]","in":"query","required":false,"schema":{"type":"string"}},{"name":"q[status_eq]","in":"query","required":false,"schema":{"type":"string"}},{"name":"sort","in":"query","required":false,"schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to embed. Supported: `price_rules`.","schema":{"type":"string"}}],"responses":{"200":{"description":"price lists found","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/PriceList"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"required":["data","meta"]}}}}}},"post":{"summary":"Create a price list","tags":["Pricing"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Creates a new draft price list.\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"201":{"description":"price list created (server-to-server — rules + prices, no product_ids)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PriceList"}}}},"422":{"description":"validation error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["name"],"properties":{"name":{"type":"string"},"description":{"type":"string","nullable":true},"starts_at":{"type":"string","nullable":true},"ends_at":{"type":"string","nullable":true},"match_policy":{"type":"string","enum":["all","any"]},"position":{"type":"integer"},"product_ids":{"type":"array","items":{"type":"string"},"description":"Prefixed product ids to seed the list with."},"rules":{"type":"array","description":"STI-typed price rules to attach on create. Existing rules on the same payload via PATCH reconcile by id.","items":{"type":"object","required":["type"],"properties":{"type":{"type":"string"},"preferences":{"type":"object","additionalProperties":true}}}},"prices":{"type":"array","description":"Server-to-server alternative to `product_ids`: ship the exact per-variant prices the list should contain. Each row upserts on the unique key `(variant_id, currency, price_list_id)`. Mix-and-match with `product_ids` is supported but typically unnecessary — `prices` alone tells the server which variants belong to the list and what the override amount is.","items":{"type":"object","required":["variant_id","currency"],"properties":{"variant_id":{"type":"string"},"currency":{"type":"string"},"amount":{"type":"string","nullable":true},"compare_at_amount":{"type":"string","nullable":true}}}}}}}}}}},"/api/v3/admin/price_lists/{id}":{"parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"get":{"summary":"Get a price list","tags":["Pricing"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"**Required scope:** `read_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"schema":{"type":"string"}}],"responses":{"200":{"description":"price list found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PriceList"}}}},"404":{"description":"price list not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}},"patch":{"summary":"Update a price list","tags":["Pricing"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Updates a price list. The optional `rules:` array reconciles nested\nSTI-typed price rules in a single round-trip — existing rules update\nby `id`, new rules build, missing rules destroy. Mirrors the\npromotion editor's \"save the whole thing on Save\" pattern.\n\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"price list updated with nested rules","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PriceList"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string"},"description":{"type":"string","nullable":true},"starts_at":{"type":"string","nullable":true},"ends_at":{"type":"string","nullable":true},"match_policy":{"type":"string","enum":["all","any"]},"position":{"type":"integer"},"product_ids":{"type":"array","items":{"type":"string"},"description":"Prefixed product ids — reconciles list membership (adds + removes)."},"rules":{"type":"array","items":{"type":"object","required":["type"],"properties":{"id":{"type":"string","nullable":true},"type":{"type":"string"},"preferences":{"type":"object","additionalProperties":true}}}},"prices":{"type":"array","description":"Individual price overrides (the spreadsheet payload). Each row updates by `id` if shipped, otherwise upserts on the unique key `(variant_id, currency, price_list_id)`.","items":{"type":"object","oneOf":[{"required":["id"]},{"required":["variant_id","currency"]}],"properties":{"id":{"type":"string"},"variant_id":{"type":"string"},"currency":{"type":"string"},"amount":{"type":"string","nullable":true},"compare_at_amount":{"type":"string","nullable":true}}}}}}}}}},"delete":{"summary":"Delete a price list","tags":["Pricing"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Soft-deletes the price list. Associated prices are removed asynchronously.\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"204":{"description":"price list deleted"}}}},"/api/v3/admin/price_lists/{id}/activate":{"parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"patch":{"summary":"Activate a price list","tags":["Pricing"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Transitions a draft / inactive list to `active`. If `starts_at` is\nin the future the list is marked `scheduled` instead, matching the\nlegacy admin behaviour.\n\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"price list activated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PriceList"}}}}}}},"/api/v3/admin/price_lists/{id}/deactivate":{"parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"patch":{"summary":"Deactivate a price list","tags":["Pricing"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"price list deactivated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PriceList"}}}}}}},"/api/v3/admin/prices":{"get":{"summary":"List prices","tags":["Pricing"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Generic prices endpoint covering both base prices and price-list\noverrides. Filter with Ransack: `q[price_list_id_eq]=…`,\n`q[currency_eq]=USD`, `q[price_list_id_null]=true` (base prices only).\n\nThe admin spreadsheet uses this with server-side pagination so it\nscales past the metadata-PATCH path on `/price_lists/:id`.\n\n\n**Required scope:** `read_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"page","in":"query","required":false,"schema":{"type":"integer"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer"}},{"name":"q[price_list_id_eq]","in":"query","required":false,"schema":{"type":"string"}},{"name":"q[price_list_id_null]","in":"query","required":false,"schema":{"type":"boolean"}},{"name":"q[currency_eq]","in":"query","required":false,"schema":{"type":"string"}},{"name":"q[variant_id_eq]","in":"query","required":false,"schema":{"type":"string"}},{"name":"sort","in":"query","required":false,"description":"Comma-separated sort keys. Supports e.g. `variant_product_name,variant_id`.","schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to embed. Supported: `variant`.","schema":{"type":"string"}}],"responses":{"200":{"description":"prices found","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Price"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"required":["data","meta"]}}}}}},"post":{"summary":"Create a price","tags":["Pricing"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Creates a single price. Omit `price_list_id` to create a base price.\nFor more than a handful of rows, prefer `POST /admin/prices/bulk_upsert`.\n\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"201":{"description":"price created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Price"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["variant_id","currency"],"properties":{"variant_id":{"type":"string"},"currency":{"type":"string"},"amount":{"type":"string","nullable":true},"compare_at_amount":{"type":"string","nullable":true},"price_list_id":{"type":"string","nullable":true}}}}}}}},"/api/v3/admin/prices/{id}":{"parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"get":{"summary":"Get a price","tags":["Pricing"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"**Required scope:** `read_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"price found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Price"}}}},"404":{"description":"price not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}},"patch":{"summary":"Update a price","tags":["Pricing"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"price updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Price"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"amount":{"type":"string","nullable":true},"compare_at_amount":{"type":"string","nullable":true}}}}}}},"delete":{"summary":"Delete a price","tags":["Pricing"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Soft-deletes the price (acts_as_paranoid).\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"204":{"description":"price deleted"}}}},"/api/v3/admin/prices/bulk_upsert":{"post":{"summary":"Bulk-upsert prices","tags":["Pricing"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Upserts a batch of prices in a single SQL round trip.\n\nEach row either:\n* targets an existing price by `id`, OR\n* matches on the unique key `(variant_id, currency, price_list_id)` —\n updating the existing row if one exists, creating one otherwise.\n\nModel callbacks (e.g. PriceHistory) are bypassed; this is a\nbulk-write fast path for the admin spreadsheet. The response\ncarries `price_count` — the number of rows touched.\n\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"prices upserted","content":{"application/json":{"schema":{"type":"object","properties":{"price_count":{"type":"integer"}}}}}},"422":{"description":"missing prices key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["prices"],"properties":{"prices":{"type":"array","items":{"type":"object","required":["variant_id","currency"],"properties":{"id":{"type":"string","nullable":true},"variant_id":{"type":"string"},"currency":{"type":"string"},"price_list_id":{"type":"string","nullable":true},"amount":{"type":"string","nullable":true},"compare_at_amount":{"type":"string","nullable":true}}}}}}}}}}},"/api/v3/admin/prices/bulk_destroy":{"delete":{"summary":"Bulk-delete prices","tags":["Pricing"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Soft-deletes each price in `ids`. Returns the count actually destroyed.\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"prices deleted","content":{"application/json":{"schema":{"type":"object","properties":{"price_count":{"type":"integer"}}}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["ids"],"properties":{"ids":{"type":"array","items":{"type":"string"}}}}}}}}},"/api/v3/admin/products/{product_id}/custom_fields":{"get":{"summary":"List product custom fields","tags":["Products"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns the product's custom field values.\n\n**Required scope:** `read_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"product_id","in":"path","required":true,"schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand (e.g., custom_field_definition). Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., key,value,namespace). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"custom fields found","content":{"application/json":{}}}}},"post":{"summary":"Create a product custom field","tags":["Products"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Sets a custom field value on the product. Requires an existing CustomFieldDefinition; pass its prefixed `cfdef_…` id.\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"product_id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"201":{"description":"custom field created","content":{"application/json":{}}},"422":{"description":"duplicate definition for the same product","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["custom_field_definition_id","value"],"properties":{"custom_field_definition_id":{"type":"string","description":"Prefixed `cfdef_…` id"},"value":{"description":"Value matching the definition's `field_type`"}}}}}}}},"/api/v3/admin/products/{product_id}/custom_fields/{id}":{"get":{"summary":"Show a product custom field","tags":["Products"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"**Required scope:** `read_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"product_id","in":"path","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand (e.g., custom_field_definition). Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., key,value,namespace). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"custom field found","content":{"application/json":{}}}}},"patch":{"summary":"Update a product custom field","tags":["Products"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Updates the custom field's `value`. The linked definition cannot be changed — delete and recreate to switch.\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"product_id","in":"path","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"custom field updated","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["value"],"properties":{"value":{"description":"New value"}}}}}}},"delete":{"summary":"Delete a product custom field","tags":["Products"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"product_id","in":"path","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"204":{"description":"custom field deleted"}}}},"/api/v3/admin/products":{"get":{"summary":"List products","tags":["Products"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns a paginated list of products for the current store.\n\n**Required scope:** `read_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"page","in":"query","required":false,"description":"Page number","schema":{"type":"integer"}},{"name":"limit","in":"query","required":false,"description":"Number of records per page","schema":{"type":"integer"}},{"name":"sort","in":"query","required":false,"description":"Sort field (e.g., name, -name, price, -price, best_selling)","schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand (e.g., variants, media, option_types, categories). Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., name,slug,price,status). id is always included.","schema":{"type":"string"}},{"name":"q[name_cont]","in":"query","required":false,"description":"Filter by name (contains)","schema":{"type":"string"}},{"name":"q[status_eq]","in":"query","required":false,"description":"Filter by status","schema":{"type":"string"}}],"responses":{"200":{"description":"products found","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Product"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"required":["data","meta"]}}}},"401":{"description":"unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}},"post":{"summary":"Create a product","tags":["Products"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Creates a new product. Supports nested variants with prices and option types.\n\nOption types and values are auto-created if they don't exist.\nPrices are upserted by currency. Stock items are upserted by stock location.\n\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}}],"responses":{"201":{"description":"product created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Product"}}}},"422":{"description":"validation error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string"},"description":{"type":"string"},"slug":{"type":"string"},"status":{"type":"string","enum":["draft","active","archived"]},"tax_category_id":{"type":"string","description":"Tax category ID"},"category_ids":{"type":"array","items":{"type":"string"},"description":"Array of category IDs"},"tags":{"type":"array","items":{"type":"string"}},"variants":{"type":"array","description":"Array of variant payloads. Variants can declare multiple option pairs via `options:` and per-currency prices via `prices:`. Stock counts go in `stock_items:` (per stock location).","items":{"type":"object","properties":{"sku":{"type":"string"},"options":{"type":"array","description":"One pair per option type the variant participates in (e.g. size + color). Option types and values are auto-created if missing.","items":{"type":"object","required":["name","value"],"properties":{"name":{"type":"string"},"value":{"type":"string"}}}},"prices":{"type":"array","description":"Per-currency prices. Upserted by currency.","items":{"type":"object","required":["currency","amount"],"properties":{"currency":{"type":"string"},"amount":{"type":"number"},"compare_at_amount":{"type":"number"}}}},"stock_items":{"type":"array","description":"Per-stock-location inventory. Upserted by stock_location_id.","items":{"type":"object","required":["stock_location_id","count_on_hand"],"properties":{"stock_location_id":{"type":"string","description":"Stock location ID (e.g. sloc_xxx)"},"count_on_hand":{"type":"integer"},"backorderable":{"type":"boolean"}}}}}}}},"required":["name"]}}}}}},"/api/v3/admin/products/{id}":{"get":{"summary":"Get a product","tags":["Products"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns a single product by ID.\n\n**Required scope:** `read_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Product ID (e.g., prod_xxx)","schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand (e.g., variants, media, option_types, categories). Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., name,slug,price,status). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"product found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Product"}}}},"404":{"description":"product not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}},"patch":{"summary":"Update a product","tags":["Products"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Updates a product. Only provided fields are updated.\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Product ID","schema":{"type":"string"}}],"responses":{"200":{"description":"product updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Product"}}}},"422":{"description":"validation error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string"},"description":{"type":"string"},"slug":{"type":"string"},"status":{"type":"string","enum":["draft","active","archived"]},"tax_category_id":{"type":"string","description":"Tax category ID"},"category_ids":{"type":"array","items":{"type":"string"},"description":"Array of category IDs"},"tags":{"type":"array","items":{"type":"string"}},"variants":{"type":"array","description":"Array of variant payloads. Variants can declare multiple option pairs via `options:` and per-currency prices via `prices:`. Stock counts go in `stock_items:` (per stock location).","items":{"type":"object","properties":{"sku":{"type":"string"},"options":{"type":"array","description":"One pair per option type the variant participates in (e.g. size + color). Option types and values are auto-created if missing.","items":{"type":"object","required":["name","value"],"properties":{"name":{"type":"string"},"value":{"type":"string"}}}},"prices":{"type":"array","description":"Per-currency prices. Upserted by currency.","items":{"type":"object","required":["currency","amount"],"properties":{"currency":{"type":"string"},"amount":{"type":"number"},"compare_at_amount":{"type":"number"}}}},"stock_items":{"type":"array","description":"Per-stock-location inventory. Upserted by stock_location_id.","items":{"type":"object","required":["stock_location_id","count_on_hand"],"properties":{"stock_location_id":{"type":"string","description":"Stock location ID (e.g. sloc_xxx)"},"count_on_hand":{"type":"integer"},"backorderable":{"type":"boolean"}}}}}}}}}}}}},"delete":{"summary":"Delete a product","tags":["Products"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Soft-deletes a product.\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Product ID","schema":{"type":"string"}}],"responses":{"204":{"description":"product deleted"}}}},"/api/v3/admin/products/bulk_status_update":{"post":{"summary":"Bulk-update product status","tags":["Products"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Sets `status` on each product in `ids`. Reindexes the affected products\nfor search. Cross-store IDs are silently dropped. Returns counts.\n\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"cross-store products silently dropped","content":{"application/json":{"schema":{"type":"object","properties":{"product_count":{"type":"integer"},"status":{"type":"string"}}}}}},"422":{"description":"invalid status","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["ids","status"],"properties":{"ids":{"type":"array","items":{"type":"string"}},"status":{"type":"string","enum":["draft","active","archived"]}}}}}}}},"/api/v3/admin/products/bulk_add_to_categories":{"post":{"summary":"Bulk-add products to categories","tags":["Products"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Attaches each product in `ids` to every category (taxon) in `category_ids`.\nCategories from sibling stores are silently ignored.\n\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"products added to categories","content":{"application/json":{"schema":{"type":"object","properties":{"product_count":{"type":"integer"},"category_count":{"type":"integer"}}}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["ids","category_ids"],"properties":{"ids":{"type":"array","items":{"type":"string"}},"category_ids":{"type":"array","items":{"type":"string"}}}}}}}}},"/api/v3/admin/products/bulk_remove_from_categories":{"post":{"summary":"Bulk-remove products from categories","tags":["Products"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Detaches each product in `ids` from every category in `category_ids`.\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"products removed from categories","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["ids","category_ids"],"properties":{"ids":{"type":"array","items":{"type":"string"}},"category_ids":{"type":"array","items":{"type":"string"}}}}}}}}},"/api/v3/admin/products/bulk_add_to_channels":{"post":{"summary":"Bulk-add products to channels","tags":["Products"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Publishes each product in `ids` on every channel in `channel_ids`. Idempotent —\nre-publishing on an existing channel is a no-op. Channels from sibling stores\nare silently ignored.\n\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"products published on channels","content":{"application/json":{"schema":{"type":"object","properties":{"product_count":{"type":"integer"},"channel_count":{"type":"integer"}}}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["ids","channel_ids"],"properties":{"ids":{"type":"array","items":{"type":"string"}},"channel_ids":{"type":"array","items":{"type":"string"}}}}}}}}},"/api/v3/admin/products/bulk_remove_from_channels":{"post":{"summary":"Bulk-remove products from channels","tags":["Products"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Unpublishes each product in `ids` from every channel in `channel_ids`.\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"products unpublished from channels","content":{"application/json":{"schema":{"type":"object","properties":{"product_count":{"type":"integer"},"channel_count":{"type":"integer"},"removed":{"type":"integer"}}}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["ids","channel_ids"],"properties":{"ids":{"type":"array","items":{"type":"string"}},"channel_ids":{"type":"array","items":{"type":"string"}}}}}}}}},"/api/v3/admin/products/bulk_add_tags":{"post":{"summary":"Bulk-add tags to products","tags":["Products"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Adds each tag name in `tags` to every product in `ids`. Tags are upserted by name.\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"tags added","content":{"application/json":{"schema":{"type":"object","properties":{"product_count":{"type":"integer"},"tag_count":{"type":"integer"}}}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["ids","tags"],"properties":{"ids":{"type":"array","items":{"type":"string"}},"tags":{"type":"array","items":{"type":"string"}}}}}}}}},"/api/v3/admin/products/bulk_remove_tags":{"post":{"summary":"Bulk-remove tags from products","tags":["Products"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Removes each tag in `tags` from every product in `ids`.\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"tags removed","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["ids","tags"],"properties":{"ids":{"type":"array","items":{"type":"string"}},"tags":{"type":"array","items":{"type":"string"}}}}}}}}},"/api/v3/admin/products/bulk_destroy":{"delete":{"summary":"Bulk-delete products","tags":["Products"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Soft-deletes each product in `ids`. Returns the count actually destroyed.\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"products deleted","content":{"application/json":{"schema":{"type":"object","properties":{"product_count":{"type":"integer"}}}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["ids"],"properties":{"ids":{"type":"array","items":{"type":"string"}}}}}}}}},"/api/v3/admin/promotions/{promotion_id}/coupon_codes":{"parameters":[{"name":"promotion_id","in":"path","required":true,"schema":{"type":"string"}}],"get":{"summary":"List coupon codes for a promotion","tags":["Promotions"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns the auto-generated coupon codes for a multi-code promotion. Single-code promotions store the code on the promotion itself; this endpoint returns an empty list for them.\n\n**Required scope:** `read_promotions` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"coupon codes found","content":{"application/json":{}}}}}},"/api/v3/admin/promotions/{promotion_id}/promotion_actions":{"parameters":[{"name":"promotion_id","in":"path","required":true,"schema":{"type":"string"}}],"get":{"summary":"List actions for a promotion","tags":["Promotions"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"**Required scope:** `read_promotions` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"actions found","content":{"application/json":{}}}}},"post":{"summary":"Create an action on a promotion","tags":["Promotions"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Adds a new action to a promotion. The `type` is the wire shorthand from `GET /promotion_actions/types` (e.g. `free_shipping`, `create_item_adjustments`). Fully-qualified Ruby class names are also accepted for backward compatibility.\n\n**Required scope:** `write_promotions` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"201":{"description":"action created","content":{"application/json":{}}},"422":{"description":"unknown action type","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"type":{"type":"string"},"preferences":{"type":"object","additionalProperties":true}},"required":["type"]}}}}}},"/api/v3/admin/promotions/{promotion_id}/promotion_actions/{id}":{"parameters":[{"name":"promotion_id","in":"path","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"delete":{"summary":"Delete an action from a promotion","tags":["Promotions"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"**Required scope:** `write_promotions` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"204":{"description":"action deleted"}}}},"/api/v3/admin/promotions/{promotion_id}/promotion_rules":{"parameters":[{"name":"promotion_id","in":"path","required":true,"schema":{"type":"string"}}],"get":{"summary":"List rules for a promotion","tags":["Promotions"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"**Required scope:** `read_promotions` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"rules found","content":{"application/json":{}}}}},"post":{"summary":"Create a rule on a promotion","tags":["Promotions"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Adds a new rule to a promotion. The `type` is the wire shorthand from `GET /promotion_rules/types` (e.g. `currency`, `item_total`, `product`). Fully-qualified Ruby class names are also accepted for backward compatibility.\n\n**Required scope:** `write_promotions` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"201":{"description":"rule created with preferences","content":{"application/json":{}}},"422":{"description":"unknown rule type","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"type":{"type":"string"},"preferences":{"type":"object","additionalProperties":true}},"required":["type"]}}}}}},"/api/v3/admin/promotions/{promotion_id}/promotion_rules/{id}":{"parameters":[{"name":"promotion_id","in":"path","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"patch":{"summary":"Update a rule's preferences","tags":["Promotions"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"**Required scope:** `write_promotions` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"rule updated","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"preferences":{"type":"object","additionalProperties":true}}}}}}},"delete":{"summary":"Delete a rule from a promotion","tags":["Promotions"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"**Required scope:** `write_promotions` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"204":{"description":"rule deleted"}}}},"/api/v3/admin/promotions":{"get":{"summary":"List promotions","tags":["Promotions"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns the store's promotions, including manual coupon and automatic promotions.\n\n**Required scope:** `read_promotions` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"promotions found","content":{"application/json":{}}}}},"post":{"summary":"Create a promotion","tags":["Promotions"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Creates a new promotion. `code` is required for single-code coupon promotions;\npass `multi_codes: true` with `number_of_codes` to auto-generate a batch.\n\nRules and actions can be created in the same request by passing arrays of\n`{ type, preferences, ... }` rows. The server reconciles to the desired set:\nnew rows are built, existing rows (by `id`) are updated, omitted rows are removed.\n\n\n**Required scope:** `write_promotions` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"201":{"description":"promotion created with rules and actions","content":{"application/json":{}}},"422":{"description":"invalid params","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string"},"code":{"type":"string","nullable":true},"description":{"type":"string","nullable":true},"starts_at":{"type":"string","format":"date-time","nullable":true},"expires_at":{"type":"string","format":"date-time","nullable":true},"usage_limit":{"type":"integer","nullable":true},"match_policy":{"type":"string","enum":["all","any"]},"kind":{"type":"string","enum":["coupon_code","automatic"]},"multi_codes":{"type":"boolean"},"number_of_codes":{"type":"integer","nullable":true},"code_prefix":{"type":"string","nullable":true},"promotion_category_id":{"type":"string","nullable":true},"rules":{"type":"array","items":{"type":"object","properties":{"type":{"type":"string"},"preferences":{"type":"object","additionalProperties":true},"product_ids":{"type":"array","items":{"type":"string"}},"category_ids":{"type":"array","items":{"type":"string"}},"customer_ids":{"type":"array","items":{"type":"string"}}},"required":["type"]}},"actions":{"type":"array","items":{"type":"object","properties":{"type":{"type":"string"},"preferences":{"type":"object","additionalProperties":true},"calculator":{"type":"object","properties":{"type":{"type":"string"},"preferences":{"type":"object","additionalProperties":true}}}},"required":["type"]}}},"required":["name"]}}}}}},"/api/v3/admin/promotions/{id}":{"get":{"summary":"Show a promotion","tags":["Promotions"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"**Required scope:** `read_promotions` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"promotion found","content":{"application/json":{}}}}},"patch":{"summary":"Update a promotion","tags":["Promotions"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Updates a promotion. The `rules` and `actions` arrays are treated as\na *desired set* — rows with `id` update in place, rows without `id` are\nbuilt fresh, and any existing row not present in the array is destroyed.\nPass `rules: []` or `actions: []` to clear them.\n\n\n**Required scope:** `write_promotions` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"rules and actions cleared with empty arrays","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string"},"description":{"type":"string","nullable":true},"code":{"type":"string","nullable":true},"starts_at":{"type":"string","format":"date-time","nullable":true},"expires_at":{"type":"string","format":"date-time","nullable":true},"usage_limit":{"type":"integer","nullable":true},"match_policy":{"type":"string","enum":["all","any"]},"kind":{"type":"string","enum":["coupon_code","automatic"]},"promotion_category_id":{"type":"string","nullable":true},"rules":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","nullable":true,"description":"Pass to update an existing rule; omit to build a new one"},"type":{"type":"string"},"preferences":{"type":"object","additionalProperties":true},"product_ids":{"type":"array","items":{"type":"string"}},"category_ids":{"type":"array","items":{"type":"string"}},"customer_ids":{"type":"array","items":{"type":"string"}}},"required":["type"]}},"actions":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","nullable":true},"type":{"type":"string"},"preferences":{"type":"object","additionalProperties":true},"calculator":{"type":"object","properties":{"type":{"type":"string"},"preferences":{"type":"object","additionalProperties":true}}}},"required":["type"]}}}}}}}},"delete":{"summary":"Delete a promotion","tags":["Promotions"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"**Required scope:** `write_promotions` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"204":{"description":"promotion deleted"}}}},"/api/v3/admin/promotion_actions/types":{"get":{"summary":"List available promotion action types","tags":["Promotions"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns the registered Spree::PromotionAction subclasses with their preference schemas. Used by admin UIs to populate the \"Add action\" picker and render generic preference forms.\n\n**Required scope:** `read_promotions` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"action types found","content":{"application/json":{}}}}}},"/api/v3/admin/promotion_rules/types":{"get":{"summary":"List available promotion rule types","tags":["Promotions"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns the registered Spree::PromotionRule subclasses with their preference schemas.\n\n**Required scope:** `read_promotions` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"rule types found","content":{"application/json":{}}}}}},"/api/v3/admin/orders/{order_id}/refunds":{"get":{"summary":"List refunds","tags":["Refunds"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns all refunds for an order.\n\n**Required scope:** `read_refunds` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"order_id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand (e.g., payment, refund_reason). Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., amount,reason,transaction_id). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"refunds found","content":{"application/json":{}}}}},"post":{"summary":"Create a refund","tags":["Refunds"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Creates a refund for a payment on the order. The refund is automatically processed via the payment gateway.\n\n**Required scope:** `write_refunds` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"order_id","in":"path","required":true,"description":"Order ID","schema":{"type":"string"}}],"responses":{"201":{"description":"refund created","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["payment_id","amount"],"properties":{"payment_id":{"type":"string","description":"Payment ID"},"amount":{"type":"number"},"refund_reason_id":{"type":"string","description":"Refund reason ID"}}}}}}}},"/api/v3/admin/store_credit_categories":{"get":{"summary":"List store credit categories","tags":["Settings"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns the configured store credit categories. Categories classify\nstore credits (e.g., \"Goodwill\", \"Gift Card\", \"Refund\") and surface\nin the admin UI as a dropdown when issuing or editing a store\ncredit. Category names matching `Spree::Config[:non_expiring_credit_types]`\nare flagged via `non_expiring: true`.\n\n\n**Required scope:** `read_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"page","in":"query","required":false,"description":"Page number","schema":{"type":"integer"}},{"name":"limit","in":"query","required":false,"description":"Number of records per page","schema":{"type":"integer"}},{"name":"q[name_cont]","in":"query","required":false,"description":"Filter by name (contains)","schema":{"type":"string"}},{"name":"sort","in":"query","required":false,"description":"Sort by field. Prefix with `-` for descending (e.g., `-created_at`).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include. id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"store credit categories found","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/StoreCreditCategory"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"required":["data","meta"]}}}},"401":{"description":"unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/api/v3/admin/store_credit_categories/{id}":{"parameters":[{"name":"id","in":"path","required":true,"description":"Store credit category ID","schema":{"type":"string"}}],"get":{"summary":"Get a store credit category","tags":["Settings"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns a single store credit category by prefixed ID.\n\n**Required scope:** `read_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include. id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"store credit category found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StoreCreditCategory"}}}},"404":{"description":"store credit category not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/api/v3/admin/store":{"get":{"summary":"Get the current store","tags":["Settings"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns the current store configuration. The store is resolved from the request context (host or admin selection); there is no `id` parameter.\n\n**Required scope:** `read_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}}],"responses":{"200":{"description":"current store","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Store"}}}},"401":{"description":"unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}},"patch":{"summary":"Update the current store","tags":["Settings"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Updates the current store configuration.\n\n**Required scope:** `write_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}}],"responses":{"200":{"description":"store updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Store"}}}},"422":{"description":"validation error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string"},"preferred_admin_locale":{"type":"string"},"preferred_timezone":{"type":"string"},"preferred_weight_unit":{"type":"string"},"preferred_unit_system":{"type":"string"}}}}}}}},"/api/v3/admin/tags":{"get":{"summary":"List tags","tags":["Settings"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns tag names for a given taggable type. Used for autocomplete in tag inputs on products, orders, and customers.","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"taggable_type","in":"query","required":true,"description":"Taggable type (`Spree::Product`, `Spree::Order`, or `Spree::User`)","schema":{"type":"string"}},{"name":"q","in":"query","required":false,"description":"Optional case-insensitive substring filter","schema":{"type":"string"}}],"responses":{"200":{"description":"tags found","content":{"application/json":{}}},"422":{"description":"invalid taggable type","content":{"application/json":{}}}}}},"/api/v3/admin/admin_users":{"get":{"summary":"List staff","tags":["Staff"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns admin users with at least one role assignment on the current store.\n\n**Required scope:** `read_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"staff found","content":{"application/json":{}}}}}},"/api/v3/admin/admin_users/{id}":{"get":{"summary":"Show a staff member","tags":["Staff"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"**Required scope:** `read_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"staff member found","content":{"application/json":{}}}}},"patch":{"summary":"Update a staff member","tags":["Staff"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Updates name fields and reassigns roles for the current store. `role_ids` is a complete replacement — roles not in the array are removed for this store.\n\n**Required scope:** `write_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"staff member updated","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"first_name":{"type":"string"},"last_name":{"type":"string"},"role_ids":{"type":"array","items":{"type":"string"}}}}}}}},"delete":{"summary":"Remove a staff member from this store","tags":["Staff"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Removes the user's role assignments on the current store. The account is preserved — the user keeps access to any other stores.\n\n**Required scope:** `write_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"204":{"description":"staff removed from store"}}}},"/api/v3/admin/invitations":{"get":{"summary":"List invitations","tags":["Staff"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns invitations for the current store, including pending and accepted.\n\n**Required scope:** `read_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"invitations found","content":{"application/json":{}}}}},"post":{"summary":"Create an invitation","tags":["Staff"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Invites a teammate by email. The invitation is scoped to the current store and carries the chosen role; on accept, a `RoleUser` is created via the invitation's `after_accept` callback.\n\n**Required scope:** `write_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"201":{"description":"invitation created","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["email","role_id"],"properties":{"email":{"type":"string"},"role_id":{"type":"string"}}}}}}}},"/api/v3/admin/invitations/{id}":{"delete":{"summary":"Revoke an invitation","tags":["Staff"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"**Required scope:** `write_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"204":{"description":"invitation revoked"}}}},"/api/v3/admin/invitations/{id}/resend":{"patch":{"summary":"Resend an invitation","tags":["Staff"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Issues a fresh token and dispatches the invitation email again.\n\n**Required scope:** `write_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"invitation resent","content":{"application/json":{}}}}}},"/api/v3/admin/roles":{"get":{"summary":"List roles","tags":["Staff"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns the roles available for staff role pickers. Roles are global, not per-store.\n\n**Required scope:** `read_settings` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"roles found","content":{"application/json":{}}}}}},"/api/v3/admin/stock_locations":{"get":{"summary":"List stock locations","tags":["Stock Locations"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns the configured stock locations. Stock locations are global\n(shared across stores). Filter with Ransack predicates such as\n`q[active_eq]`, `q[kind_eq]`, `q[pickup_enabled_eq]`, or\n`q[name_cont]`.\n\nPickup-related attributes (`kind`, `pickup_enabled`,\n`pickup_stock_policy`, `pickup_ready_in_minutes`,\n`pickup_instructions`) drive merchant pickup support at checkout —\ncustomers can collect orders from any active location with\n`pickup_enabled: true`.\n\n\n**Required scope:** `read_stock` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"page","in":"query","required":false,"description":"Page number","schema":{"type":"integer"}},{"name":"limit","in":"query","required":false,"description":"Number of records per page","schema":{"type":"integer"}},{"name":"q[name_cont]","in":"query","required":false,"description":"Filter by name (contains)","schema":{"type":"string"}},{"name":"q[active_eq]","in":"query","required":false,"description":"Filter by active status","schema":{"type":"boolean"}},{"name":"q[kind_eq]","in":"query","required":false,"description":"Filter by kind (built-in: 'warehouse', 'store', 'fulfillment_center')","schema":{"type":"string"}},{"name":"q[pickup_enabled_eq]","in":"query","required":false,"description":"Filter by pickup-enabled flag","schema":{"type":"boolean"}},{"name":"sort","in":"query","required":false,"description":"Sort by field. Prefix with `-` for descending (e.g., `-created_at`).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include. id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"stock locations found","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/StockLocation"}},"meta":{"$ref":"#/components/schemas/PaginationMeta"}},"required":["data","meta"]}}}},"401":{"description":"unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}},"post":{"summary":"Create a stock location","tags":["Stock Locations"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Creates a new stock location.\n\nSetting `default: true` automatically demotes the previous default\nlocation.\n\n\n**Required scope:** `write_stock` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}}],"responses":{"201":{"description":"stock location created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StockLocation"}}}},"422":{"description":"validation error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string"},"admin_name":{"type":"string","nullable":true,"description":"Internal name shown only in the admin"},"active":{"type":"boolean"},"default":{"type":"boolean","description":"Setting to true demotes the previous default."},"kind":{"type":"string","enum":["warehouse","store","fulfillment_center"],"description":"Categorizes the location."},"propagate_all_variants":{"type":"boolean"},"backorderable_default":{"type":"boolean"},"address1":{"type":"string","nullable":true},"address2":{"type":"string","nullable":true},"city":{"type":"string","nullable":true},"zipcode":{"type":"string","nullable":true},"phone":{"type":"string","nullable":true},"company":{"type":"string","nullable":true},"country_iso":{"type":"string","nullable":true,"description":"ISO-3166 alpha-2 country code (e.g. \"US\")."},"state_abbr":{"type":"string","nullable":true,"description":"State / province abbreviation (e.g. \"NY\"). Resolved against the selected country."},"state_name":{"type":"string","nullable":true,"description":"Free-text state for countries without a states list."},"pickup_enabled":{"type":"boolean"},"pickup_stock_policy":{"type":"string","enum":["local","any"],"description":"'local' = items at this location only; 'any' = transfer-eligible (ship-to-store)."},"pickup_ready_in_minutes":{"type":"number","nullable":true,"minimum":0},"pickup_instructions":{"type":"string","nullable":true}},"required":["name"]}}}}}},"/api/v3/admin/stock_locations/{id}":{"parameters":[{"name":"id","in":"path","required":true,"description":"Stock location ID","schema":{"type":"string"}}],"get":{"summary":"Get a stock location","tags":["Stock Locations"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns a single stock location by prefixed ID.\n\n**Required scope:** `read_stock` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include. id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"stock location found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StockLocation"}}}},"404":{"description":"stock location not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}},"patch":{"summary":"Update a stock location","tags":["Stock Locations"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Updates an existing stock location. Same address-field conventions as\nthe create endpoint.\n\nSetting `default: true` automatically demotes the previous default.\n\n\n**Required scope:** `write_stock` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}}],"responses":{"200":{"description":"stock location updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StockLocation"}}}},"422":{"description":"validation error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string"},"admin_name":{"type":"string","nullable":true},"active":{"type":"boolean"},"default":{"type":"boolean"},"kind":{"type":"string","enum":["warehouse","store","fulfillment_center"]},"propagate_all_variants":{"type":"boolean"},"backorderable_default":{"type":"boolean"},"address1":{"type":"string","nullable":true},"address2":{"type":"string","nullable":true},"city":{"type":"string","nullable":true},"zipcode":{"type":"string","nullable":true},"phone":{"type":"string","nullable":true},"company":{"type":"string","nullable":true},"country_iso":{"type":"string","nullable":true},"state_abbr":{"type":"string","nullable":true},"state_name":{"type":"string","nullable":true},"pickup_enabled":{"type":"boolean"},"pickup_stock_policy":{"type":"string","enum":["local","any"]},"pickup_ready_in_minutes":{"type":"number","nullable":true,"minimum":0},"pickup_instructions":{"type":"string","nullable":true}}}}}}},"delete":{"summary":"Delete a stock location","tags":["Stock Locations"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Soft-deletes the stock location (sets `deleted_at`). Existing\nfulfillments that referenced it keep the historical record via\n`Spree::StockLocation.with_deleted`.\n\n\n**Required scope:** `write_stock` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}}],"responses":{"204":{"description":"stock location deleted"}}}},"/api/v3/admin/products/{product_id}/variants":{"get":{"summary":"List product variants","tags":["Variants"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns a paginated list of variants for a product, including the master variant.\n\n**Required scope:** `read_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"product_id","in":"path","required":true,"description":"Product ID","schema":{"type":"string"}},{"name":"page","in":"query","required":false,"description":"Page number","schema":{"type":"integer"}},{"name":"limit","in":"query","required":false,"description":"Number of records per page","schema":{"type":"integer"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand (e.g., images, prices, stock_items, option_values). Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., sku,price,stock). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"variants found","content":{"application/json":{}}}}},"post":{"summary":"Create a variant","tags":["Variants"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Creates a new variant for a product. Supports nested prices and stock items.\n\nOption types and values are auto-created if they don't exist.\nPrices are upserted by currency. Stock items are upserted by stock location.\n\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"product_id","in":"path","required":true,"description":"Product ID","schema":{"type":"string"}}],"responses":{"201":{"description":"variant created","content":{"application/json":{}}},"422":{"description":"validation error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"sku":{"type":"string"},"price":{"type":"number"},"compare_at_price":{"type":"number"},"cost_price":{"type":"number"},"cost_currency":{"type":"string"},"weight":{"type":"number"},"height":{"type":"number"},"width":{"type":"number"},"depth":{"type":"number"},"weight_unit":{"type":"string"},"dimensions_unit":{"type":"string"},"track_inventory":{"type":"boolean"},"tax_category_id":{"type":"string"},"options":{"type":"array","description":"One pair per option type the variant participates in (e.g. size + color). Option types and values are auto-created if missing.","items":{"type":"object","required":["name","value"],"properties":{"name":{"type":"string"},"value":{"type":"string"}}}},"position":{"type":"integer"},"barcode":{"type":"string"},"prices":{"type":"array","description":"Per-currency prices. Upserted by currency.","items":{"type":"object","required":["currency","amount"],"properties":{"currency":{"type":"string"},"amount":{"type":"number"},"compare_at_amount":{"type":"number"}}}},"stock_items":{"type":"array","description":"Per-stock-location inventory. Upserted by stock_location_id.","items":{"type":"object","required":["stock_location_id","count_on_hand"],"properties":{"stock_location_id":{"type":"string","description":"Stock location ID (e.g. sloc_xxx)"},"count_on_hand":{"type":"integer"},"backorderable":{"type":"boolean"}}}}}}}}}}},"/api/v3/admin/products/{product_id}/variants/{id}":{"get":{"summary":"Get a variant","tags":["Variants"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns a single variant by ID.\n\n**Required scope:** `read_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"product_id","in":"path","required":true,"description":"Product ID","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Variant ID","schema":{"type":"string"}},{"name":"expand","in":"query","required":false,"description":"Comma-separated associations to expand (e.g., images, prices, stock_items, option_values). Use dot notation for nested expand (max 4 levels).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include (e.g., sku,price,stock). id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"variant found","content":{"application/json":{}}},"404":{"description":"variant not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}},"patch":{"summary":"Update a variant","tags":["Variants"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Updates a variant. Only provided fields are updated.\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"product_id","in":"path","required":true,"description":"Product ID","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Variant ID","schema":{"type":"string"}}],"responses":{"200":{"description":"variant updated","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"sku":{"type":"string"},"price":{"type":"number"},"compare_at_price":{"type":"number"},"cost_price":{"type":"number"},"cost_currency":{"type":"string"},"weight":{"type":"number"},"height":{"type":"number"},"width":{"type":"number"},"depth":{"type":"number"},"weight_unit":{"type":"string"},"dimensions_unit":{"type":"string"},"track_inventory":{"type":"boolean"},"tax_category_id":{"type":"string"},"options":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"value":{"type":"string"}}}},"total_on_hand":{"type":"integer"},"position":{"type":"integer"},"barcode":{"type":"string"},"prices":{"type":"array","items":{"type":"object","properties":{"currency":{"type":"string"},"amount":{"type":"number"},"compare_at_amount":{"type":"number"}},"required":["currency","amount"]}},"stock_items":{"type":"array","items":{"type":"object","properties":{"stock_location_id":{"type":"string"},"count_on_hand":{"type":"integer"},"backorderable":{"type":"boolean"}}}}}}}}}},"delete":{"summary":"Delete a variant","tags":["Variants"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Soft-deletes a variant.\n\n**Required scope:** `write_products` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"product_id","in":"path","required":true,"description":"Product ID","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Variant ID","schema":{"type":"string"}}],"responses":{"204":{"description":"variant deleted"}}}},"/api/v3/admin/webhook_endpoints/{webhook_endpoint_id}/deliveries":{"parameters":[{"name":"webhook_endpoint_id","in":"path","required":true,"description":"Parent webhook endpoint ID","schema":{"type":"string"}}],"get":{"summary":"List webhook deliveries","tags":["Webhooks"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns delivery attempts for the given endpoint, most recent first.\nEach row carries the original request payload, the response code\n(when the receiver replied), the execution time, and any transport\nerror — everything needed to audit failures and decide whether to\nredeliver.\n\n\n**Required scope:** `read_webhooks` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"page","in":"query","required":false,"description":"Page number","schema":{"type":"integer"}},{"name":"limit","in":"query","required":false,"description":"Number of records per page","schema":{"type":"integer"}},{"name":"q[event_name_eq]","in":"query","required":false,"description":"Filter by event name (exact)","schema":{"type":"string"}},{"name":"q[success_eq]","in":"query","required":false,"description":"Filter by success flag","schema":{"type":"boolean"}},{"name":"sort","in":"query","required":false,"description":"Sort by field. Prefix with `-` for descending (e.g., `-delivered_at`).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include. id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"deliveries found","content":{"application/json":{}}},"404":{"description":"parent webhook endpoint not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/api/v3/admin/webhook_endpoints/{webhook_endpoint_id}/deliveries/{id}":{"parameters":[{"name":"webhook_endpoint_id","in":"path","required":true,"description":"Parent webhook endpoint ID","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Webhook delivery ID","schema":{"type":"string"}}],"get":{"summary":"Get a webhook delivery","tags":["Webhooks"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns a single delivery attempt with the full request payload and\nthe response body the receiver returned. Use this for ad-hoc debug\nof failed deliveries.\n\n\n**Required scope:** `read_webhooks` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include. id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"delivery found","content":{"application/json":{}}},"404":{"description":"delivery not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/api/v3/admin/webhook_endpoints/{webhook_endpoint_id}/deliveries/{id}/redeliver":{"parameters":[{"name":"webhook_endpoint_id","in":"path","required":true,"description":"Parent webhook endpoint ID","schema":{"type":"string"}},{"name":"id","in":"path","required":true,"description":"Webhook delivery ID to redeliver","schema":{"type":"string"}}],"post":{"summary":"Redeliver a webhook delivery","tags":["Webhooks"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Creates a new delivery row with the same payload + event_name and\nqueues it. The original row is preserved for audit history.\n\n\n**Required scope:** `write_webhooks` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}}],"responses":{"201":{"description":"redelivery queued","content":{"application/json":{}}}}}},"/api/v3/admin/webhook_endpoints":{"get":{"summary":"List webhook endpoints","tags":["Webhooks"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns outbound webhook subscriptions for the current store. Each\nendpoint receives a signed POST when any subscribed event fires.\n`secret_key` is `null` on list reads — the plaintext is delivered\nexactly once on create.\n\n\n**Required scope:** `read_webhooks` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"page","in":"query","required":false,"description":"Page number","schema":{"type":"integer"}},{"name":"limit","in":"query","required":false,"description":"Number of records per page","schema":{"type":"integer"}},{"name":"q[name_cont]","in":"query","required":false,"description":"Filter by name (contains)","schema":{"type":"string"}},{"name":"q[url_cont]","in":"query","required":false,"description":"Filter by URL (contains)","schema":{"type":"string"}},{"name":"sort","in":"query","required":false,"description":"Sort by field. Prefix with `-` for descending (e.g., `-created_at`).","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include. id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"webhook endpoints found","content":{"application/json":{}}},"401":{"description":"unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}},"post":{"summary":"Create a webhook endpoint","tags":["Webhooks"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Creates a new outbound webhook subscription. The plaintext\n`secret_key` is returned **once** in this response — persist it\nimmediately to verify incoming webhook signatures. Subsequent reads\nreturn `null` for the secret. Pass an empty `subscriptions` array or\nomit it to receive every event.\n\n\n**Required scope:** `write_webhooks` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}}],"responses":{"201":{"description":"webhook endpoint created — secret_key returned once","content":{"application/json":{}}},"422":{"description":"validation error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["url"],"properties":{"name":{"type":"string"},"url":{"type":"string"},"active":{"type":"boolean"},"subscriptions":{"type":"array","items":{"type":"string"}}}}}}}}},"/api/v3/admin/webhook_endpoints/{id}":{"parameters":[{"name":"id","in":"path","required":true,"description":"Webhook endpoint ID","schema":{"type":"string"}}],"get":{"summary":"Get a webhook endpoint","tags":["Webhooks"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Returns a single webhook endpoint by prefixed ID.\n\n**Required scope:** `read_webhooks` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}},{"name":"fields","in":"query","required":false,"description":"Comma-separated list of fields to include. id is always included.","schema":{"type":"string"}}],"responses":{"200":{"description":"webhook endpoint found","content":{"application/json":{}}},"404":{"description":"webhook endpoint not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}},"patch":{"summary":"Update a webhook endpoint","tags":["Webhooks"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Updates name, URL, active flag, or the event subscription list.\nToggling `active` here is equivalent to calling `disable`/`enable`\nwithout an audit reason.\n\n\n**Required scope:** `write_webhooks` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}}],"responses":{"200":{"description":"webhook endpoint updated","content":{"application/json":{}}},"422":{"description":"validation error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string"},"url":{"type":"string"},"active":{"type":"boolean"},"subscriptions":{"type":"array","items":{"type":"string"}}}}}}}},"delete":{"summary":"Delete a webhook endpoint","tags":["Webhooks"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Soft-deletes the endpoint and stops future deliveries.\n\n**Required scope:** `write_webhooks` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}}],"responses":{"204":{"description":"webhook endpoint deleted"}}}},"/api/v3/admin/webhook_endpoints/{id}/send_test":{"parameters":[{"name":"id","in":"path","required":true,"description":"Webhook endpoint ID","schema":{"type":"string"}}],"post":{"summary":"Send a test delivery","tags":["Webhooks"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Creates a `webhook.test` delivery record and queues it. Use this to\nverify the endpoint is reachable and your signature verification\naccepts Spree's payloads.\n\n\n**Required scope:** `write_webhooks` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}}],"responses":{"201":{"description":"test delivery queued","content":{"application/json":{}}}}}},"/api/v3/admin/webhook_endpoints/{id}/enable":{"parameters":[{"name":"id","in":"path","required":true,"description":"Webhook endpoint ID","schema":{"type":"string"}}],"patch":{"summary":"Re-enable a webhook endpoint","tags":["Webhooks"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Re-enables an endpoint that was manually or automatically disabled.\n\n**Required scope:** `write_webhooks` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}}],"responses":{"200":{"description":"webhook endpoint enabled","content":{"application/json":{}}}}}},"/api/v3/admin/webhook_endpoints/{id}/disable":{"parameters":[{"name":"id","in":"path","required":true,"description":"Webhook endpoint ID","schema":{"type":"string"}}],"patch":{"summary":"Disable a webhook endpoint","tags":["Webhooks"],"security":[{"api_key":[],"bearer_auth":[]}],"description":"Manually pauses an endpoint. Unlike auto-disable (triggered after\nrepeated delivery failures), no notification email is sent.\n\n\n**Required scope:** `write_webhooks` (for API-key authentication).","parameters":[{"name":"x-spree-api-key","in":"header","required":true,"schema":{"type":"string"}},{"name":"Authorization","in":"header","required":true,"description":"Bearer token for admin authentication","schema":{"type":"string"}}],"responses":{"200":{"description":"webhook endpoint disabled","content":{"application/json":{}}}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"reason":{"type":"string"}}}}}}}}},"components":{"schemas":{"PaginationMeta":{"type":"object","properties":{"page":{"type":"integer"},"limit":{"type":"integer"},"count":{"type":"integer","description":"Total number of records"},"pages":{"type":"integer","description":"Total number of pages"},"from":{"type":"integer","description":"Index of first record on this page"},"to":{"type":"integer","description":"Index of last record on this page"},"in":{"type":"integer","description":"Number of records on this page"},"previous":{"type":"integer","nullable":true,"description":"Previous page number"},"next":{"type":"integer","nullable":true,"description":"Next page number"}},"required":["page","limit","count","pages","from","to","in"]},"ErrorResponse":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"},"details":{"type":"object","description":"Field-specific validation errors","nullable":true}},"required":["code","message"]}},"required":["error"]},"AuthResponse":{"type":"object","properties":{"token":{"type":"string","description":"JWT access token"},"user":{"$ref":"#/components/schemas/AdminUser"}},"required":["token","user"]},"PermissionRule":{"type":"object","description":"A single permission rule (CanCanCan rule). Rules are applied in order, last-matching-wins.","properties":{"allow":{"type":"boolean","description":"true for `can`, false for `cannot`"},"actions":{"type":"array","items":{"type":"string"},"description":"Action names, e.g. [\"read\", \"update\"] or [\"manage\"]"},"subjects":{"type":"array","items":{"type":"string"},"description":"Subject class names, e.g. [\"Spree::Product\"] or [\"all\"]"},"has_conditions":{"type":"boolean","description":"True if the server-side rule has per-record conditions. The SPA shows the action optimistically and handles 403 from the API."}},"required":["allow","actions","subjects","has_conditions"]},"MeResponse":{"type":"object","description":"Current admin user profile and serialized permissions","properties":{"user":{"$ref":"#/components/schemas/AdminUser"},"permissions":{"type":"array","items":{"$ref":"#/components/schemas/PermissionRule"}}},"required":["user","permissions"]},"CheckoutRequirement":{"type":"object","properties":{"step":{"type":"string","description":"Checkout step this requirement belongs to"},"field":{"type":"string","description":"Field that needs to be satisfied"},"message":{"type":"string","description":"Human-readable requirement message"}},"required":["step","field","message"]},"CartWarning":{"type":"object","description":"A warning about a cart issue (e.g., item removed due to stock change)","properties":{"code":{"type":"string","description":"Machine-readable warning code"},"message":{"type":"string","description":"Human-readable warning message"},"line_item_id":{"type":"string","nullable":true,"description":"Prefixed line item ID (when applicable)"},"variant_id":{"type":"string","nullable":true,"description":"Prefixed variant ID (when applicable)"}},"required":["code","message"]},"FulfillmentManifestItem":{"type":"object","description":"An item within a fulfillment — which line item and how many units are in this fulfillment","properties":{"item_id":{"type":"string","description":"Line item ID"},"variant_id":{"type":"string","description":"Variant ID"},"quantity":{"type":"integer","description":"Quantity in this fulfillment"}},"required":["item_id","variant_id","quantity"]},"AdminUserRoleAssignment":{"type":"object","description":"A role assignment for the current store on a staff member","properties":{"id":{"type":"string","description":"Prefixed role ID"},"name":{"type":"string","description":"Role name"}},"required":["id","name"]},"PreferenceField":{"type":"object","description":"A single configurable preference on a payment method, promotion rule/action, or calculator. The frontend uses `type` + `default` to render a sensible input.","properties":{"key":{"type":"string"},"type":{"type":"string","description":"string | text | password | integer | decimal | boolean | array | hash"},"default":{"description":"Default value (any JSON type), null when there is no default","nullable":true}},"required":["key","type"]},"PromotionActionCalculator":{"type":"object","description":"The action's nested calculator (when the action carries one — null for actions like `free_shipping`)","properties":{"type":{"type":"string","description":"Wire shorthand for the calculator subclass"},"label":{"type":"string"},"preferences":{"type":"object","additionalProperties":true},"preference_schema":{"type":"array","items":{"$ref":"#/components/schemas/PreferenceField"}}},"required":["type","label","preferences","preference_schema"]},"PromotionActionLineItem":{"type":"object","description":"One row in a `create_line_items` action — the variant added to the order and how many","properties":{"variant_id":{"type":"string"},"quantity":{"type":"integer"}},"required":["variant_id","quantity"]},"Address":{"type":"object","properties":{"id":{"type":"string"},"first_name":{"type":"string","nullable":true},"last_name":{"type":"string","nullable":true},"full_name":{"type":"string"},"address1":{"type":"string","nullable":true},"address2":{"type":"string","nullable":true},"postal_code":{"type":"string","nullable":true},"city":{"type":"string","nullable":true},"phone":{"type":"string","nullable":true},"company":{"type":"string","nullable":true},"country_name":{"type":"string"},"country_iso":{"type":"string"},"state_text":{"type":"string","nullable":true},"state_abbr":{"type":"string","nullable":true},"quick_checkout":{"type":"boolean"},"is_default_billing":{"type":"boolean"},"is_default_shipping":{"type":"boolean"},"state_name":{"type":"string","nullable":true},"label":{"type":"string","nullable":true},"metadata":{"type":"object"},"created_at":{"type":"string"},"updated_at":{"type":"string"},"customer_id":{"type":"string","nullable":true}},"required":["id","first_name","last_name","full_name","address1","address2","postal_code","city","phone","company","country_name","country_iso","state_text","state_abbr","quick_checkout","is_default_billing","is_default_shipping","state_name","label","metadata","created_at","updated_at","customer_id"],"x-typelizer":true},"Adjustment":{"type":"object","properties":{"id":{"type":"string"},"label":{"type":"string"},"display_amount":{"type":"string"},"included":{"type":"boolean"},"created_at":{"type":"string"},"updated_at":{"type":"string"},"amount":{"type":"string"},"order_id":{"type":"string","nullable":true}},"required":["id","label","display_amount","included","created_at","updated_at","amount","order_id"],"x-typelizer":true},"AdminUser":{"type":"object","properties":{"id":{"type":"string"},"email":{"type":"string"},"first_name":{"type":"string","nullable":true},"last_name":{"type":"string","nullable":true},"full_name":{"type":"string","nullable":true},"created_at":{"type":"string"},"updated_at":{"type":"string"},"roles":{"type":"array","items":{"$ref":"#/components/schemas/AdminUserRoleAssignment"}}},"required":["id","email","first_name","last_name","full_name","created_at","updated_at","roles"],"x-typelizer":true},"AllowedOrigin":{"type":"object","properties":{"id":{"type":"string"},"origin":{"type":"string"},"created_at":{"type":"string"},"updated_at":{"type":"string"}},"required":["id","origin","created_at","updated_at"],"x-typelizer":true},"ApiKey":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"key_type":{"type":"string"},"token_prefix":{"type":"string","nullable":true},"scopes":{"type":"array","items":{"type":"string"}},"created_at":{"type":"string"},"updated_at":{"type":"string"},"revoked_at":{"type":"string","nullable":true},"last_used_at":{"type":"string","nullable":true},"plaintext_token":{"type":"string","nullable":true},"created_by_email":{"type":"string","nullable":true}},"required":["id","name","key_type","token_prefix","scopes","created_at","updated_at","revoked_at","last_used_at","plaintext_token","created_by_email"],"x-typelizer":true},"Category":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"permalink":{"type":"string"},"position":{"type":"number"},"depth":{"type":"number"},"meta_title":{"type":"string","nullable":true},"meta_description":{"type":"string","nullable":true},"meta_keywords":{"type":"string","nullable":true},"children_count":{"type":"number"},"parent_id":{"type":"string","nullable":true},"description":{"type":"string"},"description_html":{"type":"string"},"image_url":{"type":"string","nullable":true},"square_image_url":{"type":"string","nullable":true},"is_root":{"type":"boolean"},"is_child":{"type":"boolean"},"is_leaf":{"type":"boolean"},"parent":{"$ref":"#/components/schemas/Category"},"children":{"type":"array","items":{"$ref":"#/components/schemas/Category"}},"ancestors":{"type":"array","items":{"$ref":"#/components/schemas/Category"}},"custom_fields":{"type":"array","items":{"$ref":"#/components/schemas/CustomField"}},"metadata":{"type":"object"},"pretty_name":{"type":"string"},"lft":{"type":"number"},"rgt":{"type":"number"},"created_at":{"type":"string"},"updated_at":{"type":"string"}},"required":["id","name","permalink","position","depth","meta_title","meta_description","meta_keywords","children_count","parent_id","description","description_html","image_url","square_image_url","is_root","is_child","is_leaf","metadata","pretty_name","lft","rgt","created_at","updated_at"],"x-typelizer":true},"Channel":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"code":{"type":"string"},"active":{"type":"boolean"},"default":{"type":"boolean"},"preferred_order_routing_strategy":{"type":"string","nullable":true},"created_at":{"type":"string"},"updated_at":{"type":"string"}},"required":["id","name","code","active","default","preferred_order_routing_strategy","created_at","updated_at"],"x-typelizer":true},"Country":{"type":"object","properties":{"iso":{"type":"string"},"iso3":{"type":"string"},"name":{"type":"string"},"states_required":{"type":"boolean"},"zipcode_required":{"type":"boolean"},"states":{"type":"array","items":{"$ref":"#/components/schemas/State"}},"market":{"allOf":[{"$ref":"#/components/schemas/Market"}],"nullable":true},"created_at":{"type":"object"},"updated_at":{"type":"object"}},"required":["iso","iso3","name","states_required","zipcode_required","created_at","updated_at"],"x-typelizer":true},"CouponCode":{"type":"object","properties":{"id":{"type":"string"},"code":{"type":"string"},"state":{"type":"string","nullable":true},"created_at":{"type":"string"},"updated_at":{"type":"string"},"promotion_id":{"type":"string"},"order_id":{"type":"string","nullable":true}},"required":["id","code","state","created_at","updated_at","promotion_id","order_id"],"x-typelizer":true},"CreditCard":{"type":"object","properties":{"id":{"type":"string"},"brand":{"type":"string"},"last4":{"type":"string"},"month":{"type":"number"},"year":{"type":"number"},"name":{"type":"string","nullable":true},"default":{"type":"boolean"},"gateway_payment_profile_id":{"type":"string","nullable":true},"customer_id":{"type":"string","nullable":true},"payment_method_id":{"type":"string","nullable":true},"metadata":{"type":"object"},"created_at":{"type":"string"},"updated_at":{"type":"string"}},"required":["id","brand","last4","month","year","name","default","gateway_payment_profile_id","customer_id","payment_method_id","metadata","created_at","updated_at"],"x-typelizer":true},"CustomFieldDefinition":{"type":"object","properties":{"id":{"type":"string"},"namespace":{"type":"string"},"key":{"type":"string"},"label":{"type":"string"},"field_type":{"type":"string","enum":["short_text","long_text","rich_text","number","boolean","json"]},"resource_type":{"type":"string"},"storefront_visible":{"type":"boolean"},"created_at":{"type":"string"},"updated_at":{"type":"string"}},"required":["id","namespace","key","label","field_type","resource_type","storefront_visible","created_at","updated_at"],"x-typelizer":true},"CustomField":{"type":"object","properties":{"id":{"type":"string"},"label":{"type":"string"},"type":{"type":"string","deprecated":true},"field_type":{"type":"string","enum":["short_text","long_text","rich_text","number","boolean","json"]},"key":{"type":"string"},"value":{"type":"object"},"created_at":{"type":"string"},"updated_at":{"type":"string"},"storefront_visible":{"type":"boolean"},"custom_field_definition_id":{"type":"string"}},"required":["id","label","type","field_type","key","value","created_at","updated_at","storefront_visible","custom_field_definition_id"],"x-typelizer":true},"CustomerGroup":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"description":{"type":"string","nullable":true},"customers_count":{"type":"number"},"created_at":{"type":"string"},"updated_at":{"type":"string"},"customers":{"type":"array","items":{"$ref":"#/components/schemas/Customer"}}},"required":["id","name","description","customers_count","created_at","updated_at"],"x-typelizer":true},"Customer":{"type":"object","properties":{"id":{"type":"string"},"email":{"type":"string"},"first_name":{"type":"string","nullable":true},"last_name":{"type":"string","nullable":true},"phone":{"type":"string","nullable":true},"accepts_email_marketing":{"type":"boolean"},"full_name":{"type":"string"},"available_store_credit_total":{"type":"string"},"display_available_store_credit_total":{"type":"string"},"addresses":{"type":"array","items":{"$ref":"#/components/schemas/Address"}},"default_billing_address":{"allOf":[{"$ref":"#/components/schemas/Address"}],"nullable":true},"default_shipping_address":{"allOf":[{"$ref":"#/components/schemas/Address"}],"nullable":true},"login":{"type":"string","nullable":true},"metadata":{"type":"object"},"last_sign_in_at":{"type":"string","nullable":true},"current_sign_in_at":{"type":"string","nullable":true},"created_at":{"type":"string"},"updated_at":{"type":"string"},"sign_in_count":{"type":"number"},"failed_attempts":{"type":"number"},"last_sign_in_ip":{"type":"string","nullable":true},"current_sign_in_ip":{"type":"string","nullable":true},"tags":{"type":"array","items":{"type":"string"}},"internal_note_html":{"type":"string","nullable":true},"default_billing_address_id":{"type":"string","nullable":true},"default_shipping_address_id":{"type":"string","nullable":true},"orders_count":{"type":"number"},"total_spent":{"type":"string"},"display_total_spent":{"type":"string"},"last_order_completed_at":{"type":"string","nullable":true},"orders":{"type":"array","items":{"$ref":"#/components/schemas/Order"}},"store_credits":{"type":"array","items":{"$ref":"#/components/schemas/StoreCredit"}},"customer_groups":{"type":"array","items":{"$ref":"#/components/schemas/CustomerGroup"}}},"required":["id","email","first_name","last_name","phone","accepts_email_marketing","full_name","available_store_credit_total","display_available_store_credit_total","login","metadata","last_sign_in_at","current_sign_in_at","created_at","updated_at","sign_in_count","failed_attempts","last_sign_in_ip","current_sign_in_ip","tags","internal_note_html","default_billing_address_id","default_shipping_address_id","orders_count","total_spent","display_total_spent","last_order_completed_at"],"x-typelizer":true},"DeliveryMethod":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"code":{"type":"string","nullable":true},"created_at":{"type":"string"},"updated_at":{"type":"string"}},"required":["id","name","code","created_at","updated_at"],"x-typelizer":true},"DeliveryRate":{"type":"object","properties":{"id":{"type":"string"},"delivery_method_id":{"type":"string"},"name":{"type":"string"},"selected":{"type":"boolean"},"cost":{"type":"string"},"total":{"type":"string"},"additional_tax_total":{"type":"string"},"included_tax_total":{"type":"string"},"tax_total":{"type":"string"},"display_cost":{"type":"string"},"display_total":{"type":"string"},"display_additional_tax_total":{"type":"string"},"display_included_tax_total":{"type":"string"},"display_tax_total":{"type":"string"},"delivery_method":{"$ref":"#/components/schemas/DeliveryMethod"},"created_at":{"type":"string"},"updated_at":{"type":"string"}},"required":["id","delivery_method_id","name","selected","cost","total","additional_tax_total","included_tax_total","tax_total","display_cost","display_total","display_additional_tax_total","display_included_tax_total","display_tax_total","created_at","updated_at"],"x-typelizer":true},"DigitalLink":{"type":"object","properties":{"id":{"type":"string"},"access_counter":{"type":"number"},"filename":{"type":"string"},"content_type":{"type":"string"},"download_url":{"type":"string"},"authorizable":{"type":"boolean"},"expired":{"type":"boolean"},"access_limit_exceeded":{"type":"boolean"},"created_at":{"type":"string"},"updated_at":{"type":"string"}},"required":["id","access_counter","filename","content_type","download_url","authorizable","expired","access_limit_exceeded","created_at","updated_at"],"x-typelizer":true},"Discount":{"type":"object","properties":{"id":{"type":"string"},"promotion_id":{"type":"string"},"name":{"type":"string"},"description":{"type":"string","nullable":true},"code":{"type":"string","nullable":true},"amount":{"type":"string"},"display_amount":{"type":"string"},"created_at":{"type":"string"},"updated_at":{"type":"string"}},"required":["id","promotion_id","name","description","code","amount","display_amount","created_at","updated_at"],"x-typelizer":true},"Export":{"type":"object","properties":{"id":{"type":"string"},"number":{"type":"string"},"type":{"type":"string","nullable":true},"format":{"type":"string","nullable":true},"created_at":{"type":"string"},"updated_at":{"type":"string"},"user_id":{"type":"string","nullable":true},"done":{"type":"boolean"},"filename":{"type":"string","nullable":true},"byte_size":{"type":"number","nullable":true},"download_url":{"type":"string","nullable":true}},"required":["id","number","type","format","created_at","updated_at","user_id","done","filename","byte_size","download_url"],"x-typelizer":true},"Fulfillment":{"type":"object","properties":{"id":{"type":"string"},"number":{"type":"string"},"tracking":{"type":"string","nullable":true},"tracking_url":{"type":"string","nullable":true},"cost":{"type":"string"},"display_cost":{"type":"string"},"total":{"type":"string"},"display_total":{"type":"string"},"discount_total":{"type":"string"},"display_discount_total":{"type":"string"},"additional_tax_total":{"type":"string"},"display_additional_tax_total":{"type":"string"},"included_tax_total":{"type":"string"},"display_included_tax_total":{"type":"string"},"tax_total":{"type":"string"},"display_tax_total":{"type":"string"},"status":{"type":"string"},"fulfillment_type":{"type":"string"},"fulfilled_at":{"type":"string","nullable":true},"items":{"type":"array","items":{"$ref":"#/components/schemas/FulfillmentManifestItem"}},"delivery_method":{"$ref":"#/components/schemas/DeliveryMethod"},"stock_location":{"$ref":"#/components/schemas/StockLocation"},"delivery_rates":{"type":"array","items":{"$ref":"#/components/schemas/DeliveryRate"}},"metadata":{"type":"object"},"adjustment_total":{"type":"string"},"pre_tax_amount":{"type":"string"},"created_at":{"type":"string"},"updated_at":{"type":"string"},"order_id":{"type":"string","nullable":true},"stock_location_id":{"type":"string","nullable":true},"order":{"$ref":"#/components/schemas/Order"},"adjustments":{"type":"array","items":{"$ref":"#/components/schemas/Adjustment"}}},"required":["id","number","tracking","tracking_url","cost","display_cost","total","display_total","discount_total","display_discount_total","additional_tax_total","display_additional_tax_total","included_tax_total","display_included_tax_total","tax_total","display_tax_total","status","fulfillment_type","fulfilled_at","items","metadata","adjustment_total","pre_tax_amount","created_at","updated_at","order_id","stock_location_id"],"x-typelizer":true},"GiftCardBatch":{"type":"object","properties":{"id":{"type":"string"},"codes_count":{"type":"number"},"currency":{"type":"string","nullable":true},"prefix":{"type":"string","nullable":true},"created_at":{"type":"string"},"updated_at":{"type":"string"},"amount":{"type":"string","nullable":true},"expires_at":{"type":"string","nullable":true},"created_by_id":{"type":"string","nullable":true}},"required":["id","codes_count","currency","prefix","created_at","updated_at","amount","expires_at","created_by_id"],"x-typelizer":true},"GiftCard":{"type":"object","properties":{"id":{"type":"string"},"code":{"type":"string"},"status":{"type":"string"},"currency":{"type":"string"},"amount":{"type":"string"},"amount_used":{"type":"string"},"amount_authorized":{"type":"string"},"amount_remaining":{"type":"string"},"display_amount":{"type":"string"},"display_amount_used":{"type":"string"},"display_amount_remaining":{"type":"string"},"expires_at":{"type":"string","nullable":true},"redeemed_at":{"type":"string","nullable":true},"expired":{"type":"boolean"},"active":{"type":"boolean"},"created_at":{"type":"string"},"updated_at":{"type":"string"},"customer_id":{"type":"string","nullable":true},"created_by_id":{"type":"string","nullable":true},"customer":{"$ref":"#/components/schemas/Customer"},"created_by":{"$ref":"#/components/schemas/AdminUser"},"gift_card_batch":{"$ref":"#/components/schemas/GiftCardBatch"},"orders":{"type":"array","items":{"$ref":"#/components/schemas/Order"}}},"required":["id","code","status","currency","amount","amount_used","amount_authorized","amount_remaining","display_amount","display_amount_used","display_amount_remaining","expires_at","redeemed_at","expired","active","created_at","updated_at","customer_id","created_by_id"],"x-typelizer":true},"Invitation":{"type":"object","properties":{"id":{"type":"string"},"email":{"type":"string"},"status":{"type":"string"},"created_at":{"type":"string"},"updated_at":{"type":"string"},"expires_at":{"type":"string"},"role_id":{"type":"string"},"role_name":{"type":"string"},"inviter_email":{"type":"string"},"acceptance_url":{"type":"string"},"invitee_exists":{"type":"boolean"},"store":{"type":"object"}},"required":["id","email","status","created_at","updated_at","expires_at","role_id","role_name","inviter_email","acceptance_url","invitee_exists","store"],"x-typelizer":true},"LineItem":{"type":"object","properties":{"id":{"type":"string"},"variant_id":{"type":"string"},"quantity":{"type":"number"},"currency":{"type":"string"},"name":{"type":"string"},"slug":{"type":"string"},"options_text":{"type":"string"},"price":{"type":"string"},"display_price":{"type":"string"},"total":{"type":"string"},"display_total":{"type":"string"},"adjustment_total":{"type":"string"},"display_adjustment_total":{"type":"string"},"additional_tax_total":{"type":"string"},"display_additional_tax_total":{"type":"string"},"included_tax_total":{"type":"string"},"display_included_tax_total":{"type":"string"},"discount_total":{"type":"string"},"display_discount_total":{"type":"string"},"pre_tax_amount":{"type":"string"},"display_pre_tax_amount":{"type":"string"},"discounted_amount":{"type":"string"},"display_discounted_amount":{"type":"string"},"display_compare_at_amount":{"type":"string","nullable":true},"compare_at_amount":{"type":"string","nullable":true},"thumbnail_url":{"type":"string","nullable":true},"option_values":{"type":"array","items":{"$ref":"#/components/schemas/OptionValue"}},"digital_links":{"type":"array","items":{"$ref":"#/components/schemas/DigitalLink"}},"metadata":{"type":"object"},"created_at":{"type":"string"},"updated_at":{"type":"string"},"cost_price":{"type":"string","nullable":true},"tax_category_id":{"type":"string","nullable":true},"variant":{"$ref":"#/components/schemas/Variant"},"tax_category":{"$ref":"#/components/schemas/TaxCategory"},"adjustments":{"type":"array","items":{"$ref":"#/components/schemas/Adjustment"}}},"required":["id","variant_id","quantity","currency","name","slug","options_text","price","display_price","total","display_total","adjustment_total","display_adjustment_total","additional_tax_total","display_additional_tax_total","included_tax_total","display_included_tax_total","discount_total","display_discount_total","pre_tax_amount","display_pre_tax_amount","discounted_amount","display_discounted_amount","display_compare_at_amount","compare_at_amount","thumbnail_url","option_values","digital_links","metadata","created_at","updated_at","cost_price","tax_category_id"],"x-typelizer":true},"Market":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"currency":{"type":"string"},"default_locale":{"type":"string"},"tax_inclusive":{"type":"boolean"},"default":{"type":"boolean"},"country_isos":{"type":"array","items":{"type":"string"}},"supported_locales":{"type":"array","items":{"type":"string"}},"countries":{"type":"array","items":{"$ref":"#/components/schemas/Country"}},"created_at":{"type":"string"},"updated_at":{"type":"string"}},"required":["id","name","currency","default_locale","tax_inclusive","default","country_isos","supported_locales","created_at","updated_at"],"x-typelizer":true},"Media":{"type":"object","properties":{"id":{"type":"string"},"product_id":{"type":"string","nullable":true},"variant_ids":{"type":"array","items":{"type":"string"}},"position":{"type":"number"},"alt":{"type":"string","nullable":true},"media_type":{"type":"string"},"focal_point_x":{"type":"number","nullable":true},"focal_point_y":{"type":"number","nullable":true},"external_video_url":{"type":"string","nullable":true},"original_url":{"type":"string","nullable":true},"mini_url":{"type":"string","nullable":true},"small_url":{"type":"string","nullable":true},"medium_url":{"type":"string","nullable":true},"large_url":{"type":"string","nullable":true},"xlarge_url":{"type":"string","nullable":true},"og_image_url":{"type":"string","nullable":true},"created_at":{"type":"string"},"updated_at":{"type":"string"},"viewable_id":{"type":"string"},"download_url":{"type":"string","nullable":true},"metadata":{"type":"object"},"viewable_type":{"type":"string"}},"required":["id","product_id","variant_ids","position","alt","media_type","focal_point_x","focal_point_y","external_video_url","original_url","mini_url","small_url","medium_url","large_url","xlarge_url","og_image_url","created_at","updated_at","viewable_id","download_url","metadata","viewable_type"],"x-typelizer":true},"OptionType":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"label":{"type":"string"},"position":{"type":"number"},"kind":{"type":"string"},"metadata":{"type":"object"},"filterable":{"type":"boolean"},"created_at":{"type":"string"},"updated_at":{"type":"string"},"option_values":{"type":"array","items":{"$ref":"#/components/schemas/OptionValue"}}},"required":["id","name","label","position","kind","metadata","filterable","created_at","updated_at"],"x-typelizer":true},"OptionValue":{"type":"object","properties":{"id":{"type":"string"},"option_type_id":{"type":"string"},"name":{"type":"string"},"label":{"type":"string"},"position":{"type":"number"},"color_code":{"type":"string","nullable":true},"option_type_name":{"type":"string"},"option_type_label":{"type":"string"},"image_url":{"type":"string","nullable":true},"metadata":{"type":"object"},"created_at":{"type":"string"},"updated_at":{"type":"string"},"option_type":{"$ref":"#/components/schemas/OptionType"}},"required":["id","option_type_id","name","label","position","color_code","option_type_name","option_type_label","image_url","metadata","created_at","updated_at"],"x-typelizer":true},"Order":{"type":"object","properties":{"id":{"type":"string"},"market_id":{"type":"string","nullable":true},"channel_id":{"type":"string","nullable":true},"number":{"type":"string"},"email":{"type":"string"},"customer_note":{"type":"string","nullable":true},"currency":{"type":"string"},"locale":{"type":"string","nullable":true},"total_quantity":{"type":"number"},"item_total":{"type":"string"},"display_item_total":{"type":"string"},"adjustment_total":{"type":"string"},"display_adjustment_total":{"type":"string"},"discount_total":{"type":"string"},"display_discount_total":{"type":"string"},"tax_total":{"type":"string"},"display_tax_total":{"type":"string"},"included_tax_total":{"type":"string"},"display_included_tax_total":{"type":"string"},"additional_tax_total":{"type":"string"},"display_additional_tax_total":{"type":"string"},"total":{"type":"string"},"display_total":{"type":"string"},"gift_card_total":{"type":"string"},"display_gift_card_total":{"type":"string"},"amount_due":{"type":"string"},"display_amount_due":{"type":"string"},"delivery_total":{"type":"string"},"display_delivery_total":{"type":"string"},"fulfillment_status":{"type":"string","nullable":true},"payment_status":{"type":"string","nullable":true},"completed_at":{"type":"string","nullable":true},"store_credit_total":{"type":"string"},"display_store_credit_total":{"type":"string"},"covered_by_store_credit":{"type":"boolean"},"discounts":{"type":"array","items":{"$ref":"#/components/schemas/Discount"}},"items":{"type":"array","items":{"$ref":"#/components/schemas/LineItem"}},"fulfillments":{"type":"array","items":{"$ref":"#/components/schemas/Fulfillment"}},"payments":{"type":"array","items":{"$ref":"#/components/schemas/Payment"}},"billing_address":{"allOf":[{"$ref":"#/components/schemas/Address"}],"nullable":true},"shipping_address":{"allOf":[{"$ref":"#/components/schemas/Address"}],"nullable":true},"gift_card":{"allOf":[{"$ref":"#/components/schemas/GiftCard"}],"nullable":true},"market":{"allOf":[{"$ref":"#/components/schemas/Market"}],"nullable":true},"status":{"type":"string"},"last_ip_address":{"type":"string","nullable":true},"considered_risky":{"type":"boolean"},"confirmation_delivered":{"type":"boolean"},"store_owner_notification_delivered":{"type":"boolean"},"payment_total":{"type":"string"},"display_payment_total":{"type":"string"},"metadata":{"type":"object"},"canceled_at":{"type":"string","nullable":true},"approved_at":{"type":"string","nullable":true},"created_at":{"type":"string"},"updated_at":{"type":"string"},"preferred_stock_location_id":{"type":"string","nullable":true},"tags":{"type":"array","items":{"type":"string"}},"internal_note":{"type":"string","nullable":true},"approver_id":{"type":"string","nullable":true},"canceler_id":{"type":"string","nullable":true},"created_by_id":{"type":"string","nullable":true},"customer_id":{"type":"string","nullable":true},"channel":{"$ref":"#/components/schemas/Channel"},"preferred_stock_location":{"$ref":"#/components/schemas/StockLocation"},"payment_methods":{"type":"array","items":{"$ref":"#/components/schemas/PaymentMethod"}},"customer":{"$ref":"#/components/schemas/Customer"},"approver":{"$ref":"#/components/schemas/Customer"},"canceler":{"$ref":"#/components/schemas/Customer"},"created_by":{"$ref":"#/components/schemas/Customer"},"adjustments":{"type":"array","items":{"$ref":"#/components/schemas/Adjustment"}},"return_authorizations":{"type":"array","items":{"$ref":"#/components/schemas/ReturnAuthorization"}},"reimbursements":{"type":"array","items":{"$ref":"#/components/schemas/Reimbursement"}}},"required":["id","market_id","channel_id","number","email","customer_note","currency","locale","total_quantity","item_total","display_item_total","adjustment_total","display_adjustment_total","discount_total","display_discount_total","tax_total","display_tax_total","included_tax_total","display_included_tax_total","additional_tax_total","display_additional_tax_total","total","display_total","gift_card_total","display_gift_card_total","amount_due","display_amount_due","delivery_total","display_delivery_total","fulfillment_status","payment_status","completed_at","store_credit_total","display_store_credit_total","covered_by_store_credit","gift_card","market","status","last_ip_address","considered_risky","confirmation_delivered","store_owner_notification_delivered","payment_total","display_payment_total","metadata","canceled_at","approved_at","created_at","updated_at","preferred_stock_location_id","tags","internal_note","approver_id","canceler_id","created_by_id","customer_id"],"x-typelizer":true},"PaymentMethod":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"description":{"type":"string","nullable":true},"type":{"type":"string"},"session_required":{"type":"boolean"},"source_required":{"type":"boolean"},"metadata":{"type":"object"},"active":{"type":"boolean"},"auto_capture":{"type":"boolean","nullable":true},"storefront_visible":{"type":"boolean"},"position":{"type":"number"},"created_at":{"type":"string"},"updated_at":{"type":"string"},"preferences":{"type":"object"},"preference_schema":{"type":"object"}},"required":["id","name","description","type","session_required","source_required","metadata","active","auto_capture","storefront_visible","position","created_at","updated_at","preferences","preference_schema"],"x-typelizer":true},"Payment":{"type":"object","properties":{"id":{"type":"string"},"payment_method_id":{"type":"string"},"response_code":{"type":"string","nullable":true},"number":{"type":"string"},"amount":{"type":"string"},"display_amount":{"type":"string"},"status":{"type":"string"},"source_type":{"type":"string","nullable":true,"enum":["credit_card","store_credit","payment_source"]},"source_id":{"type":"string","nullable":true},"source":{"anyOf":[{"$ref":"#/components/schemas/CreditCard"},{"$ref":"#/components/schemas/StoreCredit"},{"$ref":"#/components/schemas/PaymentSource"}],"nullable":true},"payment_method":{"$ref":"#/components/schemas/PaymentMethod"},"metadata":{"type":"object"},"avs_response":{"type":"string","nullable":true},"cvv_response_code":{"type":"string","nullable":true},"cvv_response_message":{"type":"string","nullable":true},"created_at":{"type":"string"},"updated_at":{"type":"string"},"captured_amount":{"type":"string"},"order_id":{"type":"string","nullable":true},"order":{"$ref":"#/components/schemas/Order"},"refunds":{"type":"array","items":{"$ref":"#/components/schemas/Refund"}}},"required":["id","payment_method_id","response_code","number","amount","display_amount","status","source_type","source_id","source","metadata","avs_response","cvv_response_code","cvv_response_message","created_at","updated_at","captured_amount","order_id"],"x-typelizer":true},"PaymentSource":{"type":"object","properties":{"id":{"type":"string"},"gateway_payment_profile_id":{"type":"string","nullable":true},"metadata":{"type":"object"},"created_at":{"type":"string"},"updated_at":{"type":"string"}},"required":["id","gateway_payment_profile_id","metadata","created_at","updated_at"],"x-typelizer":true},"PriceHistory":{"type":"object","properties":{"id":{"type":"string"},"amount":{"type":"string"},"amount_in_cents":{"type":"number"},"currency":{"type":"string"},"display_amount":{"type":"string"},"recorded_at":{"type":"string"},"variant_id":{"type":"string"},"price_id":{"type":"string"},"compare_at_amount":{"type":"string","nullable":true},"created_at":{"type":"string"}},"required":["id","amount","amount_in_cents","currency","display_amount","recorded_at","variant_id","price_id","compare_at_amount","created_at"],"x-typelizer":true},"PriceList":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"description":{"type":"string","nullable":true},"status":{"type":"string"},"position":{"type":"number"},"match_policy":{"type":"string"},"starts_at":{"type":"string","nullable":true},"ends_at":{"type":"string","nullable":true},"deleted_at":{"type":"string","nullable":true},"created_at":{"type":"string"},"updated_at":{"type":"string"},"currently_active":{"type":"boolean"},"products_count":{"type":"number"},"prices_count":{"type":"number"},"product_ids":{"type":"array","items":{"type":"string"}},"price_rules":{"type":"array","items":{"$ref":"#/components/schemas/PriceRule"}}},"required":["id","name","description","status","position","match_policy","starts_at","ends_at","deleted_at","created_at","updated_at","currently_active","products_count","prices_count","product_ids"],"x-typelizer":true},"PriceRule":{"type":"object","properties":{"id":{"type":"string"},"created_at":{"type":"string"},"updated_at":{"type":"string"},"type":{"type":"string"},"price_list_id":{"type":"string"},"preferences":{"type":"object"},"preference_schema":{"type":"array","items":{"$ref":"#/components/schemas/PreferenceField"}},"label":{"type":"string"},"description":{"type":"string","nullable":true},"markets":{"type":"array","items":{"$ref":"#/components/schemas/Market"}},"customer_groups":{"type":"array","items":{"$ref":"#/components/schemas/CustomerGroup"}},"customers":{"type":"array","items":{"$ref":"#/components/schemas/Customer"}}},"required":["id","created_at","updated_at","type","price_list_id","preferences","preference_schema","label","description"],"x-typelizer":true},"Price":{"type":"object","properties":{"id":{"type":"string"},"amount":{"type":"string","nullable":true},"amount_in_cents":{"type":"number","nullable":true},"compare_at_amount":{"type":"string","nullable":true},"compare_at_amount_in_cents":{"type":"number","nullable":true},"currency":{"type":"string","nullable":true},"display_amount":{"type":"string","nullable":true},"display_compare_at_amount":{"type":"string","nullable":true},"price_list_id":{"type":"string","nullable":true},"variant_id":{"type":"string","nullable":true},"created_at":{"type":"string"},"updated_at":{"type":"string"},"variant":{"$ref":"#/components/schemas/Variant"}},"required":["id","amount","amount_in_cents","compare_at_amount","compare_at_amount_in_cents","currency","display_amount","display_compare_at_amount","price_list_id","variant_id","created_at","updated_at"],"x-typelizer":true},"ProductPublication":{"type":"object","properties":{"id":{"type":"string"},"published_at":{"type":"string","nullable":true},"unpublished_at":{"type":"string","nullable":true},"product_id":{"type":"string"},"channel_id":{"type":"string"},"created_at":{"type":"string"},"updated_at":{"type":"string"}},"required":["id","published_at","unpublished_at","product_id","channel_id","created_at","updated_at"],"x-typelizer":true},"Product":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"slug":{"type":"string"},"meta_title":{"type":"string","nullable":true},"meta_description":{"type":"string","nullable":true},"meta_keywords":{"type":"string","nullable":true},"variant_count":{"type":"number"},"available_on":{"type":"string","nullable":true},"purchasable":{"type":"boolean"},"in_stock":{"type":"boolean"},"backorderable":{"type":"boolean"},"available":{"type":"boolean"},"description":{"type":"string","nullable":true},"description_html":{"type":"string","nullable":true},"default_variant_id":{"type":"string"},"thumbnail_url":{"type":"string","nullable":true},"tags":{"type":"array","items":{"type":"string"}},"price":{"allOf":[{"$ref":"#/components/schemas/Price"}],"nullable":true},"original_price":{"allOf":[{"$ref":"#/components/schemas/Price"}],"nullable":true},"primary_media":{"$ref":"#/components/schemas/Media"},"media":{"type":"array","items":{"$ref":"#/components/schemas/Media"}},"variants":{"type":"array","items":{"$ref":"#/components/schemas/Variant"}},"default_variant":{"$ref":"#/components/schemas/Variant"},"option_types":{"type":"array","items":{"$ref":"#/components/schemas/OptionType"}},"option_values":{"type":"array","items":{"$ref":"#/components/schemas/OptionValue"}},"categories":{"type":"array","items":{"$ref":"#/components/schemas/Category"}},"custom_fields":{"type":"array","items":{"$ref":"#/components/schemas/CustomField"}},"prior_price":{"allOf":[{"$ref":"#/components/schemas/PriceHistory"}],"nullable":true},"status":{"type":"string"},"metadata":{"type":"object"},"deleted_at":{"type":"string","nullable":true},"created_at":{"type":"string"},"updated_at":{"type":"string"},"tax_category_id":{"type":"string","nullable":true},"product_publications":{"type":"array","items":{"$ref":"#/components/schemas/ProductPublication"}},"channels":{"type":"array","items":{"$ref":"#/components/schemas/Channel"}}},"required":["id","name","slug","meta_title","meta_description","meta_keywords","variant_count","available_on","purchasable","in_stock","backorderable","available","description","description_html","default_variant_id","thumbnail_url","tags","price","original_price","status","metadata","deleted_at","created_at","updated_at","tax_category_id"],"x-typelizer":true},"PromotionAction":{"type":"object","properties":{"id":{"type":"string"},"created_at":{"type":"string"},"updated_at":{"type":"string"},"type":{"type":"string"},"promotion_id":{"type":"string"},"preferences":{"type":"object"},"preference_schema":{"type":"array","items":{"$ref":"#/components/schemas/PreferenceField"}},"label":{"type":"string"},"calculator":{"allOf":[{"$ref":"#/components/schemas/PromotionActionCalculator"}],"nullable":true},"line_items":{"type":"array","items":{"$ref":"#/components/schemas/PromotionActionLineItem"},"nullable":true}},"required":["id","created_at","updated_at","type","promotion_id","preferences","preference_schema","label","calculator","line_items"],"x-typelizer":true},"PromotionRule":{"type":"object","properties":{"id":{"type":"string"},"created_at":{"type":"string"},"updated_at":{"type":"string"},"type":{"type":"string"},"promotion_id":{"type":"string"},"preferences":{"type":"object"},"preference_schema":{"type":"array","items":{"$ref":"#/components/schemas/PreferenceField"}},"label":{"type":"string"},"product_ids":{"type":"array","items":{"type":"string"},"nullable":true},"category_ids":{"type":"array","items":{"type":"string"},"nullable":true},"customer_ids":{"type":"array","items":{"type":"string"},"nullable":true},"products":{"type":"array","items":{"$ref":"#/components/schemas/Product"}},"categories":{"type":"array","items":{"$ref":"#/components/schemas/Category"}},"customers":{"type":"array","items":{"$ref":"#/components/schemas/Customer"}},"customer_groups":{"type":"array","items":{"$ref":"#/components/schemas/CustomerGroup"}},"countries":{"type":"array","items":{"$ref":"#/components/schemas/Country"}}},"required":["id","created_at","updated_at","type","promotion_id","preferences","preference_schema","label","product_ids","category_ids","customer_ids"],"x-typelizer":true},"Promotion":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"description":{"type":"string","nullable":true},"code":{"type":"string","nullable":true},"starts_at":{"type":"string","nullable":true},"expires_at":{"type":"string","nullable":true},"usage_limit":{"type":"number","nullable":true},"match_policy":{"type":"string","enum":["all","any"]},"path":{"type":"string","nullable":true},"kind":{"type":"string","enum":["coupon_code","automatic"]},"multi_codes":{"type":"boolean"},"number_of_codes":{"type":"number","nullable":true},"code_prefix":{"type":"string","nullable":true},"promotion_category_id":{"type":"string","nullable":true},"metadata":{"type":"object"},"created_at":{"type":"string"},"updated_at":{"type":"string"},"action_ids":{"type":"array","items":{"type":"string"}},"rule_ids":{"type":"array","items":{"type":"string"}}},"required":["id","name","description","code","starts_at","expires_at","usage_limit","match_policy","path","kind","multi_codes","number_of_codes","code_prefix","promotion_category_id","metadata","created_at","updated_at","action_ids","rule_ids"],"x-typelizer":true},"Refund":{"type":"object","properties":{"id":{"type":"string"},"transaction_id":{"type":"string","nullable":true},"amount":{"type":"string","nullable":true},"payment_id":{"type":"string","nullable":true},"refund_reason_id":{"type":"string","nullable":true},"reimbursement_id":{"type":"string","nullable":true},"metadata":{"type":"object"},"created_at":{"type":"string"},"updated_at":{"type":"string"},"payment":{"$ref":"#/components/schemas/Payment"},"reimbursement":{"$ref":"#/components/schemas/Reimbursement"}},"required":["id","transaction_id","amount","payment_id","refund_reason_id","reimbursement_id","metadata","created_at","updated_at"],"x-typelizer":true},"Reimbursement":{"type":"object","properties":{"id":{"type":"string"},"number":{"type":"string"},"reimbursement_status":{"type":"string","nullable":true},"total":{"type":"string","nullable":true},"order_id":{"type":"string","nullable":true},"customer_return_id":{"type":"string","nullable":true},"created_at":{"type":"string"},"updated_at":{"type":"string"},"order":{"$ref":"#/components/schemas/Order"}},"required":["id","number","reimbursement_status","total","order_id","customer_return_id","created_at","updated_at"],"x-typelizer":true},"ReturnAuthorization":{"type":"object","properties":{"id":{"type":"string"},"number":{"type":"string"},"status":{"type":"string"},"order_id":{"type":"string","nullable":true},"stock_location_id":{"type":"string","nullable":true},"return_authorization_reason_id":{"type":"string","nullable":true},"created_at":{"type":"string"},"updated_at":{"type":"string"},"order":{"$ref":"#/components/schemas/Order"},"stock_location":{"$ref":"#/components/schemas/StockLocation"}},"required":["id","number","status","order_id","stock_location_id","return_authorization_reason_id","created_at","updated_at"],"x-typelizer":true},"Role":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"created_at":{"type":"string"},"updated_at":{"type":"string"}},"required":["id","name","created_at","updated_at"],"x-typelizer":true},"State":{"type":"object","properties":{"abbr":{"type":"string"},"name":{"type":"string"},"created_at":{"type":"object"},"updated_at":{"type":"object"}},"required":["abbr","name","created_at","updated_at"],"x-typelizer":true},"StockItem":{"type":"object","properties":{"id":{"type":"string"},"count_on_hand":{"type":"number"},"backorderable":{"type":"boolean"},"stock_location_id":{"type":"string","nullable":true},"variant_id":{"type":"string","nullable":true},"metadata":{"type":"object"},"created_at":{"type":"string"},"updated_at":{"type":"string"},"allocated_count":{"type":"number"},"available_count":{"type":"number"},"stock_location":{"$ref":"#/components/schemas/StockLocation"},"variant":{"$ref":"#/components/schemas/Variant"}},"required":["id","count_on_hand","backorderable","stock_location_id","variant_id","metadata","created_at","updated_at","allocated_count","available_count"],"x-typelizer":true},"StockLocation":{"type":"object","properties":{"id":{"type":"string"},"state_abbr":{"type":"string","nullable":true},"name":{"type":"string"},"address1":{"type":"string","nullable":true},"city":{"type":"string","nullable":true},"zipcode":{"type":"string","nullable":true},"country_iso":{"type":"string","nullable":true},"country_name":{"type":"string","nullable":true},"state_text":{"type":"string","nullable":true},"admin_name":{"type":"string","nullable":true},"address2":{"type":"string","nullable":true},"state_name":{"type":"string","nullable":true},"phone":{"type":"string","nullable":true},"company":{"type":"string","nullable":true},"active":{"type":"boolean"},"default":{"type":"boolean"},"backorderable_default":{"type":"boolean"},"propagate_all_variants":{"type":"boolean"},"kind":{"type":"string"},"pickup_enabled":{"type":"boolean"},"pickup_stock_policy":{"type":"string"},"pickup_ready_in_minutes":{"type":"number","nullable":true},"pickup_instructions":{"type":"string","nullable":true},"created_at":{"type":"string"},"updated_at":{"type":"string"}},"required":["id","state_abbr","name","address1","city","zipcode","country_iso","country_name","state_text","admin_name","address2","state_name","phone","company","active","default","backorderable_default","propagate_all_variants","kind","pickup_enabled","pickup_stock_policy","pickup_ready_in_minutes","pickup_instructions","created_at","updated_at"],"x-typelizer":true},"StockReservation":{"type":"object","properties":{"id":{"type":"string"},"stock_item_id":{"type":"string"},"line_item_id":{"type":"string"},"order_id":{"type":"string"},"variant_id":{"type":"string","nullable":true},"stock_location_id":{"type":"string","nullable":true},"quantity":{"type":"number"},"expires_at":{"type":"string"},"active":{"type":"boolean"},"created_at":{"type":"string"},"updated_at":{"type":"string"}},"required":["id","stock_item_id","line_item_id","order_id","variant_id","stock_location_id","quantity","expires_at","active","created_at","updated_at"],"x-typelizer":true},"StockTransfer":{"type":"object","properties":{"id":{"type":"string"},"number":{"type":"string"},"reference":{"type":"string","nullable":true},"metadata":{"type":"object"},"created_at":{"type":"string"},"updated_at":{"type":"string"},"source_location_id":{"type":"string","nullable":true},"destination_location_id":{"type":"string","nullable":true},"source_location":{"$ref":"#/components/schemas/StockLocation"},"destination_location":{"$ref":"#/components/schemas/StockLocation"}},"required":["id","number","reference","metadata","created_at","updated_at","source_location_id","destination_location_id"],"x-typelizer":true},"StoreCreditCategory":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"created_at":{"type":"string"},"updated_at":{"type":"string"},"non_expiring":{"type":"boolean"}},"required":["id","name","created_at","updated_at","non_expiring"],"x-typelizer":true},"StoreCredit":{"type":"object","properties":{"id":{"type":"string"},"amount":{"type":"string"},"amount_used":{"type":"string"},"amount_remaining":{"type":"string"},"display_amount":{"type":"string"},"display_amount_used":{"type":"string"},"display_amount_remaining":{"type":"string"},"currency":{"type":"string"},"memo":{"type":"string","nullable":true},"metadata":{"type":"object"},"created_at":{"type":"string"},"updated_at":{"type":"string"},"customer_id":{"type":"string","nullable":true},"created_by_id":{"type":"string","nullable":true},"category_id":{"type":"string","nullable":true},"category_name":{"type":"string","nullable":true}},"required":["id","amount","amount_used","amount_remaining","display_amount","display_amount_used","display_amount_remaining","currency","memo","metadata","created_at","updated_at","customer_id","created_by_id","category_id","category_name"],"x-typelizer":true},"Store":{"type":"object","properties":{"id":{"type":"string"},"metadata":{"type":"object"},"name":{"type":"string"},"default_currency":{"type":"string"},"default_locale":{"type":"string"},"mail_from_address":{"type":"string","nullable":true},"customer_support_email":{"type":"string","nullable":true},"new_order_notifications_email":{"type":"string","nullable":true},"preferred_send_consumer_transactional_emails":{"type":"boolean"},"preferred_admin_locale":{"type":"string","nullable":true},"preferred_timezone":{"type":"string"},"preferred_weight_unit":{"type":"string"},"preferred_unit_system":{"type":"string"},"created_at":{"type":"string"},"updated_at":{"type":"string"},"url":{"type":"string"},"supported_currencies":{"type":"array","items":{"type":"string"}},"supported_locales":{"type":"array","items":{"type":"string"}},"logo_url":{"type":"string","nullable":true},"mailer_logo_url":{"type":"string","nullable":true}},"required":["id","metadata","name","default_currency","default_locale","mail_from_address","customer_support_email","new_order_notifications_email","preferred_send_consumer_transactional_emails","preferred_admin_locale","preferred_timezone","preferred_weight_unit","preferred_unit_system","created_at","updated_at","url","supported_currencies","supported_locales","logo_url","mailer_logo_url"],"x-typelizer":true},"TaxCategory":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"tax_code":{"type":"string","nullable":true},"description":{"type":"string","nullable":true},"is_default":{"type":"boolean"},"created_at":{"type":"string"},"updated_at":{"type":"string"}},"required":["id","name","tax_code","description","is_default","created_at","updated_at"],"x-typelizer":true},"Variant":{"type":"object","properties":{"id":{"type":"string"},"product_id":{"type":"string"},"sku":{"type":"string","nullable":true},"options_text":{"type":"string"},"track_inventory":{"type":"boolean"},"media_count":{"type":"number"},"thumbnail_url":{"type":"string","nullable":true},"purchasable":{"type":"boolean"},"in_stock":{"type":"boolean"},"backorderable":{"type":"boolean"},"weight":{"type":"number","nullable":true},"height":{"type":"number","nullable":true},"width":{"type":"number","nullable":true},"depth":{"type":"number","nullable":true},"price":{"$ref":"#/components/schemas/Price"},"original_price":{"allOf":[{"$ref":"#/components/schemas/Price"}],"nullable":true},"primary_media":{"$ref":"#/components/schemas/Media"},"media":{"type":"array","items":{"$ref":"#/components/schemas/Media"}},"option_values":{"type":"array","items":{"$ref":"#/components/schemas/OptionValue"}},"custom_fields":{"type":"array","items":{"$ref":"#/components/schemas/CustomField"}},"prior_price":{"allOf":[{"$ref":"#/components/schemas/PriceHistory"}],"nullable":true},"metadata":{"type":"object"},"position":{"type":"number"},"cost_price":{"type":"string","nullable":true},"cost_currency":{"type":"string","nullable":true},"barcode":{"type":"string","nullable":true},"weight_unit":{"type":"string","nullable":true},"dimensions_unit":{"type":"string","nullable":true},"deleted_at":{"type":"string","nullable":true},"created_at":{"type":"string"},"updated_at":{"type":"string"},"tax_category_id":{"type":"string","nullable":true},"available_stock":{"type":"number","nullable":true},"reserved_quantity":{"type":"number"},"total_on_hand":{"type":"number","nullable":true},"product_name":{"type":"string"},"prices":{"type":"array","items":{"$ref":"#/components/schemas/Price"}},"stock_items":{"type":"array","items":{"$ref":"#/components/schemas/StockItem"}}},"required":["id","product_id","sku","options_text","track_inventory","media_count","thumbnail_url","purchasable","in_stock","backorderable","weight","height","width","depth","price","original_price","option_values","metadata","position","cost_price","cost_currency","barcode","weight_unit","dimensions_unit","deleted_at","created_at","updated_at","tax_category_id","available_stock","reserved_quantity","total_on_hand","product_name"],"x-typelizer":true},"WebhookDelivery":{"type":"object","properties":{"id":{"type":"string"},"event_name":{"type":"string"},"event_id":{"type":"string","nullable":true},"response_code":{"type":"number","nullable":true},"execution_time":{"type":"number","nullable":true},"error_type":{"type":"string","nullable":true},"request_errors":{"type":"string","nullable":true},"response_body":{"type":"string","nullable":true},"success":{"type":"boolean","nullable":true},"payload":{"type":"object"},"created_at":{"type":"string"},"updated_at":{"type":"string"},"delivered_at":{"type":"string","nullable":true},"webhook_endpoint_id":{"type":"string"},"webhook_endpoint_url":{"type":"string"}},"required":["id","event_name","event_id","response_code","execution_time","error_type","request_errors","response_body","success","payload","created_at","updated_at","delivered_at","webhook_endpoint_id","webhook_endpoint_url"],"x-typelizer":true},"WebhookEndpoint":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string","nullable":true},"url":{"type":"string"},"active":{"type":"boolean"},"subscriptions":{"type":"array","items":{"type":"string"}},"disabled_reason":{"type":"string","nullable":true},"created_at":{"type":"string"},"updated_at":{"type":"string"},"disabled_at":{"type":"string","nullable":true},"secret_key":{"type":"string","nullable":true},"last_delivery_at":{"type":"string","nullable":true},"recent_delivery_count":{"type":"number"},"recent_failure_count":{"type":"number"},"total_delivery_count":{"type":"number"},"successful_delivery_count":{"type":"number"},"failed_delivery_count":{"type":"number"}},"required":["id","name","url","active","subscriptions","disabled_reason","created_at","updated_at","disabled_at","secret_key","last_delivery_at","recent_delivery_count","recent_failure_count","total_delivery_count","successful_delivery_count","failed_delivery_count"],"x-typelizer":true}}}}
\ No newline at end of file
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 8505285fd5..c83ada9f81 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -1,6 +1,8 @@
import { Command } from 'commander'
import pc from 'picocolors'
+import { registerApiCommand } from './commands/api.js'
import { registerApiKeyCommand } from './commands/api-key.js'
+import { registerAuthCommand } from './commands/auth.js'
import { registerBuildCommand } from './commands/build.js'
import { registerBundleCommand } from './commands/bundle.js'
import { registerConsoleCommand } from './commands/console.js'
@@ -33,6 +35,21 @@ const program = new Command()
// so flags like `ls -la` or `bin/rails routes -g foo` reach the inner command
// instead of being parsed as options of the spree subcommand.
.enablePositionalOptions()
+ // Must be set BEFORE registering subcommands — commander copies the exit
+ // callback to each subcommand at `.command()` creation time, so a later call
+ // would leave subcommands (e.g. `api endpoints --format`) on the default
+ // handler. Commander invokes this then calls process.exit with the error's
+ // code, so we exit directly: 0 for help/version, 2 for usage errors,
+ // matching the rest of the `spree api` surface. The message is already printed.
+ .exitOverride((err) => {
+ // Help (`spree api` with no subcommand, `--help`) and `--version` are
+ // successful exits, not errors. Everything else reaching here is a usage
+ // error → 2.
+ if (err.code.startsWith('commander.help') || err.code === 'commander.version') {
+ process.exit(0)
+ }
+ process.exit(2)
+ })
// Lifecycle / setup
registerInitCommand(program)
@@ -66,7 +83,9 @@ registerOpenCommand(program)
registerSeedCommand(program)
registerSampleDataCommand(program)
-program.exitOverride()
+// Admin API access (works against any Spree 5.5+ instance, not just local projects)
+registerApiCommand(program)
+registerAuthCommand(program)
async function main() {
try {
@@ -80,9 +99,15 @@ async function main() {
process.exit(0)
}
+ if (err instanceof Error && 'code' in err && String(err.code).startsWith('commander.')) {
+ process.exit(2)
+ }
+
+ // CredentialError carries no special code; it's a configuration problem (2).
+ const exitCode = err instanceof Error && err.constructor.name === 'CredentialError' ? 2 : 1
const message = err instanceof Error ? err.message : 'An unexpected error occurred.'
console.error(`\n${pc.red('Error:')} ${message}\n`)
- process.exit(1)
+ process.exit(exitCode)
}
}
diff --git a/packages/cli/tests/api-body.test.ts b/packages/cli/tests/api-body.test.ts
new file mode 100644
index 0000000000..430c4d0a28
--- /dev/null
+++ b/packages/cli/tests/api-body.test.ts
@@ -0,0 +1,42 @@
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { NO_BODY, readBody } from '../src/api/body'
+
+describe('readBody', () => {
+ const tempFiles: string[] = []
+
+ afterEach(() => {
+ for (const file of tempFiles) fs.rmSync(file, { force: true })
+ tempFiles.length = 0
+ })
+
+ it('returns the NO_BODY sentinel when no data given', async () => {
+ expect(await readBody(undefined)).toBe(NO_BODY)
+ })
+
+ it('preserves a literal null body (distinct from absence)', async () => {
+ expect(await readBody('null')).toBeNull()
+ })
+
+ it('parses inline JSON', async () => {
+ expect(await readBody('{"name":"Tee"}')).toEqual({ name: 'Tee' })
+ })
+
+ it('gives a clear error for a missing @file', async () => {
+ await expect(readBody('@/no/such/file.json')).rejects.toThrow(/Request body file not found/)
+ })
+
+ it('reads @file payloads', async () => {
+ const file = path.join(os.tmpdir(), `spree-cli-body-${process.pid}.json`)
+ tempFiles.push(file)
+ fs.writeFileSync(file, '{"amount":25}')
+
+ expect(await readBody(`@${file}`)).toEqual({ amount: 25 })
+ })
+
+ it('rejects invalid JSON with a clear error', async () => {
+ await expect(readBody('{nope')).rejects.toThrow(/not valid JSON/)
+ })
+})
diff --git a/packages/cli/tests/api-params.test.ts b/packages/cli/tests/api-params.test.ts
new file mode 100644
index 0000000000..844a118c05
--- /dev/null
+++ b/packages/cli/tests/api-params.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it } from 'vitest'
+import { buildParams, normalizePath } from '../src/api/params'
+
+describe('buildParams', () => {
+ it('wraps -q expressions into Ransack q[...] params', () => {
+ expect(buildParams({ query: ['status_eq=active', 'name_cont=shirt'] })).toEqual({
+ 'q[status_eq]': 'active',
+ 'q[name_cont]': 'shirt',
+ })
+ })
+
+ it('turns a repeated key into a []-suffixed array param so Rack keeps every value', () => {
+ expect(buildParams({ query: ['id_in=prod_a', 'id_in=prod_b'] })).toEqual({
+ 'q[id_in][]': ['prod_a', 'prod_b'],
+ })
+ })
+
+ it('passes pagination and shaping flags through', () => {
+ expect(
+ buildParams({
+ query: [],
+ sort: '-created_at',
+ page: '2',
+ limit: '50',
+ expand: 'variants',
+ fields: 'id,name',
+ }),
+ ).toEqual({
+ sort: '-created_at',
+ page: 2,
+ limit: 50,
+ expand: 'variants',
+ fields: 'id,name',
+ })
+ })
+
+ it('keeps = inside values', () => {
+ expect(buildParams({ query: ['name_cont=a=b'] })).toEqual({ 'q[name_cont]': 'a=b' })
+ })
+
+ it('rejects expressions without key=value shape', () => {
+ expect(() => buildParams({ query: ['status_eq'] })).toThrow(/Invalid -q expression/)
+ })
+
+ it('rejects non-numeric --page / --limit', () => {
+ expect(() => buildParams({ query: [], page: 'abc' })).toThrow(/Invalid --page/)
+ expect(() => buildParams({ query: [], limit: '0' })).toThrow(/Invalid --limit/)
+ })
+})
+
+describe('normalizePath', () => {
+ it('adds a leading slash', () => {
+ expect(normalizePath('products')).toBe('/products')
+ })
+
+ it('strips a pasted /api/v3/admin prefix', () => {
+ expect(normalizePath('/api/v3/admin/orders/ord_x')).toBe('/orders/ord_x')
+ })
+
+ it('leaves clean paths alone', () => {
+ expect(normalizePath('/orders/ord_x/refunds')).toBe('/orders/ord_x/refunds')
+ })
+})
diff --git a/packages/cli/tests/api-spec.test.ts b/packages/cli/tests/api-spec.test.ts
new file mode 100644
index 0000000000..7bd28eae41
--- /dev/null
+++ b/packages/cli/tests/api-spec.test.ts
@@ -0,0 +1,170 @@
+import { describe, expect, it } from 'vitest'
+import {
+ type AdminSpec,
+ getSchema,
+ listEndpoints,
+ loadBundledSpec,
+ requiredScope,
+ resolveRefs,
+} from '../src/api/spec'
+
+const fixture: AdminSpec = {
+ info: { title: 'Admin API', version: 'v3' },
+ paths: {
+ '/api/v3/admin/orders': {
+ get: {
+ summary: 'List orders',
+ description:
+ 'Returns orders.\n\n**Required scope:** `read_orders` (for API-key authentication).',
+ },
+ post: {
+ summary: 'Create order',
+ description: '**Required scope:** `write_orders` (for API-key authentication).',
+ requestBody: {
+ content: {
+ 'application/json': { schema: { $ref: '#/components/schemas/order_params' } },
+ },
+ },
+ },
+ },
+ '/api/v3/admin/orders/{id}': {
+ get: {
+ summary: 'Get order',
+ description: '**Required scope:** `read_orders` (for API-key authentication).',
+ },
+ },
+ '/api/v3/admin/exports': {
+ post: {
+ summary: 'Create export',
+ description:
+ '**Required scope:** the read scope of the exported resource — `read_products` for product exports, `read_customers` for customer exports, etc. (for API-key authentication).',
+ },
+ },
+ '/api/v3/admin/payment_methods/{id}': {
+ get: {
+ summary: 'Get payment method',
+ description: '**Required scope:** `read_settings` (for API-key authentication).',
+ },
+ },
+ '/api/v3/admin/payment_methods/types': {
+ get: {
+ summary: 'List payment method types',
+ description: '**Required scope:** `read_settings` (for API-key authentication).',
+ },
+ },
+ },
+ components: {
+ schemas: {
+ order_params: {
+ type: 'object',
+ properties: {
+ number: { type: 'string' },
+ nested: { $ref: '#/components/schemas/order_params' },
+ },
+ },
+ },
+ },
+}
+
+describe('requiredScope', () => {
+ it('extracts the scope token from the description', () => {
+ expect(requiredScope(fixture.paths['/api/v3/admin/orders'].get)).toBe('read_orders')
+ })
+
+ it('passes free-form scope notes through (exports)', () => {
+ expect(requiredScope(fixture.paths['/api/v3/admin/exports'].post)).toContain(
+ 'read scope of the exported resource',
+ )
+ })
+
+ it('returns a dash when no scope line exists', () => {
+ expect(requiredScope({ summary: 'x' })).toBe('—')
+ })
+})
+
+describe('listEndpoints', () => {
+ it('lists every operation with method, short path, and scope', () => {
+ const rows = listEndpoints(fixture)
+ expect(rows).toHaveLength(6)
+ expect(rows[0]).toEqual({
+ method: 'GET',
+ path: '/orders',
+ scope: 'read_orders',
+ summary: 'List orders',
+ })
+ })
+
+ it('filters by resource (first path segment)', () => {
+ const rows = listEndpoints(fixture, { resource: 'exports' })
+ expect(rows).toHaveLength(1)
+ expect(rows[0].path).toBe('/exports')
+ })
+
+ it('filters by search term across method, path, and summary', () => {
+ const rows = listEndpoints(fixture, { search: 'create order' })
+ expect(rows).toHaveLength(1)
+ expect(rows[0].method).toBe('POST')
+ })
+})
+
+describe('getSchema', () => {
+ it('matches METHOD /path and resolves $refs inline', () => {
+ const matches = getSchema(fixture, 'POST /orders')
+ expect(matches).toHaveLength(1)
+ const body = JSON.stringify(matches[0].requestBody)
+ expect(body).toContain('"number"')
+ })
+
+ it('keeps cyclic refs as raw pointers instead of recursing forever', () => {
+ const matches = getSchema(fixture, 'POST /orders')
+ expect(JSON.stringify(matches[0].requestBody)).toContain('#/components/schemas/order_params')
+ })
+
+ it('matches a concrete ID against {id} placeholders', () => {
+ const matches = getSchema(fixture, 'GET /orders/ord_x8k2J9aQ')
+ expect(matches).toHaveLength(1)
+ expect(matches[0].path).toBe('/orders/{id}')
+ })
+
+ it('returns all methods when no method is given', () => {
+ const matches = getSchema(fixture, '/orders')
+ expect(matches.map((m) => m.method).sort()).toEqual(['GET', 'POST'])
+ })
+
+ it('tolerates the /api/v3/admin prefix in the target', () => {
+ expect(getSchema(fixture, 'GET /api/v3/admin/orders')).toHaveLength(1)
+ })
+
+ it('prefers an exact literal path over a {id} template (router precedence)', () => {
+ const matches = getSchema(fixture, 'GET /payment_methods/types')
+ expect(matches).toHaveLength(1)
+ expect(matches[0].path).toBe('/payment_methods/types')
+ expect(matches[0].summary).toBe('List payment method types')
+ })
+})
+
+describe('resolveRefs', () => {
+ it('returns scalars untouched', () => {
+ expect(resolveRefs('x', fixture)).toBe('x')
+ })
+})
+
+describe('bundled snapshot', () => {
+ it('loads with a substantial operation inventory', () => {
+ const spec = loadBundledSpec()
+ const rows = listEndpoints(spec)
+ expect(rows.length).toBeGreaterThan(150)
+ })
+
+ it('answers a real schema lookup', () => {
+ const matches = getSchema(loadBundledSpec(), 'GET /products')
+ expect(matches.length).toBeGreaterThanOrEqual(1)
+ expect(matches[0].summary).toBeTruthy()
+ })
+
+ it('carries scope annotations for most operations', () => {
+ const rows = listEndpoints(loadBundledSpec())
+ const annotated = rows.filter((row) => row.scope !== '—')
+ expect(annotated.length / rows.length).toBeGreaterThan(0.8)
+ })
+})
diff --git a/packages/cli/tests/config.test.ts b/packages/cli/tests/config.test.ts
new file mode 100644
index 0000000000..7a18e0107b
--- /dev/null
+++ b/packages/cli/tests/config.test.ts
@@ -0,0 +1,228 @@
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { CredentialError, resolveCredentials, writeProjectCredentials } from '../src/config'
+
+describe('resolveCredentials', () => {
+ const tempDirs: string[] = []
+ const savedEnv: Record<string, string | undefined> = {
+ SPREE_BASE_URL: process.env.SPREE_BASE_URL,
+ SPREE_API_KEY: process.env.SPREE_API_KEY,
+ XDG_CONFIG_HOME: process.env.XDG_CONFIG_HOME,
+ }
+
+ function makeTempDir(): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'spree-cli-config-'))
+ tempDirs.push(dir)
+ return dir
+ }
+
+ /** Points the profile store at an isolated config home. */
+ function isolateConfigHome(): string {
+ const home = makeTempDir()
+ process.env.XDG_CONFIG_HOME = home
+ return home
+ }
+
+ function writeProfiles(home: string, config: unknown): void {
+ const dir = path.join(home, 'spree')
+ fs.mkdirSync(dir, { recursive: true })
+ fs.writeFileSync(path.join(dir, 'config.json'), JSON.stringify(config))
+ }
+
+ afterEach(() => {
+ for (const [key, value] of Object.entries(savedEnv)) {
+ if (value === undefined) delete process.env[key]
+ else process.env[key] = value
+ }
+ for (const dir of tempDirs) fs.rmSync(dir, { recursive: true, force: true })
+ tempDirs.length = 0
+ })
+
+ it('resolves from SPREE_BASE_URL + SPREE_API_KEY env vars', async () => {
+ isolateConfigHome()
+ process.env.SPREE_BASE_URL = 'https://env.example.com'
+ process.env.SPREE_API_KEY = 'sk_env_token_123'
+
+ const creds = await resolveCredentials({}, { cwd: makeTempDir(), allowMint: false })
+
+ expect(creds).toMatchObject({
+ baseUrl: 'https://env.example.com',
+ apiKey: 'sk_env_token_123',
+ source: 'env',
+ })
+ expect(creds.tokenPrefix).toBe('sk_env_token')
+ })
+
+ it('lets flags override env', async () => {
+ isolateConfigHome()
+ process.env.SPREE_BASE_URL = 'https://env.example.com'
+ process.env.SPREE_API_KEY = 'sk_env_token_123'
+
+ const creds = await resolveCredentials(
+ { baseUrl: 'https://flag.example.com', apiKey: 'sk_flag_token' },
+ { cwd: makeTempDir(), allowMint: false },
+ )
+
+ expect(creds).toMatchObject({
+ baseUrl: 'https://flag.example.com',
+ apiKey: 'sk_flag_token',
+ source: 'flags',
+ })
+ })
+
+ it('uses existing project credentials without minting', async () => {
+ isolateConfigHome()
+ const projectDir = makeTempDir()
+ fs.writeFileSync(path.join(projectDir, 'docker-compose.yml'), 'services:')
+ writeProjectCredentials(projectDir, {
+ baseUrl: 'http://localhost:3000',
+ token: 'sk_project_token',
+ scopes: ['read_all'],
+ mintedAt: '2026-06-12T00:00:00Z',
+ })
+
+ const creds = await resolveCredentials({}, { cwd: projectDir, allowMint: false })
+
+ expect(creds).toMatchObject({
+ baseUrl: 'http://localhost:3000',
+ apiKey: 'sk_project_token',
+ source: 'project',
+ scopes: ['read_all'],
+ })
+ })
+
+ it('an explicit --profile outranks env', async () => {
+ const home = isolateConfigHome()
+ writeProfiles(home, {
+ defaultProfile: 'prod',
+ profiles: { prod: { baseUrl: 'https://prod.example.com', token: 'sk_prod_token' } },
+ })
+ process.env.SPREE_API_KEY = 'sk_env_token'
+ process.env.SPREE_BASE_URL = 'https://env.example.com'
+
+ const creds = await resolveCredentials(
+ { profile: 'prod' },
+ { cwd: makeTempDir(), allowMint: false },
+ )
+
+ expect(creds).toMatchObject({
+ baseUrl: 'https://prod.example.com',
+ apiKey: 'sk_prod_token',
+ source: 'profile',
+ profileName: 'prod',
+ })
+ })
+
+ it('falls back to the default profile when nothing else resolves', async () => {
+ const home = isolateConfigHome()
+ writeProfiles(home, {
+ defaultProfile: 'staging',
+ profiles: { staging: { baseUrl: 'https://staging.example.com', token: 'sk_staging' } },
+ })
+
+ const creds = await resolveCredentials({}, { cwd: makeTempDir(), allowMint: false })
+
+ expect(creds).toMatchObject({ source: 'profile', profileName: 'staging' })
+ })
+
+ it('throws CredentialError for an unknown --profile', async () => {
+ isolateConfigHome()
+ await expect(
+ resolveCredentials({ profile: 'nope' }, { cwd: makeTempDir(), allowMint: false }),
+ ).rejects.toThrow(CredentialError)
+ })
+
+ // Security: SPREE_BASE_URL alone must never re-point a saved/minted key at an
+ // arbitrary host. The key anchors its layer; only an explicit flag re-points.
+ it('does NOT pair SPREE_BASE_URL with a profile key (no silent exfiltration)', async () => {
+ const home = isolateConfigHome()
+ writeProfiles(home, {
+ defaultProfile: 'prod',
+ profiles: { prod: { baseUrl: 'https://prod.example.com', token: 'sk_prod_secret' } },
+ })
+ process.env.SPREE_BASE_URL = 'https://attacker.example'
+
+ const creds = await resolveCredentials({}, { cwd: makeTempDir(), allowMint: false })
+
+ // The profile key stays paired with the profile host, not the env host.
+ expect(creds.baseUrl).toBe('https://prod.example.com')
+ expect(creds.apiKey).toBe('sk_prod_secret')
+ })
+
+ it('does NOT pair SPREE_BASE_URL with a project key', async () => {
+ isolateConfigHome()
+ const projectDir = makeTempDir()
+ fs.writeFileSync(path.join(projectDir, 'docker-compose.yml'), 'services:')
+ writeProjectCredentials(projectDir, {
+ baseUrl: 'http://localhost:3000',
+ token: 'sk_project_token',
+ scopes: ['read_all'],
+ mintedAt: '2026-06-12T00:00:00Z',
+ })
+ process.env.SPREE_BASE_URL = 'https://attacker.example'
+
+ const creds = await resolveCredentials({}, { cwd: projectDir, allowMint: false })
+
+ expect(creds.baseUrl).toBe('http://localhost:3000')
+ expect(creds.apiKey).toBe('sk_project_token')
+ })
+
+ it('does NOT auto-mint when an explicit --base-url targets a different host', async () => {
+ isolateConfigHome()
+ const projectDir = makeTempDir()
+ fs.writeFileSync(path.join(projectDir, 'docker-compose.yml'), 'services:')
+ // allowMint defaults true; the foreign --base-url must still suppress minting.
+ await expect(
+ resolveCredentials({ baseUrl: 'https://prod.example.com' }, { cwd: projectDir }),
+ ).rejects.toThrow(CredentialError)
+ expect(fs.existsSync(path.join(projectDir, '.spree', 'credentials.json'))).toBe(false)
+ })
+
+ it('an explicit --base-url re-points a flag --api-key (the sanctioned cross-source mix)', async () => {
+ isolateConfigHome()
+ const creds = await resolveCredentials(
+ { baseUrl: 'https://staging.example.com', apiKey: 'sk_flag' },
+ { cwd: makeTempDir(), allowMint: false },
+ )
+ expect(creds).toMatchObject({
+ baseUrl: 'https://staging.example.com',
+ apiKey: 'sk_flag',
+ source: 'flags',
+ })
+ })
+
+ it('backs up a corrupt config.json instead of resolving it as empty', async () => {
+ const home = isolateConfigHome()
+ const dir = path.join(home, 'spree')
+ fs.mkdirSync(dir, { recursive: true })
+ fs.writeFileSync(path.join(dir, 'config.json'), '{ not json')
+
+ // Reading must not throw, and must move the bad file aside.
+ await expect(
+ resolveCredentials({ profile: 'x' }, { cwd: makeTempDir(), allowMint: false }),
+ ).rejects.toThrow(/Unknown profile/)
+ expect(fs.existsSync(path.join(dir, 'config.json.bak'))).toBe(true)
+ })
+
+ it('throws CredentialError when nothing resolves', async () => {
+ isolateConfigHome()
+ await expect(resolveCredentials({}, { cwd: makeTempDir(), allowMint: false })).rejects.toThrow(
+ /No Admin API credentials found/,
+ )
+ })
+
+ it('writes project credentials with owner-only permissions', () => {
+ const projectDir = makeTempDir()
+ writeProjectCredentials(projectDir, {
+ baseUrl: 'http://localhost:3000',
+ token: 'sk_secret',
+ scopes: ['read_all'],
+ mintedAt: '2026-06-12T00:00:00Z',
+ })
+
+ const mode = fs.statSync(path.join(projectDir, '.spree', 'credentials.json')).mode & 0o777
+ expect(mode).toBe(0o600)
+ })
+})
diff --git a/packages/create-spree-app/.changeset/spree-credentials-gitignore.md b/packages/create-spree-app/.changeset/spree-credentials-gitignore.md
new file mode 100644
index 0000000000..2159fa4277
--- /dev/null
+++ b/packages/create-spree-app/.changeset/spree-credentials-gitignore.md
@@ -0,0 +1,5 @@
+---
+"create-spree-app": patch
+---
+
+Scaffolded `.gitignore` now excludes `.spree/` — the local Admin API credentials directory used by `spree api` / `spree auth`.
diff --git a/packages/create-spree-app/src/templates/gitignore.ts b/packages/create-spree-app/src/templates/gitignore.ts
index c58965aedc..e7684ae10a 100644
--- a/packages/create-spree-app/src/templates/gitignore.ts
+++ b/packages/create-spree-app/src/templates/gitignore.ts
@@ -3,5 +3,7 @@ export function gitignoreContent(): string {
.env
.env.local
.DS_Store
+# Local Admin API credentials minted by \`spree api\` / \`spree auth\`
+.spree/
`
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 5d4e7564a4..e47e51567f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -63,6 +63,9 @@ importers:
'@clack/prompts':
specifier: ^1.3.0
version: 1.3.0
+ '@spree/admin-sdk':
+ specifier: workspace:^
+ version: link:../admin-sdk
commander:
specifier: ^14.0.3
version: 14.0.3
@@ -94,6 +97,9 @@ importers:
vitest:
specifier: ^4.1.5
+ yaml:
+ specifier: ^2.8.4
+ version: 2.8.4
packages/create-spree-app:
dependencies: