REST API Design: It is Not Just About GET and POST
Any junior dev can write an endpoint that returns JSON. But designing an API that is Predictable, Scalable, and Maintainable? That takes care.
Your API is a User Interface for developers. If it is confusing, they will hate you.
Here is what we'll cover:
- Resource Naming: Nouns, not Verbs.
- HTTP Semantic Methods: When to use PUT vs PATCH.
- Status Codes: Stop returning 200 OK for errors.
- Idempotency: Safe retries.
1. Resource Naming (Nouns, Not Verbs)
Bad:
POST /getAllUsersPOST /createUserPOST /updateUser(This is RPC style, not REST).
Good:
GET /users(Get list)POST /users(Create)GET /users/123(Get specific)PUT /users/123(Update)
Rule: The URL describes the Resource (The thing). The Method describes the Action (The verb).
2. PUT vs. PATCH
This is a common interview question.
- PUT: Replace the Entire object.
- If I send
{ "name": "Bob" }, and the user had an age, the age is deleted. The new object is just{ "name": "Bob" }.
- If I send
- PATCH: Update Partial fields.
- If I send
{ "name": "Bob" }, the age is preserved.
- If I send
Mentor Tip: Most of the time, you want PATCH. PUT is dangerous if you don't send the whole payload.
3. Status Codes: Stop Lying
If I fail to login, do NOT return 200 OK with { "error": "Bad Password" }.
That breaks every monitoring tool in existence.
- 2xx (Success):
200: OK.201: Created (Use this for POST).204: No Content (Use this for DELETE).
- 4xx (Client Error):
400: Bad Request (You sent bad JSON).401: Unauthorized (Who are you?).403: Forbidden (I know who you are, but you can't touch this).404: Not Found.
- 5xx (Server Error):
500: I crashed. (This is shameful. Fix your logs).
4. Idempotency (Safe Retries)
Networks are flaky. Clients will retry requests. Idempotency means: "If I make the same request 10 times, the result is the same as if I made it 1 time."
GET: Idempotent (Reading 10 times changes nothing).PUT/DELETE: Idempotent (Deleting row 123 ten times is fine. It's gone).POST: NOT Idempotent.- If I POST
/payment10 times, I might charge the customer 10 times.
- If I POST
The Fix: Use "Idempotency Keys." The client generates a unique ID (UUID) and sends it in the header. The server checks: "Have I seen this UUID before? If yes, ignore."
Summary
- URLs are Nouns. Actions are Verbs.
- Respect Status Codes. Don't lie to the client.
- Know your Methods. PUT (Replace) vs PATCH (Update).
- Design for retry. The network will fail.
