Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
What Is REST? | 191

Implicit in this definition of resources is that resources have state as well (a resource
could have empty state in the degenerate case, but this is atypical). One of the con-
straints that REST places on interaction with resources is that every RESTful
resource has a uniform interface. No client has ad-hoc access (read or write) to a
resource’s state; it is internal to the resource. All access takes place by transferring
representationsof the resource’s state*back and forth via a uniform set of methods
(in our case, HTTP).


Name opacity


A controversial principle of REST is whether names should beopaque. An opaque
value, in a network protocol, is a piece of data that the recipient can remember and


Pragmatic REST
REST in Rails is a balance between theoretical purity and pragmatism. The fact is that
many browsers do not support the full set of response codes according to the HTTP
standard.
Resource creation viaPOSTis a good example of a discrepancy. The correct response to
successful creation is a201 Createdcode with aLocationheader pointing to the created
resource. However, most web browsers will not redirect in response to a 2xx-series
response. Rails strikes a balance. When rendering HTML, it uses a 3xx-series redirect
to satisfy web browsers. When rendering XML, it is assumed that the client will be cog-
nizant of all HTTP response codes, and it uses the appropriate response codes.
We see this in action in a typical scaffolded controller:
# POST /products
# POST /products.xml
def create
@product = Product.new(params[:product])

respond_to do |format|
if @product.save
flash[:notice] = 'Product was successfully created.'
format.html { redirect_to(@product) }
format.xml { render :xml => @product,
:status => :created, :location => @product }
else
format.html { render :action => "new" }
format.xml { render :xml => @product.errors,
:status => :unprocessable_entity }
end
end
end


  • Hence the name:Representational State Transfer.

Free download pdf