Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 2: Working with web services CHAPTER 8 365


Understanding Representational State Transfer (REST)
REST attempts to use the standard operations of HTTP (or similar protocols) by mapping cre-
ate, retrieve, update, and delete (CRUD) operations to HTTP methods so that GET retrieves
data or performs an operation that does not change server-side data. POST updates data but
can retrieve data when complex parameter values need to be sent to the server. PUT inserts
new data, and DELETE deletes data. REST focuses on interacting with stateless resources
rather than on messages or operations. Clean URLs are tightly associated with the REST con-
cept. Because the method infers a verb, the URL should describe the entity as a noun. Here
are some examples of REST URLs.
■■Retrieve customer number five The number five is part of the URL and not part of
the QueryString. The routing mechanism in the server would need to parse this cor-
rectly. Because this is retrieving data, the HTTP method would be set to GET. You can
POST to this location to update or DELETE to this URL to delete the customer.
http://localhost:8080/Customer/5
■■Retrieve vehicle with a Vehicle Identification Number (VIN) of ABC123 The VIN
is in the QueryString. Once again, the HTTP method is set to GET.
http://localhost:8080/Vehicle?VIN=ABC123
■■Retrieve all orders The HTTP method is set to GET, and there is no parameter. A PUT
to this URL adds an order.
http://localhost:8080/Orders
■■Insert customer The HTTP method is set to PUT, and the postback data is in the
request body, so you don’t see the data in the URL or QueryString. The following is the
URL and the postback data.
http://localhost:8080/Customers
name=ACME&Address=123+Bumblebee+Lane

To work around the problem when many firewalls don’t allow PUT and DELETE methods,
you can specify a verb in your QueryString or postback data. You should not change the URL
to contain the method because that breaks the RESTful interface, which specifies that the URL
must be a reference to an entity or entity collection. Here are a couple of examples of placing
the verb in the data.
■■Delete vehicle with a Vehicle Identification Number (VIN) of ABC123 The VIN is
in the QueryString. The HTTP method is set to GET to get past the firewall.
http://localhost:8080/Vehicle?verb=DELETE&VIN=ABC123
■■Insert customer The HTTP method is set to POST, and the postback data is in the
request body, so you don’t see the data in the URL or QueryString. The verb is set to
PUT in the data. The following is the URL and the postback data.
http://localhost:8080/Customers
varb=PUT&name=ACME&Address=123+Bumblebee+Lane
Free download pdf