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.