Skip to content

11 · A Button Click, fetch(), and a Page That Updates

Our application can authenticate users, authorize document access, validate input, and store documents in SQLite. The last lesson introduced Alembic so the database structure can evolve with the application.

Now we move into the browser.

Jinja is our server-side template engine. It takes an HTML template containing expressions such as {{ review_document.title }}, combines it with Python values, and returns ordinary HTML. The browser receives that rendered HTML; it does not evaluate Jinja or receive a SQLAlchemy object. Today’s template and route show that boundary directly.

Today, a document page will display its current review status and a Refresh status button. Clicking that button will ask FastAPI for the latest status and update one line on the page.

The page will stay open. Its address will stay the same.

There are two separate HTTP exchanges:

Moment Browser requests Server returns
Opening the page GET /documents/101 HTML rendered by Jinja
Clicking the button GET /documents/101/status JSON containing the current status

Both requests go through authentication, authorization, and a database lookup. The difference is what the browser does with the response.

Let’s follow the entire interaction.


First, here is the Python code for today’s document router. It reuses our existing Document SQLAlchemy model, DbSession dependency, and authentication dependency.

For continuity, CurrentUserDep still supplies the user dictionary from our earlier lessons, so we use current_user["firm_id"].

app/routers/documents.py
from pathlib import Path
from typing import Annotated
from fastapi import (
APIRouter,
Depends,
HTTPException,
Request,
Response,
)
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel, ConfigDict
from sqlalchemy import select
from ..database import DbSession
from ..dependencies import CurrentUserDep
from ..models.documents import Document
router = APIRouter(prefix="/documents")
templates = Jinja2Templates(
directory=Path(__file__).resolve().parents[1] / "templates"
)
def get_authorized_document(
document_id: int,
current_user: CurrentUserDep,
db: DbSession,
) -> Document:
statement = select(Document).where(
Document.id == document_id,
)
if current_user["role"] != "admin":
if current_user["firm_id"] is None:
raise HTTPException(404, "Document not found")
statement = statement.where(
Document.firm_id == current_user["firm_id"],
)
document = db.scalar(statement)
if document is None:
raise HTTPException(404, "Document not found")
return document
AuthorizedDocument = Annotated[
Document,
Depends(get_authorized_document),
]
class DocumentStatusRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
status: str
@router.get("/{document_id}", response_class=HTMLResponse)
def document_page(
request: Request,
document: AuthorizedDocument,
):
return templates.TemplateResponse(
request=request,
name="documents/detail.html",
context={"review_document": document},
headers={"Cache-Control": "no-store"},
)
@router.get("/{document_id}/status", response_model=DocumentStatusRead)
def document_status(
response: Response,
document: AuthorizedDocument,
):
response.headers["Cache-Control"] = "no-store"
return document

The lookup dependency serves both endpoints. This is the database-backed version of the AuthorizedDocument idea introduced earlier.

Our document-creation service remains responsible for creating documents. Today’s operation is a straightforward authorized read, so the example keeps that lookup in the dependency.

Now the Jinja template:

app/templates/documents/detail.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{ review_document.title }}</title>
<script
src="{{ url_for('static', path='/document-status.js') }}"
defer
></script>
</head>
<body>
<h1>{{ review_document.title }}</h1>
<p>
Review status:
<strong id="review-status">
{{ review_document.status }}
</strong>
</p>
<button
id="refresh-status"
type="button"
data-status-url="{{ url_for(
'document_status',
document_id=review_document.id
) }}"
>
Refresh status
</button>
<p id="status-message" role="status"></p>
</body>
</html>

The JavaScript file contains:

app/static/document-status.js
const button = document.querySelector("#refresh-status");
const statusElement = document.querySelector("#review-status");
const messageElement = document.querySelector("#status-message");
button.addEventListener("click", refreshStatus);
async function refreshStatus() {
button.disabled = true;
messageElement.textContent = "Checking…";
try {
const response = await fetch(button.dataset.statusUrl, {
headers: {
Accept: "application/json",
},
});
if (response.status === 401) {
throw new Error("Your session expired. Please sign in again.");
}
if (response.status === 404) {
throw new Error("This document is no longer available.");
}
if (!response.ok) {
throw new Error("Could not refresh the status.");
}
const data = await response.json();
statusElement.textContent = data.status;
messageElement.textContent = "Status updated.";
} catch (error) {
messageElement.textContent =
error instanceof TypeError
? "Connection problem. Please try again."
: error.message;
} finally {
button.disabled = false;
}
}

Finally, our existing main.py makes the JavaScript file available:

from pathlib import Path
from fastapi.staticfiles import StaticFiles
app.mount(
"/static",
StaticFiles(
directory=Path(__file__).resolve().parent / "static",
),
name="static",
)

That is the whole interaction. Now we can slow it down.


The first action is ordinary browser navigation.

Max opens:

https://example.com/documents/101

The browser sends a GET request and the applicable session cookie. Session middleware reconstructs request.session, and FastAPI matches the page route.

Before calling document_page(), FastAPI resolves:

document: AuthorizedDocument

The dependency receives the document ID, authenticated user, and database session.

