Last active
August 29, 2015 14:01
-
-
Save CITguy/20ce9fed8582ff77d1d9 to your computer and use it in GitHub Desktop.
Using Rails 4.1 Action Pack variants with Vendor MIME Type for simple API versioning
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/routes.rb | |
Rails.application.routes.draw do | |
# use json if format not defined in url | |
scope(format: :json) do | |
get :hello, controller: :sandbox | |
end | |
end | |
# config/initializers/mime_types.rb | |
# Define a custom Vendor MIME type | |
Mime::Type.register "application/sandbox-v1+json", :v1json | |
# app/controllers/sandbox_controller.rb | |
class SandboxController < ApplicationController | |
def hello | |
respond_to do |format| | |
format.json # hello.jbuilder | |
format.v1json do | |
request.variant = :v1 # hello+v1.jbuilder | |
end | |
end | |
end | |
end | |
# app/views/sandbox/hello.jbuilder | |
json.hello "from default json" | |
# app/views/sandbox/hello+v1.jbuilder | |
json.hello "from v1 json variant" | |
# GET [Accept:'application/json', Content-Type:"application/json"] /sandbox/hello | |
# { "hello":"from default json" } | |
# GET [Accept:'application/sandbox-v1+json', Content-Type:"application/sandbox-v1+json"] /sandbox/hello | |
# { "hello":"from v1 json variant" } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment