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

REST APIs on Rails

REST APIs on Rails

Lucas André de Alencar

September 15, 2015
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. LongTrains::Application.routes.draw do api_version(:module => "V1", :path => {:value => "v1"})

    do resources :trains end end URL api.longtrains.com/v1/trains
  4. LongTrains::Application.routes.draw do api_version(:module => "V1", :parameter => {:name => "version",

    :value => "1"}) do resources :trains end end Request Params api.longtrains.com/trains?version=1
  5. LongTrains::Application.routes.draw do api_version(:module => "V1", :header => {:name => "Accept",

    :value => "application/json; version=1"}) do resources :trains end end HTTP Header Accept: application/json; version=1
  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
  8. TDD