Upgrade to Pro — share decks privately, control downloads, hide ads and more …

REST APIs on Rails (v2)

REST APIs on Rails (v2)

Tweet

More Decks by Lucas André de Alencar

Other Decks in Programming

Transcript

  1. # instead of class ApplicationController < ActionController::Base end # do

    class ApplicationController < ActionController::API include ActionController::HttpAuthentication::Token::ControllerMethods include ActionController::MimeResponds include AbstractController::Translation # Your beautiful code goes here! end
  2. $ rails new long-trains --api ... $ rails g scaffold

    train type:string wagons:integer invoke active_record create db/migrate/20150907193647_create_trains.rb create app/models/train.rb invoke test_unit create test/models/train_test.rb create test/fixtures/trains.yml invoke resource_route route resources :trains create app/serializers/train_serializer.rb invoke scaffold_controller create app/controllers/trains_controller.rb invoke test_unit create test/controllers/trains_controller_test.rb
  3. Too much copying / pasting between versions No versioning included

    No documentation system included Disadvantages
  4. LongTrains::Application.routes.draw do params = {name: "version", value: "1"} api_version(module: "V1",

    parameter: params) do resources :trains end end Request Params api.longtrains.com/trains?version=1 config/routes.rb
  5. LongTrains::Application.routes.draw do params = {name: "Accept", value: "application/json; version=1"} api_version(module:

    "V1", header: params) do resources :trains end end HTTP Header Accept: application/json; version=1 config/routes.rb
  6. class PostSerializer < ActiveModel::Serializer attributes :title, :body has_many :comments end

    class CommentSerializer < ActiveModel::Serializer attributes :name, :body belongs_to :post end class PostPreviewSerializer < ActiveModel::Serializer attributes :title, :preview end
  7. class PostsController < ApplicationController def show @post = Post.find(params[:id]) render

    json: @post end def index @posts = Post.all render json: @posts, each_serializer: PostPreviewSerializer end end