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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Fixed Country/States API
Damian Legawiec75fee5114f34
diff --git a/api/app/controllers/spree/api/v3/store/countries_controller.rb b/api/app/controllers/spree/api/v3/store/countries_controller.rbindex 70c5af6c1a..8e72f719c9 100644--- a/api/app/controllers/spree/api/v3/store/countries_controller.rb+++ b/api/app/controllers/spree/api/v3/store/countries_controller.rb@@ -2,19 +2,52 @@ module Spreemodule Apimodule V3module Store- class CountriesController < Store::ResourceController- protected+ class CountriesController < Store::BaseController+ # GET /api/v3/store/countries+ # Returns all countries available for checkout from store's checkout zone+ def index+ countries = checkout_countries.order(:name)- def scope- Spree::Country.accessible_by(current_ability, :show)+ render json: {+ data: countries.map { |country| serialize_country(country) }+ }end- def model_class- Spree::Country+ # GET /api/v3/store/countries/:id+ # Returns a single country with its states+ def show+ country = checkout_countries.find_by!(iso: params[:id].upcase)++ render json: serialize_country(country, include_states: true)end- def serializer_class- Spree.api.country_serializer+ private++ # Get countries from the store's checkout zone+ # Falls back to all countries if no checkout zone is configured+ def checkout_countries+ zone = current_store.checkout_zone+ return Spree::Country.all unless zone++ zone.country_list+ end++ def serialize_country(country, include_states: false)+ data = {+ iso: country.iso,+ iso3: country.iso3,+ name: country.name,+ states_required: country.states_required,+ zipcode_required: country.zipcode_required+ }++ if include_states+ data[:states] = country.states.order(:name).map do |state|+ { iso: state.abbr, name: state.name }+ end+ end++ dataendendenddiff --git a/api/app/serializers/spree/api/v3/country_serializer.rb b/api/app/serializers/spree/api/v3/country_serializer.rbindex dcd46e8a64..6de62b7d2e 100644--- a/api/app/serializers/spree/api/v3/country_serializer.rb+++ b/api/app/serializers/spree/api/v3/country_serializer.rb@@ -1,11 +1,15 @@module Spreemodule Apimodule V3- class CountrySerializer < BaseSerializer- typelize iso: :string, iso3: :string, iso_name: :string, name: :string,+ class CountrySerializer+ include Alba::Resource+ include Typelizer::DSL++ # ISO 3166-1 codes - iso is the identifier, no redundant id field+ typelize iso: :string, iso3: :string, name: :string,states_required: :boolean, zipcode_required: :boolean- attributes :iso, :iso3, :iso_name, :name, :states_required, :zipcode_required+ attributes :iso, :iso3, :name, :states_required, :zipcode_requiredmany :states,resource: Spree.api.state_serializer,diff --git a/api/app/serializers/spree/api/v3/state_serializer.rb b/api/app/serializers/spree/api/v3/state_serializer.rbindex fbeb00a224..1f6ac13777 100644--- a/api/app/serializers/spree/api/v3/state_serializer.rb+++ b/api/app/serializers/spree/api/v3/state_serializer.rb@@ -1,14 +1,19 @@module Spreemodule Apimodule V3- class StateSerializer < BaseSerializer- typelize name: :string, abbr: :string, country_id: :string+ class StateSerializer+ include Alba::Resource+ include Typelizer::DSL- attribute :country_id do |state|- state.country&.prefix_id+ # ISO 3166-2 subdivision code (without country prefix)+ # No id field - iso is the identifier+ typelize iso: :string, name: :string++ attribute :iso do |state|+ state.abbrend- attributes :name, :abbr+ attributes :nameendendenddiff --git a/api/spec/controllers/spree/api/v3/store/countries_controller_spec.rb b/api/spec/controllers/spree/api/v3/store/countries_controller_spec.rbindex 1b55e79147..2c185f631e 100644--- a/api/spec/controllers/spree/api/v3/store/countries_controller_spec.rb+++ b/api/spec/controllers/spree/api/v3/store/countries_controller_spec.rb@@ -9,7 +9,7 @@ RSpec.describe Spree::Api::V3::Store::CountriesController, type: :controller dolet!(:country2) { create(:country) }before do- request.headers['X-Spree-Api-Key'] = api_key.token+ request.headers['x-spree-api-key'] = api_key.tokenenddescribe 'GET #index' do@@ -25,17 +25,11 @@ RSpec.describe Spree::Api::V3::Store::CountriesController, type: :controller doget :indexcountry_data = json_response['data'].first- expect(country_data).to include('id', 'name', 'iso')- end-- it 'returns pagination metadata' do- get :index-- expect(json_response['meta']).to include('page', 'count', 'pages')+ expect(country_data).to include('iso', 'iso3', 'name', 'states_required', 'zipcode_required')endcontext 'without API key' do- before { request.headers['X-Spree-Api-Key'] = nil }+ before { request.headers['x-spree-api-key'] = nil }it 'returns unauthorized' doget :index@@ -48,37 +42,32 @@ RSpec.describe Spree::Api::V3::Store::CountriesController, type: :controller doenddescribe 'GET #show' do- it 'returns the country by id' do- get :show, params: { id: country.id }+ it 'returns the country by iso code' do+ get :show, params: { id: country.iso }expect(response).to have_http_status(:ok)- expect(json_response['id']).to eq(country.id)- expect(json_response['name']).to eq(country.name)expect(json_response['iso']).to eq(country.iso)+ expect(json_response['name']).to eq(country.name)end- it 'includes states when available' do+ it 'includes states' dostate = create(:state, country: country)- get :show, params: { id: country.id }+ get :show, params: { id: country.iso }expect(response).to have_http_status(:ok)+ expect(json_response['states']).to be_present+ expect(json_response['states'].first['iso']).to eq(state.abbr)+ expect(json_response['states'].first['name']).to eq(state.name)endcontext 'error handling' doit 'returns not found for non-existent country' do- get :show, params: { id: 0 }+ get :show, params: { id: 'XX' }expect(response).to have_http_status(:not_found)expect(json_response['error']['code']).to eq('record_not_found')expect(json_response['error']['message']).to be_presentend-- it 'returns not found for invalid id' do- get :show, params: { id: 'invalid' }-- expect(response).to have_http_status(:not_found)- expect(json_response['error']['code']).to eq('record_not_found')- endendendenddiff --git a/api/spec/integration/api/v2/platform/countries_spec.rb b/api/spec/integration/api/v2/platform/countries_spec.rbdeleted file mode 100644index f412a4b999..0000000000--- a/api/spec/integration/api/v2/platform/countries_spec.rb+++ /dev/null@@ -1,34 +0,0 @@-require 'swagger_helper'--describe 'Countries API', swagger: true do- include_context 'Platform API v2'-- path '/api/v2/platform/countries' do- get 'Returns a list of Countries' do- tags 'Countries'- security [ bearer_auth: [] ]- operationId 'countries-list'- description 'Returns a list of Countries'- before { create_list(:country, 2) }-- it_behaves_like 'records returned'- it_behaves_like 'authentication failed'- end- end-- path '/api/v2/platform/countries/{id}' do- let(:id) { create(:country).id }-- get 'Returns a Country' do- tags 'Countries'- security [ bearer_auth: [] ]- operationId 'show-country'- description 'Returns a Country'- parameter name: :id, in: :path, type: :string-- it_behaves_like 'record found'- it_behaves_like 'record not found'- it_behaves_like 'authentication failed'- end- end-enddiff --git a/api/spec/integration/api/v2/platform/states_spec.rb b/api/spec/integration/api/v2/platform/states_spec.rbdeleted file mode 100644index a1a28c6ff4..0000000000--- a/api/spec/integration/api/v2/platform/states_spec.rb+++ /dev/null@@ -1,38 +0,0 @@-require 'swagger_helper'--describe 'States API', swagger: true do- include_context 'Platform API v2'-- path '/api/v2/platform/states' do- get 'Returns a list of States' do- tags 'States'- security [ bearer_auth: [] ]- operationId 'states-list'- description 'Returns a list of States'- before { create_list(:state, 2) }-- include_context 'jsonapi pagination'- json_api_include_parameter('country')- json_api_filter_parameter([{ name: 'filter[country_id_eq]', example: '4' }])-- it_behaves_like 'records returned'- it_behaves_like 'authentication failed'- end- end-- path '/api/v2/platform/states/{id}' do- let(:id) { create(:state).id }-- get 'Returns a State' do- tags 'States'- security [ bearer_auth: [] ]- operationId 'show-state'- description 'Returns a State'- parameter name: :id, in: :path, type: :string-- it_behaves_like 'record found'- it_behaves_like 'record not found'- it_behaves_like 'authentication failed'- end- end-enddiff --git a/api/spec/integration/spree/api/v3/store/countries_spec.rb b/api/spec/integration/spree/api/v3/store/countries_spec.rbnew file mode 100644index 0000000000..2933beb2d7--- /dev/null+++ b/api/spec/integration/spree/api/v3/store/countries_spec.rb@@ -0,0 +1,122 @@+# frozen_string_literal: true++require 'swagger_helper'++RSpec.describe 'Countries API', type: :request, swagger_doc: 'api-reference/store.yaml' do+ include_context 'API v3 Store'++ let!(:usa) { Spree::Country.find_by(iso: 'US') || create(:country, iso: 'US', name: 'United States', states_required: true) }+ let!(:california) { Spree::State.find_by(abbr: 'CA', country: usa) || create(:state, country: usa, name: 'California', abbr: 'CA') }+ let!(:new_york) { Spree::State.find_by(abbr: 'NY', country: usa) || create(:state, country: usa, name: 'New York', abbr: 'NY') }+ let!(:germany) { Spree::Country.find_by(iso: 'DE') || create(:country, iso: 'DE', name: 'Germany', states_required: false) }++ path '/api/v3/store/countries' do+ get 'List checkout countries' do+ tags 'Countries'+ produces 'application/json'+ security [api_key: []]+ description 'Returns countries available for checkout from the store checkout zone'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true++ response '200', 'countries found' do+ let(:'x-spree-api-key') { api_key.token }++ schema type: :object,+ properties: {+ data: {+ type: :array,+ items: {+ type: :object,+ properties: {+ iso: { type: :string, description: 'ISO 3166-1 alpha-2 code' },+ iso3: { type: :string, description: 'ISO 3166-1 alpha-3 code' },+ name: { type: :string },+ states_required: { type: :boolean },+ zipcode_required: { type: :boolean }+ },+ required: %w[iso iso3 name states_required zipcode_required]+ }+ }+ },+ required: ['data']++ run_test! do |response|+ data = JSON.parse(response.body)+ expect(data['data']).to be_an(Array)+ # Find USA in response+ us_country = data['data'].find { |c| c['iso'] == 'US' }+ expect(us_country).to be_present+ expect(us_country['name']).to be_present+ # States should NOT be included in index+ expect(us_country).not_to have_key('states')+ end+ end++ response '401', 'unauthorized' do+ let(:'x-spree-api-key') { 'invalid' }++ schema '$ref' => '#/components/schemas/ErrorResponse'++ run_test!+ end+ end+ end++ path '/api/v3/store/countries/{iso}' do+ get 'Get a country with states' do+ tags 'Countries'+ produces 'application/json'+ security [api_key: []]+ description 'Returns a single country by ISO code with its states'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :iso, in: :path, type: :string, required: true,+ description: 'Country ISO 3166-1 alpha-2 code (e.g., "US", "DE", "CA")'++ response '200', 'country found' do+ let(:'x-spree-api-key') { api_key.token }+ let(:iso) { 'US' }++ schema type: :object,+ properties: {+ iso: { type: :string, description: 'ISO 3166-1 alpha-2 code' },+ iso3: { type: :string, description: 'ISO 3166-1 alpha-3 code' },+ name: { type: :string },+ states_required: { type: :boolean },+ zipcode_required: { type: :boolean },+ states: {+ type: :array,+ items: {+ type: :object,+ properties: {+ iso: { type: :string, description: 'ISO 3166-2 subdivision code (without country prefix)' },+ name: { type: :string }+ },+ required: %w[iso name]+ }+ }+ },+ required: %w[iso iso3 name states_required zipcode_required states]++ run_test! do |response|+ data = JSON.parse(response.body)+ expect(data['iso']).to eq('US')+ expect(data['states']).to be_an(Array)+ # Check that states have the expected structure+ state_isos = data['states'].map { |s| s['iso'] }+ expect(state_isos).to include('CA', 'NY')+ end+ end++ response '404', 'country not found' do+ let(:'x-spree-api-key') { api_key.token }+ let(:iso) { 'XX' }++ schema '$ref' => '#/components/schemas/ErrorResponse'++ run_test!+ end+ end+ end+enddiff --git a/core/app/models/spree/country.rb b/core/app/models/spree/country.rbindex 2c66019c36..f5d7941479 100644--- a/core/app/models/spree/country.rb+++ b/core/app/models/spree/country.rb@@ -1,7 +1,5 @@module Spreeclass Country < Spree.base_class- has_prefix_id :ctry # Spree-specific: country-has_many :addresses, dependent: :restrict_with_errorhas_many :states,-> { order name: :asc },diff --git a/core/app/models/spree/state.rb b/core/app/models/spree/state.rbindex 62174fd7e8..979645fbfd 100644--- a/core/app/models/spree/state.rb+++ b/core/app/models/spree/state.rb@@ -1,7 +1,5 @@module Spreeclass State < Spree.base_class- has_prefix_id :state # Spree-specific: state/province-belongs_to :country, class_name: 'Spree::Country'has_many :addresses, dependent: :restrict_with_errordiff --git a/sdk/src/types/generated/StoreCountry.ts b/sdk/src/types/generated/StoreCountry.tsindex ef17043cc5..5a7d963b1c 100644--- a/sdk/src/types/generated/StoreCountry.ts+++ b/sdk/src/types/generated/StoreCountry.ts@@ -1,13 +1,11 @@-// Typelizer digest b88be993a45c6f05cf6a7c8b296a0b29+// Typelizer digest 9cec9b196b3857ffdab3e40ffd0ad55b//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {StoreState} from '@/types'type StoreCountry = {- id: string;iso: string;iso3: string;- iso_name: string;name: string;states_required: boolean;zipcode_required: boolean;diff --git a/sdk/src/types/generated/StoreState.ts b/sdk/src/types/generated/StoreState.tsindex 220d13d9e7..89a260616d 100644--- a/sdk/src/types/generated/StoreState.ts+++ b/sdk/src/types/generated/StoreState.ts@@ -1,12 +1,10 @@-// Typelizer digest 246896ce6b43b425b06dae6c29915075+// Typelizer digest 29bade6d72448ee72050b9751ecebf7a//// DO NOT MODIFY: This file was automatically generated by Typelizer.type StoreState = {- id: string;- country_id: string;+ iso: string;name: string;- abbr: string;}export default StoreState;