RESTful

Adrian M Popan
2 min readJul 31, 2019

--

What is REST?

Representational State Transfer (REST) is an architectural style for web-based communication that permits clients to talk to servers in a unique fashion. In particular, REST represents resources within a given server as uniform resource identifiers (URIs), simplifying the implementation of REST architectures on the Hypertext Transport Protocol (HTTP). REST is a set of constraints that ensure a scalable, fault-tolerant and easily extendible system.

  1. GET all the photos (aka “index” the photos)
  2. GET the page that lets you create a new photo (aka view the “new” photo page)
  3. POST the data you just filled out for a new photo back to the server so it can create that photo (aka “create” the photo)
  4. GET just one specific photo (aka “show” that photo)
  5. GET the page that lets you edit an existing photo (aka view the “edit” photo page)
  6. PUT the data you just filled out to edit the photo back to the server so it can actually perform the update (aka “update” the photo)
  7. DELETE one specific photo by sending a delete request to the server (aka “destroy” the photo)

The RAILS way to write RESTful routes:

# in config/routes.rb
...
resources :photos
...

All the routes are corresponding to a controller action:

# in app/controllers/photos_controller.rb
class PhotosController < ApplicationController

def index
# very simple code to grab all photos so they can be
# displayed in the Index view (index.html.erb)
end

def show
# very simple code to grab the proper Photo so it can be
# displayed in the Show view (show.html.erb)
end

def new
# very simple code to create an empty photo and send the user
# to the New view for it (new.html.erb), which will have a
# form for creating the photo
end

def create
# code to create a new photo based on the parameters that
# were submitted with the form (and are now available in the
# params hash)
end

def edit
# very simple code to find the photo we want and send the
# user to the Edit view for it(edit.html.erb), which has a
# form for editing the photo
end

def update
# code to figure out which photo we're trying to update, then
# actually update the attributes of that photo. Once that's
# done, redirect us to somewhere like the Show page for that
# photo
end

def destroy
# very simple code to find the photo we're referring to and
# destroy it. Once that's done, redirect us to somewhere fun.
end
end

In case you decide that all 7 RESTful routes that resources are too much you can opt in or out the routes:

resources :photos, only: [:index, :show]
...
or
...
resources :photos, except: [:index]

For more documentation on rails routes :

https://edgeguides.rubyonrails.org/routing.html

--

--