In a Rails API that serves a mobile app, how do you lay out Api::V1 and add V2 without breaking clients still on old app versions?
answer
- nested namespace blocks in routes
- app/controllers/api/v1 maps to Api::V1
- a base controller per version
- V2 beside V1, not on top
- acronym API renames the module
basics
~20 sNest namespace :api and namespace :v1 in config/routes.rb so controllers live in app/controllers/api/v1 as Api::V1::*. Add V2 as a sibling namespace with its own controllers and JSON views, and retire V1 only when old app builds stop calling it.
solid answer
~40 sIn `config/routes.rb`, `namespace :api do namespace :v1 do resources :workouts end end` maps `/api/v1/workouts` to `Api::V1::WorkoutsController`, which Zeitwerk expects in `app/controllers/api/v1/workouts_controller.rb`; the path helpers become `api_v1_workouts_path`. Give each version a base controller, such as `Api::V1::BaseController < ApplicationController`, for its auth, `rescue_from` and error shape. When the contract changes, add `namespace :v2` beside V1 with its own controllers and views, sharing models and service objects but not response code; let V2 controllers inherit V1 ones only where behaviour is identical. Mobile builds cannot be force-updated, so V1 stays until request logs show its traffic gone. If you add `inflect.acronym "API"`, both Zeitwerk and the router expect `API::V1`, so file contents must follow.
code
ruby · 10 lines# config/routes.rb
namespace :api, defaults: { format: :json } do
namespace :v1 do
resources :workouts, only: %i[index show create]
end
namespace :v2 do
resources :workouts, only: %i[index show create]
end
endgo deeper
Know how namespace :api and :v1 map URLs to Api::V1 controllers in app/controllers/api/v1.
Explain Zeitwerk's directory-to-module mapping, the path-helper prefix and why each version gets its own base controller.
Plan V2 beside V1, decide where versions share code, and set a retirement rule driven by real mobile-build traffic.
Set the organisation's API compatibility policy: how long versions live, how clients are told to upgrade, and whether path or header versioning fits.
## Why mobile clients force versioning A browser app is redeployed with the server, so its JavaScript and the API change together. A **native mobile app** is not: users keep old builds for months, and each build has the JSON contract it was compiled against baked in. Any breaking change to a payload (a renamed key, a removed field, a different error shape) must therefore ship as a new version while the old one keeps answering. In Rails the conventional way is **path versioning** with nested route namespaces. ## The routes and the files ```ruby # config/routes.rb namespace :api, defaults: { format: :json } do namespace :v1 do resources :workouts, only: %i[index show create update destroy] resource :profile, only: %i[show update] end end ``` `namespace` sets three things at once: the URL prefix (`/api/v1`), the controller module (`api/v1`) and the route-helper prefix (`api_v1_`). The pieces line up like this: | Piece | Value | |---|---| | URL | `GET /api/v1/workouts` | | Controller | `Api::V1::WorkoutsController#index` | | File | `app/controllers/api/v1/workouts_controller.rb` | | Path helper | `api_v1_workouts_path` | | Jbuilder view (if used) | `app/views/api/v1/workouts/index.json.jbuilder` | **Zeitwerk**, Rails' autoloader, treats directories under `app/controllers` as namespaces, so `api/v1/` becomes the modules `Api` and `V1` without any file defining them. It camelizes names with Active Support's inflector, so if `config/initializers/inflections.rb` declares `inflect.acronym "API"`, the directory becomes `API` instead, and the router's `api/v1/workouts` resolves to `API::V1::WorkoutsController` too. Either spelling works; mixing them does not. ## A base controller per version ```ruby module Api module V1 class BaseController < ApplicationController before_action :authenticate_device rescue_from ActiveRecord::RecordNotFound, with: :not_found private def authenticate_device # look up the device token, head :unauthorized when it is missing end def not_found render json: { error: "not_found" }, status: :not_found end end end end ``` Each version's controllers inherit its base. That gives one place for the version's authentication rule, its `rescue_from` handlers and its error body, so V2 can change any of them without touching V1. ## Adding V2 1. Add `namespace :v2` next to `namespace :v1` in the routes. 2. Create `app/controllers/api/v2/` with its own base controller. 3. Copy only the controllers whose contract changes; for unchanged endpoints, either route V2 paths to the V1 controller or subclass it (`class Api::V2::ProfilesController < Api::V1::ProfilesController`). 4. Give V2 its own response shaping (Jbuilder views under `app/views/api/v2/` or a V2 serializer). 5. Keep models, validations and service objects shared; versions differ in the **contract**, not in business rules. Subclassing V1 controllers saves code but couples the versions: a later fix in V1 silently changes V2. Teams usually subclass only while behaviour is truly identical and copy once it diverges. ## Retiring V1 - Watch request logs or metrics per path prefix to see which app builds still call `/api/v1`. - Have the mobile app send its build number, so the API can answer an outdated build with a clear "please update" error instead of malformed data. - Remove the V1 namespace, controllers and views together once traffic is gone, and run `bin/rails routes` to confirm nothing points at deleted controllers. ## Header versioning in Rails Some teams keep a single `/api/workouts` URL and pick the version from a header, using a **route constraint**: an object whose `matches?(request)` checks the `Accept` header, applied with `scope module: :v2, constraints: ApiVersion.new(2)`. It keeps URLs stable but makes versions invisible in logs, curl commands and caches unless you add them back. Path namespaces remain the more common Rails choice because routes, files and modules all show the version. ## Testing versions side by side Keep tests in the same shape as the code, under `test/controllers/api/v1/` and `test/controllers/api/v2/`, and use the version's path helper in each: `get api_v1_workouts_path, as: :json` and `get api_v2_workouts_path, as: :json`. When V2 is added, the V1 tests must still pass unchanged; a V1 test that has to be edited is the earliest warning that a supposedly V2-only change leaked into the old contract.
- Should Api::V2 controllers inherit from their Api::V1 counterparts?Only while the behaviour is genuinely identical. Inheritance avoids duplication, but any later change to the V1 class leaks into V2, and removing V1 then means rewriting V2. Many teams inherit at first and copy the controller once the contracts diverge, keeping shared logic in models or service objects instead.
- What does defaults: { format: :json } on namespace :api buy you?It sets `params[:format]` to json for every route inside the namespace when the URL has no extension, so `request.format` is JSON even if a client sends a vague `Accept` header. Error pages in development and any format-dependent code then pick the JSON branch.
- Rails needs a gem before nested namespace :v1 routes work.
- Api::V1 modules must be defined in app/controllers/api.rb by hand.
- Breaking changes can ship in V1 because clients update automatically.
- Versions should have separate models copied per namespace.
- Adding inflect.acronym "API" leaves Api::V1 constant names unchanged.