API Versioning for Rails Routes

前端 未结 7 705
独厮守ぢ
独厮守ぢ 2020-12-04 04:12

I\'m trying to version my API like Stripe has. Below is given the latest API version is 2.

/api/users returns a 301 to /api/v2/users

<
7条回答
  •  既然无缘
    2020-12-04 04:59

    Implemented this today and found what I believe to be the 'right way' on RailsCasts - REST API Versioning. So simple. So maintainable. So effective.

    Add lib/api_constraints.rb (don't even have to change vnd.example.)

    class ApiConstraints
      def initialize(options)
        @version = options[:version]
        @default = options[:default]
      end
    
      def matches?(req)
        @default || req.headers['Accept'].include?("application/vnd.example.v#{@version}")
      end
    end
    

    Setup config/routes.rb like so

    require 'api_constraints'
    
    Rails.application.routes.draw do
    
      # Squads API
      namespace :api do
        # ApiConstaints is a lib file to allow default API versions,
        # this will help prevent having to change link names from /api/v1/squads to /api/squads, better maintainability
        scope module: :v1, constraints: ApiConstraints.new(version:1, default: true) do
          resources :squads do
            # my stuff was here
          end
        end
      end
    
      resources :squads
      root to: 'site#index'
    

    Edit your controller (ie /controllers/api/v1/squads_controller.rb)

    module Api
      module V1
        class SquadsController < BaseController
          # my stuff was here
        end
      end
    end
    

    Then you can change all links in your app from /api/v1/squads to /api/squads and you can EASILY implement new api versions without even having to change links

提交回复
热议问题