-
Notifications
You must be signed in to change notification settings - Fork 0
21 API NotesController
Let's add a new controller just for the api, and since we want this to have a similar RESTful structure as the rest of our app, let's namespace it under /api
. That way /api/notes.json
is a different action than the one we hit with the existing notes#index
route.
Additionally, let's namespace it under a version number, so if we have to change this API in the future, the old API will keep working. We don't want to break backwards compatibility with clients that integrated against older versions of the API.
Create a new route in config/routes.rb
:
namespace :api do
namespace :v1 do
resources :notes
end
end
Rails is going to expect our namespaced controller to be Api::V1::NotesController
, because that's how the Rails Inflector works unless we tell it otherwise.
http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html
The Inflector transforms words from singular to plural, class names to table names, modularized class names to ones without, and class names to foreign keys.
We'd prefer API
to Api
, so we'll add a custom inflector:
config/initialisers/inflections.rb
inflect.acronym 'API'
Having done that, we must add the necessary folders and files to create our API-specific NotesController
with an index
action that responds to .json
:
app/controllers/api/v1/notes_controller.rb
class API::V1::NotesController < ApplicationController
def index
@notes = Note.all
respond_to do |format|
format.json do
render json: @notes.to_json
end
end
end
end
The to_json
method can be called on any ActiveRecord model or relation, and we just called it on a relation, to return a collection of JSON hashes inside an array. However, using to_json
in this way is not a good design for an API that we don't want to change.