Skip to content

Instantly share code, notes, and snippets.

@vikram7
Last active December 26, 2015 19:40
Show Gist options
  • Save vikram7/70d42631bda2962adc58 to your computer and use it in GitHub Desktop.
Save vikram7/70d42631bda2962adc58 to your computer and use it in GitHub Desktop.
Rails API Clinic - Dad Jokes API

Gem Install the Rails API

gem install rails-api

Generate the Rails API

rails api new jokes --database=postgresql -T

Commit our app

git init
git add -A && git commit -m 'Initial commit'

Add Model

class Joke < ActiveRecord::Base
  validates :title, presence: true
  validates :selftext, presence: true
  validates :author, presence: true
  validates :score, presence: true
  validates :num_comments, presence: true
end

Add Migration

rails g migration create_jokes

Add columns to migration

class CreateJokes < ActiveRecord::Migration
  def change
    create_table :jokes do |t|
      t.string :title, null: false
      t.text :selftext, null: false
      t.string :author, null: false
      t.integer :score, null: false
      t.integer :num_comments, null: false

      t.timestamps
    end
  end
end

Write a seeder

reddit = Snooby::Client.new
jokes = reddit.subreddit('dadjokes').posts

jokes.each do |joke|
  j = Joke.new
  j.username = joke.author
  j.title = joke.title
  j.body = joke.selftext
  j.score = joke.score
  j.num_comments = joke.num_comments
  j.save!
  puts "Created Dad Joke with title #{j.title} by #{j.author}"
end

Write your routes file

Rails.application.routes.draw do
  namespace :api do
    namespace :v1 do
      resources :jokes, only: [:index]
    end
  end
end

Add controller

class Api::V1::JokesController < ApplicationController
  def index
    @jokes = Joke.All

    render json: @jokes
  end
end

Navigate to API Page

Talk through it

Go back to API Standardization slide

Remember this? Show serialized API we want

Explain serializers

Adapter Pattern

Add Serializers to your gemfile

gem 'active_model_serializers', '0.8.3'

Add serializer folder

# app/serializers/joke_serializer.rb

class DadjokeSerializer < ActiveModel::Serializer
  attributes :id, :title, :selftext, :author, :score, :num_comments
end

Reboot server because we added Serializers

Now let's customize our serializer

Questions

  1. Why would we put something like is_funny in our Serializer rather than our Model?

Ok, let's add a route to our API that generates a random joke from our database

We update our config/routes.rb file:

Rails.application.routes.draw do
  namespace :api do
    namespace :v1 do
      resources :jokes, only: [:index]
      get "/random", to: "jokes#show"
    end
  end
end

Navigate to random joke

Show how AR Serializers take care of this for us

Comment on how you can use httparty to hit our API

Say you wanted to make that Lorem Ipsum generator of dadjokes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment