-
Explain what REST is
-
Map a RESTful HTTP request to CRUD operations
-
List the 8 Rails routes for a data resource
-
Explain the purpose of each of the 8 routes
-
What is REST?
-
Anatomy of a RESTful HTTP Request
-
RESTful APIs
-
RESTful routing in Rails
-
REST is a whacky acronym that stands for:
REpresentational State Transfer -
REST was conceived by Roy Fielding.
-
Roy was born in Laguna Beach and attended UC Irvine, where he finished his doctorate within the Software Research Group.
- According to Roy, the meaning of Representational State Transfer is:
Representational State Transfer is intended to evoke an image of how a well-designed web application behaves: a network of web pages (a virtual state-machine), where the user progresses through an application by selecting links (state transitions), resulting in the next page (representing the next state of the application) being transferred to the user and rendered for their use.
If you dissect the above, it actually makes sense.
-
Defined in 2000.
-
REST is a Style of Software Architecture for distributed computing.
-
REST allows software distributed across multiple devices (clients) to interact with servers over the internet using HTTP.
-
In today's lesson, we'll look at two common scenarios of RESTful client/server interaction:
-
RESTful APIs
-
RESTful Routing in Rails
-
-
When a browser makes a request to a web server, the request is composed of the following:
- The HTTP Verb (aka HTTP Method)
- A URL identifying the resource requested
- Optional HTTP Headers (including Cookies)
- Optional body data (often referred to as the payload)
-
Let's use Chrome's DevTools to check out what these components might look like when browsing to www.yahoo.com.
-
Okay, we just saw what a HTTP request and response looks like in detail.
-
Moving on to REST, unless we need to deal with authentication when making a RESTful request, we can ignore headers and cookies.
-
That leaves us with only two key parts in a RESTful request:
The HTTP Verb, and the URI Endpoint
Note, we will also want to send a data payload with certain requests, but let's just focus on these two pieces for now.
-
When we type in a location in our browser's address bar and press [return], it will make a request using the
GET
HTTP verb. -
Since we can issue a GET request with our browser, let's make a GET request to an online RESTful API. Type this in the address bar:
http://jsonplaceholder.typicode.com/users
-
JSONPlaceholder is a RESTful API with fake data - great for testing and learning with!
-
FYI, most modern RESTful APIs return JSON content by default.
-
The
users
resource represents the data entity we are interested in accessing on the server and is usually pluralized just like a table in a database. -
Scrolling down through JSONPlaceholder's homepage reveals that they also have several other resources we can access:
posts
comments
albums
photos
todos
-
Let's breakdown the RESTful URI we just used:
http://jsonplaceholder.typicode.com/users
-
http://jsonplaceholder.typicode.com
: The scheme and host segments. -
/users
: The resource segment.
-
-
In REST, this URI is referred to as the collection URI, and is used to read or add to the resource collection.
-
The response to our
GET
request tohttp://jsonplaceholder.typicode.com/users
is formatted as _______?
-
Now let's try this URI:
http://jsonplaceholder.typicode.com/users/5
-
We have appended an extra segment to the URI that identifies a specific resource, in this case, the user with an id of 5.
-
This URI is referred to as the item URI, and is used to read, update, or delete a single existing resource.
-
Notice that although we are accessing a single entry, the resource name in the URI,
users
, remains unchanged. It should not changed touser
.
Take a minute to review these questions before the picker does its thing:
-
In your own words, what is REST?
-
Another word for a HTTP Verb is a HTTP _______.
-
A _______ sends a RESTful request, and a _______ responds to that request.
-
A RESTful request consists of a HTTP _______, a _______, and optionally a data payload.
-
Now that we know that every RESTful request consists of a HTTP Verb and a URI Endpoint, it's time to look at a specific use case: RESTful APIs.
-
RESTful APIs allow client software to Read, and optionally Create, Update and Delete data resources on a server, or in other words, perform CRUD data operations.
A tidbit of vocab:
- A RESTful Request (HTTP Verb + URI) made from a client, is also known as REST Method Call.
On the server side, the server:
- Receives the request from the client.
- The routing system matches the HTTP verb and URI to the appropriate code to run (method).
- The code performs the actual CRUD operation.
- Finally, a response is sent to the client consisting of a HTTP Status Code and the appropriate resource (usually as JSON).
Here's a link to valid HTTP Status Codes, with those used in REST identified.
-
As a reminder, there are only two URI patterns necessary to access a particular resource.
The ________ URI and the ________ URI. -
But if there are only two URIs, how does the server know which CRUD operation we want to perform?
That's where the HTTP Verb comes into play. -
Indeed, the same URI behaves differently when used with different HTTP Verbs!
-
Up to this point, we've only seen the
GET
method, now let's checkout the rest!
Here are the RESTful requests for a resource named posts:
The :id in the URI is called a named parameter in the HTTP request, which we will use heavily in Rails and Node.
Committing the REST methods & CRUD Mapping to memory is pretty much necessary, so let's get started...
-
Quick Review
Again, what are the two URI patterns,
collection & item, used for? -
Cool, let's move on.
-
This would be a good time to mention that you will come across "longer" URIs with extra segment(s) between the host and resource segments. For example:
https://www.toysrus.com/api/v2/toys
-
These extra segments are called namespacing and don't change anything in regards to REST. When designing your URIs, it's fine to just refer to the resource segment, for example:
/toys
and/toys/:id
-
GET
sounds just like what it does: it gets, which you can easily associate with the Read in CRUD. -
GET
is the only HTTP Verb used with both URI patterns:GET /todos
returns a JSON array oftodo
objects.GET /todos/:id
returns a single JSONtodo
object.
-
Slam dunk!
-
We all love slam dunks, so here's another...
-
The
DELETE
verb - you got it, maps to Delete in CRUD. -
Although we could write an API to accept
DELETE
with the collection URI, doing so would mean that you want to wipe out the entire resource collection, which would be rare. -
So, when designing your RESTful APIs in WDI, use the
DELETE
verb with just the item URI, i.e.,DELETE /frogs/249
-
Hey, that's 3 of the 6 REST methods, we're halfway home! But the last 3 require a little more effort to memorize :)
-
We need to map a HTTP verb to Create -
POST
is our answer. -
POST
is the HTTP method HTML forms use by default, so just remember that on web pages, wePOST
new data to the server. -
If POST creates a resource that doesn't exist yet, guess which URI path we must
POST
to?
-
The last two,
PUT
andPATCH
, are very similar, so similar in fact that some APIs only implementPUT
. -
We've already mapped to CRUD's Read, Delete and Create, so if you reasoned that
PUT
andPATCH
maps to CRUD's Update, you'd be correct! -
I bet you can guess which URI pattern to pair with - what is it?
-
So, what's the difference between
PUT
andPATCH
?...
The difference between PUT and PATCH is:
-
PUT
is intended to replace the entire resource with the data sent in the payload; and... -
PATCH
is intended to update just the properties included in the payload. -
I think the word
PATCH
is pretty descriptive, so hopefully you can remember thatPUT
is the one that replaces the entire resource.
-
What does a RESTful resource represent?
-
What is CRUD?
-
Name the five HTTP verbs used in REST
-
The RESTful request,
GET /tacos
, does what? -
The RESTful request,
POST /tacos
, does what? -
What is wrong with this request,
PUT /tacos
?
-
Create a file named
rest_api.md
. -
Create a heading, "RESTful API to CRUD Mapping".
-
Create a table with the following headings:
- HTTP Verb
- URI
- CRUD Operation
Click for a Markdown Syntax Cheat Sheet
-
Design a RESTful API for a resource: accounts.
-
Include all six REST Methods (HTTP Verb + URI pairs).
-
We've just learned about RESTful API client/server interaction.
What happens in that interaction? -
Now it's time to look at another use case for REST: Rails
-
The REST architectural style does not require that a RESTful request return a JSON response from the server.
-
The Ruby on Rails framework takes advantage of the flexibility of REST...
-
We're going to start working with RoR tomorrow, but we're first going to examine the role REST plays in the framework.
-
Rails can be used to expose a RESTful API like that which we just discussed.
-
However, Rails was designed to incorporate REST in a process fundamental to every web app: routing.
-
The process of routing for a web application is performed by a piece of software known as the router.
-
The router:
- Examines each HTTP request received from clients
- Matches the request against routes defined by the developer
- Invokes the code specified by the matching route definition
-
Rails was designed to use REST method calls to drive the application logic!
-
For example, lets say a web page contains a link containing
href="/students/23"
. That URI looks pretty RESTful - right? Clicking that link would send aGET /students/23
request to the server and by convention, the Rails app would respond with an HTML page displaying information pertaining to the student with an id of 23! Ponder this for a bit - it's really good stuff!
-
Route definitions map RESTful request patterns (HTTP verb + URI). Here's a fragment of a real Rails
routes.rb
file used to define the routes in a Rails app:get "/accounts", to: "accounts#index" get "/accounts/:id", to: "accounts#show" post "/accounts", to: "accounts#create" ...
-
There are 3 route definitions above, each one mapping a RESTful request to code.
-
In the first example, a
GET /accounts
request will invoke the code in theindex
action (method) that's defined in theaccounts
controller. The other two routes do what?
-
A Rails app's functionality is driven by what?
-
The software on a server that handles requests and invokes code is known as a _________?
-
A _________ definition maps an HTTP verb and URI to _________.
-
Unlike a RESTful API responding with JSON, a Rails application by convention responds to REST method calls with _________.
-
What two pieces of information does a router use when matching a route definition?
-
Like a RESTful API, each REST method call will target a particular data resource, i.e., users, posts, comments, etc. A distinction being that in Rails, we will most often think of our resources as models named singularly, e.g., a
users
resource maps to aUser
model. -
Also like a RESTful API, a Rails app performs CRUD. The difference being that a Rails app returns HTML to the client.
-
Further, just like a RESTful API, Rails may not implement every CRUD operation for a particular resource. But if it does, there are 8 routes to define...
Here are the full 8 RESTful routes in Rails that you will need to know. Let's review them:
- Once you have learned the RESTful API routes, it's not a big jump to learn the Rails routes - there are only two extra routes, which technically do not have a RESTful URI pattern.
Which are they?
-
GET /resource/new
: This non-RESTful route serves to deliver a web page with a form for entering a new resource. The form willPOST
to/resource
, which maps to thecreate
action. -
GET /resource/:id/edit
: This non-RESTful route is similar to theGET /resource/new
, except that it will deliver a web page with a form for editing an existing resource. The form when submitted will "fake" aPUT
orPATCH
to/resource/:id
. -
Why a "fake"
PUT
orPATCH
you ask...
-
By default, our web pages can only issue
GET
andPOST
requests unless we utilize the browser's XMLHttpRequest object using JavaScript. So how do we code our Rails apps to issuePUT
,PATCH
orDELETE
requests? -
Well, there's some code known as Rack middleware that Rails is built on top of. This middleware has a mechanism that will allow our normal
GET
orPOST
requests to be changed to aPUT
,PATCH
orDELETE
on the server. We'll learn more about this next week.
Finally, here's a graphical review of Rails' RESTful routing:
-
How many routes are there per resource in a full-CRUD Rails app?
-
What is one of the two non-RESTful routes and what is it for?
-
What is the other non-RESTful route and what is it for?
-
What action will the router call if a
POST /comments
request is received? -
What action will the router call if a
GET /comments/:id
request is received?
-
Create a file named
rails_rest.md
in today's working directory. -
Create a heading, "RESTful Routing in Rails".
-
Create a table with the following headings:
- HTTP Verb
- URI
- Rails controller#action
- Default View (if any - hint: only GETs have default views)
- Purpose
-
Complete all 8 routes for a resource: users.