- Natural Key: An identifier provided by the client (e.g., an invoice number like
1234-567
). - Surrogate Key: An identifier generated by the server (e.g., a database auto-incremented ID like
101
). - HTTP Verbs:
- POST: Used when the server determines the resource’s URI (uses surrogate keys).
- PUT: Used when the client determines the resource’s URI (uses natural keys).
- Scenario: You create a new Cash Card.
- How it works:
- Client sends a
POST /cashcards
request without specifying an ID. - Server generates a unique ID (e.g.,
101
) and creates the resource at/cashcards/101
. - Server returns the URI
/cashcards/101
to the client.
- Client sends a
- Why POST?
The client doesn’t know the ID upfront—it’s generated by the server. POST lets the server "decide" the URI.
- Scenario: You create an invoice with a pre-defined invoice number like
1234-567
. - How it works:
- Client sends a
PUT /invoices/1234-567
request. - The URI
/invoices/1234-567
is known in advance (the client provides the ID). - Server creates or updates the resource at that exact URI.
- Client sends a
- Why PUT?
The client controls the URI. PUT is idempotent (calling it repeatedly has the same effect as calling it once), which is safe for client-known URIs.
Scenario | POST | PUT |
---|---|---|
Who defines the URI? | Server | Client |
Use Case | Server-generated IDs (e.g., 101 ) |
Client-provided IDs (e.g., 1234-567 ) |
Idempotent? | No (multiple POSTs create duplicates) | Yes (multiple PUTs have the same effect) |
- POST is like asking a restaurant to "make me a dish" (the chef decides what you get).
- PUT is like saying, "Save this exact dish at Table 5" (you specify where it goes).
If the client knows the exact URI (natural key), use PUT.
If the server must generate the URI (surrogate key), use POST.
This ensures RESTful APIs follow HTTP standards and behave predictably.