Skip to content

Instantly share code, notes, and snippets.

@abdelghanyMh
Created February 26, 2025 20:46
Show Gist options
  • Save abdelghanyMh/ca86a403d3f9c551cf69fde7655c9e3d to your computer and use it in GitHub Desktop.
Save abdelghanyMh/ca86a403d3f9c551cf69fde7655c9e3d to your computer and use it in GitHub Desktop.

Surrogate and Natural Keys

Key Concepts:

  1. Natural Key: An identifier provided by the client (e.g., an invoice number like 1234-567).
  2. Surrogate Key: An identifier generated by the server (e.g., a database auto-incremented ID like 101).
  3. 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).

Example 1: Cash Card API (Surrogate Key)

  • 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.
  • Why POST?
    The client doesn’t know the ID upfront—it’s generated by the server. POST lets the server "decide" the URI.

Example 2: Invoice API (Natural Key)

  • 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.
  • 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.

Key Differences:

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)

Why Does This Matter?

  • 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment