Skip to content
Index Ai Academy
Phase 8 · Building APIs

A database-backed API

CRUD endpoints on SQLite, with safe concurrent updates.

About 45 minutes · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers8

First principles

Why can two valid writes still leave the wrong database state?

A read followed by a separate write can use stale information. An atomic update or a transaction makes the database apply the intended state change safely.

  1. Starting point

    Two requests increment a stored value of 7

  2. What changes

    Each executes UPDATE with value = value + 1

  3. Result

    The stored value reaches 9

Compare all three steps
  1. Starting point

    Two requests increment a stored value of 7

  2. What changes

    Each executes UPDATE with value = value + 1

  3. Result

    The stored value reaches 9

Complete and reverse the trace

Given Two requests increment a stored value of 7 and The stored value reaches 9, write down the missing step that connects them.

Compare with the worked step

Each executes UPDATE with value = value + 1

Now take Each executes UPDATE with value = value + 1 and the result above. Write an input and an implementation that could produce this trace.

Check one starting point

Two requests increment a stored value of 7. Check that your implementation produces the result shown above.

Try it on a new case

What might happen if both handlers first read 7 and later write 8?

Show worked reasoning

The final value can be 8, losing one update. The fixed version computes the increment against the database's current value.

Run, change, and build

Check this when debugging. Building UPDATE column names from request keys.

Trace the cause · HTTP request, job, and result
  1. Identify the request, response, and any durable state. Predict the status or stored result before following the trace.
  2. Change one request property and keep the client contract visible. Compare the response and job state to explain the observed behavior.
  3. Try the same reasoning on this case. What might happen if both handlers first read 7 and later write 8?

Why it matters

Real APIs keep their data in a database, and many users change it at once. That's where the subtle bugs live. Two people edit the same record and one change silently disappears. A PATCH lets a user set a field they shouldn't. A duplicate slips past a check. This lesson connects the REST design from Designing a REST API to the SQL from Phase 7, and adds the techniques that keep shared data correct.

What you'll be able to do

  • Map REST operations onto SQL through a repository layer
  • Build PATCH updates safely from an allowlist of fields
  • Prevent lost updates with version numbers, ETags and If-Match
  • Turn database outcomes into the right status codes: 201, 404, 409 (a clash with data), 412 (a stale version), 428
Quick check
Two admins load a campaign at the same time, each changes a different field, and both save the whole record. What happens?
  1. The first save always wins
  2. Both saves fail with an error
  3. The database merges both changes automatically
  4. The second save quietly overwrites the first admin's change
Show the answer

The second save quietly overwrites the first admin's change

Each admin wrote back the whole record as they last saw it, so the second save erased the first change: a lost update. A version number checked on save turns it into a clear conflict instead.

The idea: two clients, one row and a version

This rests on Designing a REST API, where PUT was idempotent and a stale write needed a precondition, and on Databases and SQL, where values went into a query through placeholders.

From routes to SQL

Think of a library's front desk. Visitors ask the librarian for a book, and only the librarian goes into the stacks. A repository class does that job in your code, using the pattern from the design lesson. Handlers ask it for things, and all the SQL lives inside it. Each REST operation maps onto one SQL statement:

requestrepository methodSQLsuccess
POST /campaignscreate(...)INSERT201 + Location
GET /campaigns/{id}get(id)SELECT ... WHERE id = ?200, or 404
PATCH /campaigns/{id}update(id, changes)UPDATE ... SET ... WHERE id = ?200, or 404
DELETE /campaigns/{id}delete(id)DELETE ... WHERE id = ?204, or 404

Handlers stay short: parse and validate, call the repository, turn the result into a response. Database rules become status codes too. A UNIQUE constraint failing on a duplicate email becomes 409 Conflict, not a 500.

Quick check
A UNIQUE constraint fails on a duplicate email. Which status should the API answer?
  1. 404 Not Found
  2. 500 Internal Server Error
  3. 409 Conflict
  4. 201 Created
Show the answer

409 Conflict

The request clashes with what is already stored. That is the client's to fix, so it gets a 4xx that says why.

The lost update

Ada and Lin both open campaign 7, budget 500. Ada changes the name and saves. Lin, looking at an older copy, changes the budget and saves the whole record. Lin's save writes back the old name. Ada's change has vanished, and nobody got an error. That's a lost update, and with many users it happens every day.

