Resources, Verbs and Status Codes
The API is the contract between Sprout's two halves. When it follows predictable rules, the person writing the client can guess a route before reading any docs, and one small helper can handle every response. REST is the most widely used set of such rules, and Sprout has been following it quietly since the CRUD lesson.
The rule
Nouns in the path, verbs in the method, the outcome in the status.
Nouns in the path. A path names a thing, called a resource, usually as a plural noun: /api/plants is the collection, /api/plants/7 is one plant, and /api/plants/7/waterings is the waterings that belong to plant 7. Verbs stay out of paths.
Verbs in paths (avoid) REST style
POST /api/createPlant POST /api/plants
GET /api/getPlant?id=7 GET /api/plants/7
POST /api/deletePlant?id=7 DELETE /api/plants/7
POST /api/waterPlant?id=7 POST /api/plants/7/wateringsVerbs in the method. GET reads, POST creates, PATCH changes part, PUT replaces, DELETE removes. GET must never change anything, because browsers, caches and link previews feel free to send GET requests on their own, sometimes more than once.
The outcome in the status. The first digit tells the client whose problem it is before it reads a word of the body:
- 2xx, it worked:
200 OK,201 Created,204 No Content. - 4xx, the request was wrong:
400malformed,401not logged in,403not allowed,404not found,409conflicts with existing data,422failed validation. - 5xx, the server failed:
500for an unexpected error,503for temporarily unavailable.
REST also asks each request to be self-contained. Sprout's server does not remember what your last request was; each one carries its cookie and everything the handler needs.
The shortcut
Turn any feature into a verb on a noun you could list. "Water plant 7" sounds like a verb, but a watering is a thing with a date, and you could list a plant's waterings. So watering means creating a watering: POST /api/plants/7/waterings. For the response, first decide whose fault it is (2, 4 or 5), then pick the exact code.
Find the noun
The event is a watering. It has a date and could be listed as a history, so it is a resource.
Drills
Answer fast — trust the rule.
Which route follows REST style for deleting plant 7?
Why must a GET request never change data?
Someone registers with an email that already has an account. Which status fits best?
A response comes back 503. Whose side is the problem on?
Remember
- Nouns in the path, verbs in the method, the outcome in the status.
- Shortcut: make the feature a verb on a listable noun; for status, decide whose fault first.
- Trap: verbs in paths and
GETroutes that change data.
