
In my last post, I wrote a general rundown of HTTP messaging. There’s a lot that goes into it. And a thorough grounding in what HTTP is and how it works is essential to API design and consumption.
Generally speaking, when you have a path to do an action, you’ll want routes (or paths) that are very general nouns. Let’s say your site creates widgets. Doesn’t matter what a widget is, replace it with any sort of record you want. There were some PHP frameworks whose default behavior is to have routes such as:
/widget/create
or /widget/-1
While these paths will work, it is not generally accepted as the “right” way to do things. Rather, you want to use HTTP verbs to define what you want to do with a widget.
HTTP Verb | Explanation | Example Path |
GET | Retrieve information about a single record by ID. | /widgets/1 |
GET | Search for widgets. | /widgets/?name=foobar |
GET | List the widgets or a create new widget form. | /widgets/ |
POST | Create a new widget record based from POST’ed data | /widgets/ |
PUT | REPLACE an existing widget record with the POST’ed data | /widgets/1 |
PATCH | Supply a set of instructions to edit a widget. | /widgets/1 |
DELETE | Delete (either physically or logically) a widget. | /widgets/1 |
Notice how using a GET request with no argument can give you either a list or an HTML form to create a new widget? So if I’m writing a JSON or XML response, I’ll usually simply list the widgets, while if I’m making HTML page, I’ll have the server respond with both a list and a form.
There are certain methods that are defined as “safe” and as “idempotent.” “Safe” methods are those that won’t change data, in other words, it’s read only. That includes the verbs GET, as well as verbs we didn’t cover here, such as HEAD, OPTIONS, and TRACE. “Idempotent” simply means that if you accidently submit it twice, it’s no biggie: it won’t change anything. For instance, if you submit a POST request twice, two identical widgets will be created. If you submit a PUT request twice, it doesn’t much matter, because you’ll just be making an update twice. PUT and DELETE requests should be considered both safe and idempotent. When we talk about status codes in HTTP response messages, we’ll see that the definition for idempotent is a little faulty, since DELETE should show a different status code the second time a DELETE request is made on the same widget.