Grape api versioning with rails

Ranjan Bajracharya
2 min readJan 31, 2021

Initially set up grape-api in ruby on rails. Follow up here for grape configuration.

Create a folder structure as below

  • api.rb is the file under subdirectory that matches the name of the Ruby module and a file name that matches the name of the class.
  • base_api.rb is the file parent class
  • v1/api.rb is the file inherited from base_api.rb
  • v2/api.rb is the file inherited from base_api.rb
// api.rb
module VersioningGrape
class API < ::Grape::API
mount V1::API
mount V2::API
end
end
//base_api.rb
module VersioningGrape
class BaseAPI < ::Grape::API
resource :test do
desc 'testing api.'
get 'test' do
{status: "ok"}
end
end
end
end
//versioning_grape/v1/api.rb
module VersioningGrape
module V1
class API < ::Grape::API
version "v1", using: :path, vendor: 'versioning-grape'
format :json
mount BaseAPI

resource :test_v1 do
desc 'test api v1'
get do
{status: "ok", version: "v1"}
end
end
add_swagger_documentation
end
end
end
//versioning_grape/v2/api.rb
module VersioningGrape
module V2
class API < ::Grape::API
version ['v2','v1'], using: :path, vendor: 'versioning-grape', cascade: true
format :json
mount BaseAPI

resource :test_v2 do
desc 'test api v2'
get do
{status: "ok", version: "v2"}
end
end
add_swagger_documentation
end
end
end

Testing for api:- Add gem grape-swagger and grape-swagger-rails

visit http://localhost:3000/swagger#/

api-doc for v1
api-doc for v2

References

https://til.codes/using-helper-methods-and-helper-modules-in-rails-grape-to-keep-the-code-dry/
https://www.monterail.com/blog/2014/introduction-to-building-apis-with-grape

http://hrcode11.blogspot.com/2015/04/rails-grape-api-versioning.html

--

--

Ranjan Bajracharya

MSP 2017. Graduation in computer science and information technology. Studying MBA.