Optimistic concurrency with versions

Think of a shared recipe card with a version number in the corner. Before you write your changes on it, you check the number is still the one you read. If it's gone up, someone has changed the card, and you read it again first.

In a database, give each row a version number that goes up on every change. A client says which version it started from, and the update only applies if that's still the current one:

UPDATE campaigns SET budget = ?, version = version + 1
WHERE id = ? AND version = ?

If someone else saved in between, the version no longer matches and no rows change. The API reports a conflict, and the client reloads and tries again. It's called optimistic because it assumes conflicts are rare and only checks at save time, instead of locking the record while someone edits it.

Quick check
Ada and Lin both read campaign 7 at version 3. Ada saves first, so the row is now at version 4. Then Lin's update runs with WHERE id = 7 AND version = 3. What happens?
  1. Ada's save is rolled back
  2. Lin's save overwrites Ada's, as before
  3. The two saves are merged
  4. No rows change, so the API reports a conflict
Show the answer

No rows change, so the API reports a conflict

The version no longer matches, so the UPDATE finds no row to change. That's the signal of a conflict: Lin reloads the new version and tries again, and Ada's change survives.

ETags and If-Match

HTTP has headers for exactly this. A GET response carries an ETag, a short tag for this version of the resource, such as "7-3". To update, the client sends it back in an If-Match header, which means "only do this if it's still that version":

  • If it matches the current ETag, the update goes ahead, and the response carries the new ETag.
  • If it doesn't, the answer is 412 Precondition Failed: "someone changed this; reload first".
  • If an API requires If-Match and it's missing, the answer is 428 Precondition Required.

ETags help reads too. A client sends If-None-Match with the ETag it has, meaning "only send it if it's changed". If nothing changed, the server answers 304 Not Modified with no body, which saves bandwidth.

Try it now

No locks: each update checks the version its author read.

Quick check
A client PATCHes with If-Match: "7-3", but the campaign is now at version 4. What should the API answer?
  1. 412 Precondition Failed
  2. 500 Internal Server Error
  3. 404 Not Found
  4. 200 OK, applying the change anyway
Show the answer

412 Precondition Failed

The client's copy is out of date. 412 tells it to fetch the latest version and try again.

In your own words
What is a lost update, and how do a version number and If-Match prevent it?

Write a sentence or two, then compare it with a good answer in the lesson.

In Python: an update you can build safely, and break

A PATCH sends only the fields to change, so the UPDATE has to be built from whichever keys arrive. Values always go in placeholders. Column names can't be placeholders, because they are part of the statement itself, so they must come from your own fixed list and never straight from the request.

An allowlist for the columns

Picture a form where staff may change your address, but not your account balance. PATCH needs the same rule. It sends only the fields to change, such as {"budget": 750}, so the UPDATE statement has to be built from whichever keys arrive.

Values always go in placeholders, the ? marks that keep data apart from the SQL. But column names can't be placeholders, because they're part of the statement itself. So they must come from your own fixed list, an allowlist, and never straight from the request. Otherwise a client could send {"is_admin": 1}, or a key containing SQL.

Setup (runs before every cell) · 3 lines

The lesson runs this once, before its first cell, and every cell, drill and example starts with what it defines. A cell that changes a setup object changes it for the cells after it, until the page reloads.

import requests

BASE = "https://api.gradient.test"
EDITABLE = {"name", "budget", "status"}          # the allowlist

def build_update(changes):
    unknown = set(changes) - EDITABLE
    if unknown:
        raise ValueError(f"can't change: {', '.join(sorted(unknown))}")
    columns = sorted(changes)                     # sorted, so the SQL is predictable
    assignments = ", ".join(f"{col} = ?" for col in columns)
    return f"UPDATE campaigns SET {assignments} WHERE id = ?", [
        changes[c] for c in columns
    ]

print(build_update({"budget": 750, "status": "active"}))
try:
    build_update({"budget": 750, "owner_id": 1})
except ValueError as err:
    print("rejected:", err)
It runs right here in your browser, with nothing to install.

The column names in the SQL come only from EDITABLE, which you wrote; the values travel separately. Allowlisting also stops mass assignment: a client quietly setting fields such as role or price_paid that it was never meant to touch.

