Lesson Tuesday

When you think about the life of any information in your application, it typically goes through four phases: creating the information, reading it, updating it, and destroy it. When we talk about databases, we often refer to these operations as CRUD.

In the web applications we've built so far, we've learned that the GET method retrieves information without changing anything on the server, and the POST method creates something on the server. To be able to update and destroy information, we need two other common HTTP methods: PATCH and DELETE. The PATCH method updates the server; and the DELETE method destroys something on the server. Most browsers can only make GET and POST requests, so to make a PATCH or DELETE request, they actually make a POST request and then include some extra information telling the server to treat it like a PATCH or DELETE.

Let's look at Facebook as an example of using GET and POST. When you go to view your friends' photos on Facebook, your browser makes a GET request: nothing is changed on the Facebook servers. But when you post a video of your dog tripping over his feet, your browser makes a POST request: you are adding to - or changing - the Facebook server, and your video resource is now stored and able to be accessed via GET requests at another time. Similarly, when you "like" your best friend's photo of her dinner last night, your browser makes a POST request to the Facebook server.

Now, let's expand this example to include PATCH and DELETE. When you edit the caption on a photo, you are telling your browser to make a PATCH request to the Facebook server, because you're updating the existing photo. And finally, when you delete that old photo of you and your ex, you are telling your browser to make a DELETE request, since you are removing that resource from the Facebook server.

In modern web applications, we typically use the same URL and a different HTTP method to convey what we're trying to do. In our car dealership app, our requests might look something like this:

Create a vehicle: POST http://localhost:8000/vehicles
View a vehicle: GET http://localhost:8000/vehicles/5 (where 5 is the ID)
Update a vehicle: PATCH http://localhost:8000/vehicles/5
Delete a vehicle: DELETE http://localhost:8000/vehicles/5

Using the same URL and different HTTP methods to convey what action the server should take is part of a widely-accepted approach for designing web applications called REST, or REpresentational State Transfer. If you follow REST, each part of your application is modeled as a resource. For now, you can think of each object in your application as a resource (for more complex applications, this isn't always true).

For viewing multiple vehicles, the request would typically be GET http://localhost:8000/vehicles. And for searching for a vehicle, or viewing a subset of all the vehicles, the request might look something like GET http://localhost:8000/vehicles?color=red&make=toyota.