It starts by building a SQLAlchemy statement:

statement = select(Document).where(
Document.id == document_id,
)

Building this object does not yet query SQLite. It describes the query we intend to run.

For an ordinary user, we add the firm restriction:

statement = statement.where(
Document.firm_id == current_user["firm_id"],
)

Our existing policy allows platform administrators to access documents across firms; ordinary users remain restricted to their firm.

For Max, the resulting query is conceptually:

SELECT ...
FROM documents
WHERE id = 101
AND firm_id = 10;

Only this line executes the statement:

document = db.scalar(statement)

With select(Document), the result is the matching Document ORM object, or None if no row matches. SQLAlchemy constructs the Python object from the database result. SQLAlchemy’s ORM SELECT documentation

Notice that a missing document and another firm’s document both produce the same result: None.

That preserves our earlier authorization behavior.


Once the dependency succeeds, the page route calls:

templates.TemplateResponse(
request=request,
name="documents/detail.html",
context={"review_document": document},
headers={"Cache-Control": "no-store"},
)

The context dictionary gives the template a variable named review_document.

Jinja evaluates:

<h1>{{ review_document.title }}</h1>

on the server, producing something like:

<h1>October Homepage Review</h1>

Likewise:

{{ review_document.status }}

becomes:

not_started

The browser receives the resulting HTML. It does not receive the SQLAlchemy object or execute the Jinja expressions. This is the template-response pattern provided by FastAPI through Starlette. FastAPI templates documentation

The name review_document is intentional. Later, JavaScript will use the browser’s built-in document object. Giving our application resource a different name keeps those two meanings clear.

Jinja also escapes ordinary inserted values in this HTML template. A title containing < or > is rendered as text rather than casually becoming executable markup. Starlette enables autoescaping for HTML templates with this directory-based configuration. Starlette templates documentation


The browser now parses the HTML and builds the DOM, the Document Object Model.

The DOM is the browser’s object representation of the page: its heading, paragraphs, button, text, and their relationships. JavaScript can find and modify these objects. MDN’s DOM documentation

For example, this HTML:

<strong id="review-status">not_started</strong>

creates an element that JavaScript can access.

Meanwhile, the browser sees:

<script src="..." defer></script>

It requests our JavaScript file from /static/document-status.js.

The defer attribute allows the browser to download the script while parsing the page, then execute it after the HTML has been parsed. The button and status elements therefore exist when the script looks for them.

This also explains why serving a JavaScript file is different from executing it:

  • FastAPI’s static-file handler sends the file’s contents.
  • The browser’s JavaScript engine executes those contents.

Python does not execute the JavaScript.


The script begins with:

const button = document.querySelector("#refresh-status");

Here, document means the browser’s current page.

querySelector() finds the first element matching a CSS selector. The # means “find the element with this ID.”

Therefore:

"#refresh-status"

matches:

<button id="refresh-status">

The variable button now refers to that DOM element.

It does not contain the button’s HTML as a string. It refers to an object representing the actual button in the displayed page.

The next two lines obtain references to the status and message elements:

const statusElement = document.querySelector("#review-status");
const messageElement = document.querySelector("#status-message");

We use const because these variables will keep referring to the same objects. We can still change properties of those objects, such as their text or disabled state.


Next comes:

button.addEventListener("click", refreshStatus);

This registers a function to run when the button receives a click event. MDN’s addEventListener() documentation

Notice the function reference:

refreshStatus

There are no parentheses.

This should feel familiar from:

Depends(get_current_user)

In both cases, we supply a function for something else to call later.

Writing:

refreshStatus()

would call the function immediately while the script was loading.

After registering the listener, the script has finished its initial work. The browser waits for interaction.

At this point, no status-refresh request has occurred.


Max clicks the button.

The browser calls:

refreshStatus()

Its first two statements run immediately:

button.disabled = true;
messageElement.textContent = "Checking…";

The button becomes disabled, preventing ordinary repeated clicks while this request is pending.

The message element changes from empty text to “Checking…”.

Both changes happen locally in the browser. FastAPI has not yet received anything.

Also, the button has:

type="button"

It has no form-submission behavior. The JavaScript listener determines what happens when it is clicked.

When we introduce a form, we’ll examine its submit event and why JavaScript sometimes calls event.preventDefault().


Now execution reaches the network operation:

const response = await fetch(button.dataset.statusUrl, {
headers: {
Accept: "application/json",
},
});

The URL came from this HTML attribute:

data-status-url="https://example.com/documents/101/status"

Jinja generated it using the named route:

url_for("document_status", document_id=review_document.id)

JavaScript exposes data-status-url as:

button.dataset.statusUrl

The hyphenated HTML name becomes a camelCase JavaScript property.

Passing the URL through an HTML attribute also keeps document-specific values out of the shared JavaScript file. The same script works for document 101, 202, or any other authorized document.

fetch() uses GET by default. Its Accept header tells the server which response format the client expects. It does not force the server to return that format.

Because the URL belongs to the same origin as the page, the browser includes applicable cookies by default. MDN’s Fetch guide

JavaScript does not need to read the session cookie itself.


