bploetz / versionist

A plugin for versioning Rails based RESTful APIs.
MIT License
972 stars 51 forks source link

Multiple APIs in the same App #78

Closed Rio517 closed 8 years ago

Rio517 commented 8 years ago

Is it possible to support multiple APIs in the same rails-api app? For example, /public-api/v1/ and /api/v1/, each with their own default versions. Based on looking at Versionist.configuration, it looks like there is no easy way to support this.

Thanks for a great gem!

bploetz commented 8 years ago

Sure, just wrap the api_version in a namespace.

app/controllers/public/v1/foos_controller.rb:

class Public::V1::FoosController < ApplicationController
  def index
    render json: {"version"=>"public v1"} and return
  end
end

app/controllers/private/v1/foos_controller.rb

class Private::V1::FoosController < ApplicationController
  def index
    render json: {"version"=>"private v1"} and return
  end
end

config/routes.rb

Rails.application.routes.draw do
  namespace :public do
    api_version(:module => "V1", :path => {:value => "v1"}) do
      resources :foos
    end
  end

  namespace :private do
    api_version(:module => "V1", :path => {:value => "v1"}) do
      resources :foos
    end
  end
end

In action:

> curl http://localhost:3000/public/v1/foos
{"version":"public v1"}

> curl http://localhost:3000/private/v1/foos
{"version":"private v1"}
Rio517 commented 8 years ago

Ah, works prefectly. I had the parent module in the :module option, and was getting the error about not having two defaults. Thanks for the help.

Previously bad code:

namespace :api do
    api_version(module: "Api::V1", path: {value: "v1"}, default: true) do
      resources :whatever, only: :create
    end
  end

  namespace :public_api do
    api_version(module: "PublicApi::V1", path: {value: "v1"}, default: true) do
      resources :typeform, only: :create
    end
  end
bploetz commented 8 years ago

👍