Quick check
Why can't you write UPDATE campaigns SET ? = ? WHERE id = ? and pass the column name as a placeholder?
  1. Column names must be written in uppercase, not passed in
  2. Placeholders only stand for values, not names of columns or tables
  3. You can: a placeholder is the safest way to pass any name
  4. SQLite only allows one placeholder in each statement
Show the answer

Placeholders only stand for values, not names of columns or tables

The database plans the query before it sees the values, so names must be in the SQL itself. That's why they must come from an allowlist you control.

An attack to try: a PATCH key that carries SQL

The cell builds an update the careless way, by pasting each key from the request into the statement. A client sends a key that is not a column name but a piece of SQL, and the statement does more than the client was allowed to ask.

Uses the setup above, 3 lines.

import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE campaigns (id INTEGER PRIMARY KEY, budget REAL, owner TEXT)")
db.execute("INSERT INTO campaigns VALUES (1, 500, 'ada')")

def naive_update(changes):
    sets = ", ".join(f"{key} = ?" for key in changes)
    db.execute(f"UPDATE campaigns SET {sets} WHERE id = 1", list(changes.values()))

naive_update({"budget": 750})
print(db.execute("SELECT budget, owner FROM campaigns").fetchone())
naive_update({"budget = 1, owner = 'mallory', id": 1})
print(db.execute("SELECT budget, owner FROM campaigns").fetchone())

The values were safe in placeholders, but the key was part of the SQL, so the second request set the budget to 1 and changed the owner to mallory. The allowlist from the cell above refuses that key before any SQL is built, because it is not one of name, budget or status.

Quick check
From the lesson on databases and SQL: values go into a query through placeholders. Two saves both believe the row is at version 3. What does this print: the rows changed by each update, and the row at the end?
import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE campaigns (id INT, budget INT, version INT)")
db.execute("INSERT INTO campaigns VALUES (7, 500, 3)")
sql = (
    "UPDATE campaigns SET budget = ?, version = version + 1 "
    "WHERE id = ? AND version = ?"
)
first = db.execute(sql, (800, 7, 3)).rowcount
second = db.execute(sql, (300, 7, 3)).rowcount
print(first, second, db.execute("SELECT budget, version FROM campaigns").fetchone())
  1. 0 0 (500, 3)
  2. 1 0 (800, 4)
  3. 1 1 (300, 5)
  4. 1 1 (300, 4)
Show the answer

1 0 (800, 4)

The first update finds the row at version 3, changes the budget and moves the version to 4. The second still asks for version 3, matches no row, and changes nothing. Nothing was overwritten, and a rowcount of 0 tells the API to answer with a conflict.

Worked example

A conflict, caught

Two clients read version 1. The first update succeeds; the second matches no rows.

Uses the setup above, 3 lines.

import sqlite3

db = sqlite3.connect(":memory:")
db.execute(
    "CREATE TABLE campaigns (id INTEGER PRIMARY KEY, name TEXT, "
    "budget REAL, version INTEGER NOT NULL DEFAULT 1)"
)
db.execute("INSERT INTO campaigns (name, budget) VALUES ('Spring', 500)")

def update_budget(cid, budget, expected_version):
    cur = db.execute(
        "UPDATE campaigns SET budget = ?, version = version + 1 "
        "WHERE id = ? AND version = ?",
        (budget, cid, expected_version),
    )
    return cur.rowcount == 1

ada_saw = lin_saw = 1                       # both loaded version 1
print("Ada saves:", update_budget(1, 650, ada_saw))
print("Lin saves:", update_budget(1, 400, lin_saw))
print(db.execute("SELECT budget, version FROM campaigns").fetchone())
In the lesson you can change this and run it.

Ada's update matched (version 1) and bumped the version to 2. Lin's update still said "version 1", so it matched nothing and rowcount was 0. The API would answer 412, and Lin reloads, sees Ada's change, and decides again. Nothing is silently lost.

Quick check
What does this print?
row = {"version": 4}
client_version = 3
print("updated" if client_version == row["version"] else "conflict")
  1. updated
  2. 4
  3. 3
  4. conflict
Show the answer

conflict

3 isn't equal to 4, so it prints conflict. Someone else changed the row since this client read it, so the update is refused.

Drill

Does If-Match still match?

