0
0
Ruby on Railsframework~5 mins

API versioning in Ruby on Rails

Choose your learning style9 modes available
Introduction

API versioning helps keep your app working smoothly when you add new features or change old ones. It lets different users use different versions without breaking anything.

You want to add new features to your API without stopping old apps from working.
You need to fix bugs or improve your API but don't want to break existing users.
You want to support multiple clients that expect different API behaviors.
You plan to change how your API works but want to keep old versions available.
You want to organize your API code clearly by versions.
Syntax
Ruby on Rails
namespace :api do
  namespace :v1 do
    resources :posts
  end

  namespace :v2 do
    resources :posts
  end
end

Use namespace to group routes by version.

Each version can have its own controllers and logic.

Examples
This defines a version 1 API route for listing users.
Ruby on Rails
namespace :api do
  namespace :v1 do
    get 'users', to: 'users#index'
  end
end
This defines a version 2 API route for listing users, which can behave differently from v1.
Ruby on Rails
namespace :api do
  namespace :v2 do
    get 'users', to: 'users#index'
  end
end
Controller for API version 1 with a simple JSON response.
Ruby on Rails
module Api
  module V1
    class UsersController < ApplicationController
      def index
        render json: { message: 'Hello from v1' }
      end
    end
  end
end
Controller for API version 2 with updated response.
Ruby on Rails
module Api
  module V2
    class UsersController < ApplicationController
      def index
        render json: { message: 'Hello from v2 with new data' }
      end
    end
  end
end
Sample Program

This example shows two API versions with the same route /api/v1/greet and /api/v2/greet. Each version returns a different message in JSON format.

Ruby on Rails
Rails.application.routes.draw do
  namespace :api do
    namespace :v1 do
      get 'greet', to: 'greetings#show'
    end
    namespace :v2 do
      get 'greet', to: 'greetings#show'
    end
  end
end

module Api
  module V1
    class GreetingsController < ApplicationController
      def show
        render json: { message: 'Hello from API v1' }
      end
    end
  end
end

module Api
  module V2
    class GreetingsController < ApplicationController
      def show
        render json: { message: 'Hello from API v2 with extra info' }
      end
    end
  end
end
OutputSuccess
Important Notes

Keep your version folders and controllers organized to avoid confusion.

Use semantic versioning if you want to be more precise (like v1.0, v1.1).

Remember to update your API documentation for each version.

Summary

API versioning helps you update your API without breaking old users.

Use namespaces in Rails routes to separate versions.

Each version can have its own controllers and responses.