The await deserves a first look:

const response = await fetch(...);

fetch() returns a Promise representing an operation that will finish later.

await pauses the continuation of this particular asynchronous function until that Promise settles. While the network request is pending, the browser can continue handling other work.

This is why the page can remain responsive while the message says “Checking…”.

We’ll explore Promises and the browser’s event loop more carefully in the next installment. For today, follow the control flow: execution will resume here when the response becomes available or the operation fails.


The server receives a second HTTP request:

GET /documents/101/status HTTP/1.1
Accept: application/json
Cookie: app_session=...

FastAPI handles it independently of the earlier page request.

It authenticates the user again, creates a database session, and runs the authorization lookup again.

The fact that Max successfully opened the page five minutes ago is insufficient. His session could have expired, his firm membership could have changed, or the document could have been deleted.

This second request must stand on its own.

The endpoint eventually runs:

def document_status(
response: Response,
document: AuthorizedDocument,
):
response.headers["Cache-Control"] = "no-store"
return document

It returns the ORM object, while:

response_model=DocumentStatusRead

limits the outgoing data to:

id: int
status: str

The result might be:

HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store
{"id":101,"status":"not_started"}

The cache instruction asks browsers and intermediaries not to store this sensitive, changeable response.

No document was updated. This endpoint only reads the current state. Alembic performs no work, and the creation service is not called.

Also, this button does not start a review. Until a separate operation changes the stored status, it will keep reporting not_started.


Back in JavaScript, response is a browser Response object.

It contains the HTTP status, headers, and access to the response body.

The code first checks specific failures:

if (response.status === 401) {
throw new Error("Your session expired. Please sign in again.");
}

Then:

if (response.status === 404) {
throw new Error("This document is no longer available.");
}

Finally:

if (!response.ok) {
throw new Error("Could not refresh the status.");
}

response.ok is true for status codes from 200 through 299.

A subtle point: fetch() does not reject its Promise merely because the server returns 404 or 500. Those are HTTP responses that JavaScript must inspect. Network failures can reject the Promise directly. MDN’s Fetch error handling

Our throw statements deliberately send unsuccessful HTTP outcomes into the catch block.

For this JSON endpoint, the authentication dependency should return a 401 response when authentication fails. Redirecting it to an HTML login page would create a different problem: the fetch could follow the redirect and receive HTML where our code expects JSON.


After a successful status check, we reach:

const data = await response.json();

This reads the response body and parses its JSON into a JavaScript value. For our response, that value is an object:

{
id: 101,
status: "not_started"
}

The second await is useful because receiving the response headers and finishing the response body are separate stages. MDN’s Response.json() documentation

There are several representations of the same information:

Location Representation
SQLite A row in documents
Python A SQLAlchemy Document object
HTTP response body JSON text encoded as bytes
Browser JavaScript An object with id and status properties
Visible page Text inside the status element

No Python object travels across the network.

The server serializes values. The browser parses them into its own objects.

For the reverse direction, JavaScript uses:

JSON.stringify({
title: "October Homepage Review",
priority: 4,
})

to produce JSON text suitable for a request body. Our current GET has no body, so it does not need JSON.stringify(). We’ll use it when a form sends data to FastAPI.


The actual visible update is one line:

statusElement.textContent = data.status;

JavaScript changes the text in the existing DOM element. The browser renders the change.

If another operation has changed the database status to completed, the page now displays:

Review status: completed

There is no new HTML page response, no Jinja rerender, and no navigation.

textContent inserts text without interpreting it as HTML. That makes it appropriate for displaying data such as status labels and document titles. MDN’s textContent documentation

This is an important limit of the operation: changing the DOM does not change SQLite. A user could edit the displayed status using browser developer tools, but the stored document would remain unchanged.

Server operations must continue to rely on authenticated requests and database state.


If something fails, execution enters:

catch (error) {
...
}

The code displays either a connection message or the error message we supplied.

The existing status stays visible. We do not replace it with a misleading success state.

Then:

finally {
button.disabled = false;
}

reenables the button whether the operation succeeded or failed.

There is still a practical limitation: we have not added an application timeout. A slow request can leave the button disabled until it finishes or fails. That gives us a useful reason to introduce cancellation in the next lesson.

Today’s operation only reads data. When we add cookie-authenticated writes, the server will also need the application’s CSRF protection. Being initiated by JavaScript does not make a request inherently trustworthy.

The entire click now has a concrete sequence:

  1. The browser calls the registered event handler.
  2. JavaScript changes local loading controls.
  3. fetch() sends an HTTP request.
  4. FastAPI authenticates and authorizes that request.
  5. SQLAlchemy reads SQLite.
  6. FastAPI returns a small JSON response.
  7. JavaScript checks the HTTP status and parses the body.
  8. JavaScript replaces text in the DOM.
  9. The browser displays the result.

The initial page came from Jinja. Its later update came from JavaScript acting on a JSON response. Both used the same FastAPI application and the same authorization rule.

Next, we’ll stay with this button and examine exactly what the browser does while await is waiting, including slow responses, cancellation, and keeping the interface honest when requests overlap.