An ETag like "cmp_9-3" names one version of a record. Write etag(record): return '"ID-VERSION"' (with the double quotes). Then write if_match_ok(header, record): True if the header is *, or if any of its comma-separated tags equals the record's current ETag; False otherwise.

Uses the setup above, 3 lines.

def etag(record):
    return record["id"]


def if_match_ok(header, record):
    return True


campaign = {"id": "cmp_9", "version": 3, "name": "Spring sale"}
print(etag(campaign), if_match_ok('"cmp_9-2"', campaign))
In the lesson, your code is checked as you write it.

Practical details

  • Timestamps: store created_at and updated_at in UTC as ISO 8601 text (2026-10-30T14:05:00Z). Convert to local time only when showing it to a person.
  • Transactions: an operation that touches several rows, such as creating an order and lowering stock, goes in one transaction. It's like a bank transfer: both halves happen, or neither does. A failure halfway leaves nothing behind.
  • Soft delete: many APIs set deleted_at instead of removing the row, like moving a file to the trash. Mistakes can be undone and history survives. Every query then has to skip deleted rows, so it's a trade-off.
  • Store time in UTC, as above, so one wall-clock time can't mean two moments when the clocks change.
  • Return the new state: after a create or update, return the full resource, with its new ETag. That saves the client a second request.
Quick check
Creating an order and lowering its stock are two writes in one transaction. The server crashes between them. What's in the database?
  1. Neither: no order, and the stock unchanged
  2. The lowered stock, with no order
  3. Both changes
  4. The order, with the stock not lowered
Show the answer

Neither: no order, and the stock unchanged

A transaction is all or nothing, like a bank transfer. A crash before it commits leaves nothing behind.

Mapping database errors to useful answers

When a unique constraint fails, the database raises an error. Left alone, that becomes a 500, telling the client your server broke. It didn't. They tried to use an email address that's already taken. Catch that specific error and return a 409 with a clear message. The constraint is still what keeps your data correct, since checking first and inserting after leaves a gap that two requests can slip through together.

Drill

Database errors as useful answers

Write db_error_to_http(message) for SQLite error messages: UNIQUE constraint failed: TABLE.COLUMN becomes (409, "COLUMN already exists"); NOT NULL constraint failed: TABLE.COLUMN becomes (422, "COLUMN is required"); FOREIGN KEY constraint failed becomes (422, "refers to something that doesn't exist"); anything else is (500, "Internal server error").

Uses the setup above, 3 lines.

def db_error_to_http(message):
    return 500, message


print(db_error_to_http("UNIQUE constraint failed: campaigns.slug"))
In the lesson, your code is checked as you write it.
In your own words
Why must column names come from an allowlist, and how do database outcomes map to status codes?

Write a sentence or two, then compare it with a good answer in the lesson.

In AI and ML systems: versions on prompts and eval records

Prompts, eval sets and experiment records are edited by several people and read by running systems, so they are exactly the rows lost updates damage: two engineers tune the same prompt, and the later save silently erases the earlier fix. Give them a version and an ETag, and refuse a stale save with 412. The practice API does it for prompt templates, so you can watch it from Python.

Worked example

A lost update on the practice API's prompts

Two editors read the same prompt. One saves. The other's save, made from the old ETag, is refused. A save with no If-Match at all is refused too.

Uses the setup above, 3 lines.

url = f"{BASE}/v1/prompts/support-reply"
requests.post(f"{BASE}/v1/reset")

ada = requests.get(url)
lin = requests.get(url)
first = requests.put(url, json={"text": "Hi, how can we help?"},
                     headers={"If-Match": ada.headers["ETag"]})
stale = requests.put(url, json={"text": "Hello!"},
                     headers={"If-Match": lin.headers["ETag"]})
bare = requests.put(url, json={"text": "Hello!"})
print(first.status_code, stale.status_code, bare.status_code)
print(sorted(stale.json()))
In the lesson you can change this and run it.

Ada's save matched the current ETag and succeeded. Lin's carried the old one, so it was refused with 412, and the body names the current version so Lin can reload. A save with no If-Match got 428.

Where this shows up in an engineer's week

