Tng Weather App API#

The original video is here youtube: Rails API Series: Our First API

rails new weather-app#

rails g model Location name:string
rails g model Recording location:references temp:integer status
rails db:migrate

seeds.rb sample data for testing#

l = Location.create(name: "Sydney")
l.recordings.create(temp:32, status: "cloudy")
l.recordings.create(temp:30, status: "rainy")
l.recordings.create(temp:28, status: "warm")
l.recordings.create(temp:22, status: "cloudy")

models/location.rb#

class Location < ApplicationRecord
  has_many :recordings
  end

> rails db:seed

rails/console#

Location.last.recordings.last

This confirms DB is setup

make routes for resources#

Rails.application.routes.draw do
# this seperates out the api
  namespace :api do
    namespace :v1 do
      resources :locations do
        resources :recordings  
      end
    end
  end

  resources :locations  # for browser to load html pages
end

rails routes # check what's been designed

Locations controller (API)#

app/controllers/api/v1/locations_controller.rb

class Api::V1::LocationController < ApplicationController
  before_action :set_location

  def show

  end

  private
  def set_location
    @location = Location.find(params[:id])  # what gets passed in
  end

end

make view for the API#

app/views/api/v1/locations/show.json.jbuilder

json.id @location.id
json.name @location.name
json.current do
  json.temp = @location.recordings.last.temp
  json.status = @location.recordings.last.status
end

Could do the same in the controller by creating a hash similar to these contents

def show
  render json: {
      id: @location.id,
      name: @location.name
  }
end

in the browser#

localhost:3000/api/v1/locations/1.json

Make own API controller#

app/controllers/api_controller.rb

class ApiController < ApplicationController
  before_action :set_default_format

  private
  def set_default_format
    request.format = :json  # over-ride what's on url
  end

Then change all controllers to inherit from this controller