· 1 min read
Screencast: Versionierung von REST APIs
Downloads in verschiedenen Formaten:
Resourcen:
terminal
[bash] rails g migration change_products_released_on rake db:migrate cp -R app/controllers/api/v1 app/controllers/api/v2 curl -H ‘Accept: application/vnd.example.v1’ http://localhost:3000/api/products [/bash]
routes.rb
[ruby] require ‘api_constraints’
Store::Application.routes.draw do namespace :api, defaults: {format: ‘json’} do scope module: :v1, constraints: ApiConstraints.new(version: 1) do resources :products end scope module: :v2, constraints: ApiConstraints.new(version: 2, default: true) do resources :products end end resources :products root to: ‘products#index’ end [/ruby]
lib/api_constraints.rb
[ruby] 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 [/ruby]
app/controllers/api/v1/products_controller.rb
[ruby] module Api module V1 class ProductsController < ApplicationController class Product < ::Product # Note: this does not take into consideration the create/update actions for changing released_on def as_json(options = {}) super.merge(released_on: released_at.to_date) end end respond_to :json
def index respond_with Product.all end
def show respond_with Product.find(params[:id]) end
def create respond_with Product.create(params[:product]) end
def update respond_with Product.update(params[:id], params[:product]) end
def destroy respond_with Product.destroy(params[:id]) end end end end [/ruby]