Three reviews recur. "Where is the version?" Any table that people or jobs both write needs one. "Why is this key pasted into the SQL?" The column names must come from an allowlist, and an ORM or a query builder does that for you. "Why is this a 500?" A unique clash is a 409, and the client should be able to branch on it. For a service that stores prompts and eval records, a version on each row and an ETag on each read means that two people tuning the same prompt never overwrite each other without being told. Goes deeper in: Project: a FastAPI service with accounts puts a database behind accounts, [[p11-experiment-tracking]] stores runs with versions, and Caches, queues and background jobs uses the same ETag idea for caches.

In your own words
Why do prompts and eval records need a version and an ETag?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 4 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 8 review cards for spaced repetition

Try a quiz question

What is a lost update?

  1. Two clients edit the same record and one's change is silently overwritten by the other's
  2. An update that fails with a 500 error, so the client has to send it again from the start
  3. A record deleted by mistake during an update, which then can't be recovered from backups
  4. An update that takes so long that the client gives up and moves on before it has finished

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 8 · about 23 hours of study

APIs

Design, build, secure and scale web APIs from first principles 27 lessons 1 free
  1. HTTP from the wire up FreeWhat really travels between client and server: bytes, headers and bodies.40 min
  2. API stylesREST, RPC, GraphQL, gRPC and streaming: what each is for.35 min
  3. Build an API server from scratchRouting, handlers and responses, with no framework.45 min
  4. A web framework, from the insideDecorators, middleware and error handling: how Flask and FastAPI work.40 min
  5. Designing a REST APIResources, methods, status codes, errors and pagination done well.45 min
  6. Validating requests with schemasCheck every request against a JSON Schema and say exactly what's wrong.45 min
  7. A database-backed APICRUD endpoints on SQLite, with safe concurrent updates.45 min
  8. Authentication and authorizationAPI keys, sessions, tokens and OAuth: who's calling, and what may they do?45 min
  9. Rate limits, retries and idempotencyKeep an API up under load and make retries safe.45 min
  10. Async HTTP clientsMany requests at once with asyncio and httpx: limits, timeouts and retries.45 min
  11. Webhooks and eventsPush events to other systems: signed, retried and deduplicated.45 min
  12. Documenting APIs with OpenAPIA machine-readable contract for docs, SDKs and AI tools.40 min
  13. Running APIs in productionVersioning, CORS, caching, request ids and health checks.45 min
  14. Project: a reviews APIAn authenticated, validated, paginated API with tests.45 min
  15. Web pages with FlaskRoutes, Jinja templates, a shared layout, links and error pages, tested with the test client.45 min
  16. Forms and redirectsGET and POST, validation messages, post/redirect/get, flash messages and CSRF tokens.45 min
  17. Accounts and loginsPassword hashing with bcrypt, sessions, pages that need a login, and safe logout.45 min
  18. Project: a trail log web appA multi-page app with a database, accounts, forms and tests.45 min
  19. JavaScript for Python programmersVariables, functions, arrays and objects mapped from Python, and the traps: truthy empty arrays, for...in and string sort.35 min
  20. Async JavaScript: promises, await and fetchThe event loop, async and await, fetch with res.ok checks, Promise.all, and timeouts with AbortController.35 min
  21. Modules, Node and reading TypeScriptimport and export, package.json, classes, and types as notes the compiler checks, read through a small tool server.30 min
  22. A chat front end in the browserThe DOM and events, model text kept out of innerHTML, a streamed reply parsed from server-sent events, and a Stop button.40 min
  23. APIs with FastAPITyped routes, pydantic models, automatic validation and docs, tested with httpx.45 min
  24. Streaming from the serverServer-sent events written by a server: an ASGI app that sends a body in pieces, FastAPI's StreamingResponse, heartbeats, and what a closed connection looks like.40 min
  25. Project: a FastAPI service with accountsA session per request, bcrypt sign-ups, signed tokens, ownership checks and tests on a fresh database.45 min
  26. Serving a model behind FastAPILoad once with lifespan, a typed predict route, a batch route, a cap on work in flight, 429 with Retry-After, a readiness route and a 202 job.45 min
  27. Capstone: a streaming chat serviceA FastAPI service with key auth, a per-user bucket, a token budget, request ids and an event-stream reply, tested on fresh state.45 min
Part of a free course 127 lessons

Free Python developer course

Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.

Part of a free course 20 lessons

Build and Operate HTTP APIs

Design, test, deploy, and operate an HTTP API that another engineer can use.

Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write