REST
We’ve already seen that with our blog, we could convey which post to display with different URL strategies, i.e.:
- http://my-blog.com/posts?id=5
- http://my-blog.com/posts/5
- http://my-blog.com/posts/5-a-night-that-was-dark
And that is just to display posts. What about when we want our blog software to allow the writer to submit new posts? Or edit existing ones? That’s a lot of different URLS we’ll need to keep track of.
Representational State Transfer (REST)
Roy Fielding tackled this issue in Chapter 5 of his Ph.D. dissertation “Architectural Styles and the Design of Network-based Software Architectures.” He recognized that increasingly dynamic web servers were dealing with resources that could be created, updated, read, and destroyed, much like the resources in database systems (not surprisingly, many of these resources were persistently stored in such a database system). These operations are so pervasive in database systems that we have an acronym for them: CRUD.
Roy mapped these CRUD methods to a HTTP URL + Method pattern he called Representational State Transfer (or REST). This pattern provided a well-defined way to express CRUD operations as HTTP requests.
Take our blog posts example. The RESTful routes associated with posts would be:
URL | HTTP Method | CRUD Operation |
---|---|---|
posts/ | GET | Read (all) |
posts/:id | GET | Read (one) |
posts/ | POST | Create |
posts/:id | POST | Update |
posts/:id | DELETE | Delete |
The :id
corresponds to an actual identifier of a specific resource - most often the id
column in the database. REST also accounts for nesting relationships. Consider if we added comments to our posts. Comments would need to correspond to a specific post, so we’d nest the routes:
URL | HTTP Method | CRUD Operation |
---|---|---|
posts/:post_id/comments | GET | Read (all) |
posts/:post_id/comments/:comment_id | GET | Read (one) |
posts/:post_id/comments | POST | Create |
posts/:post_id/comments/:comments_id | POST | Update |
posts/:post_id/comments/:comments_id | DELETE | Delete |
Notice that we now have two wildcards for most routes, one corresponding to the post
and one to the comment
.
If we didn’t want to support an operation, for example, updating comments, we could just omit that route.
REST was so straightforward and corresponded so well to how many web servers were operating, that it quickly became a widely adopted technique in the web world. When you hear of a RESTful API or RESTful routes, we are referring to using this pattern in the URLs of a site.