I'm trying to make an API for my rails application using JSON responses to RESTful resource controllers. This is a new experience for me, so I'm looking for some guidance and pointers. To start things off:
Additional information:
REST stands for REpresentational State Transfer and describes resources (in our case URLs) on which we can perform actions. CRUD , which stands for Create, Read, Update, Delete, are the actions that we perform. Although, in Rails, REST and CRUD are bestest buddies, the two can work fine on their own.
Rails embraced REST in version 2, and since then it has been core to how we write and think about the structure of our web applications.
The Rails controller is the logical center of your application. It coordinates the interaction between the user, the views, and the model. The controller is also a home to a number of important ancillary services. It is responsible for routing external requests to internal actions.
#config/routes.rb
MyApplicationsName::Application.routes.draw do
resources :articles
end
#app/controllers/articles_controller.rb
class ArticlesController < ActionController::Base
# so that respond_with knows which formats are
# allowed in each of the individual actions
respond_to :json
def index
@articles = Article.all
respond_with @articles
end
def show
@article = Article.find(params[:id])
respond_with @article
end
...
def update
@article = Article.find(params[:id])
@article.update_attributes(params[:article])
# respond_with will automatically check @article.valid?
# and respond appropriately ... @article.valid? will
# be set based on whether @article.update_attributes
# succeeded past all the validations
# if @article.valid? then respond_with will redirect to
# to the show page; if [email protected]? then respond_with
# will show the :edit view, including @article.errors
respond_with @article
end
...
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With