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.
The server and browser code
Section titled “The server and browser code”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"].
from pathlib import Pathfrom typing import Annotated
from fastapi import ( APIRouter, Depends, HTTPException, Request, Response,)from fastapi.responses import HTMLResponsefrom fastapi.templating import Jinja2Templatesfrom pydantic import BaseModel, ConfigDictfrom sqlalchemy import select
from ..database import DbSessionfrom ..dependencies import CurrentUserDepfrom ..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 documentThe 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:
<!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:
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.
Opening the page
Section titled “Opening the page”The first action is ordinary browser navigation.
Max opens:
https://example.com/documents/101The 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: AuthorizedDocumentThe 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 documentsWHERE 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.
Rendering HTML with Jinja
Section titled “Rendering HTML with Jinja”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_startedThe 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
Building the DOM
Section titled “Building the DOM”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:
refreshStatusThere 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.
Handling a click
Section titled “Handling a click”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().
Sending the status request
Section titled “Sending the status request”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.statusUrlThe 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.
Resolving the second request
Section titled “Resolving the second request”The server receives a second HTTP request:
GET /documents/101/status HTTP/1.1Accept: application/jsonCookie: 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 documentIt returns the ORM object, while:
response_model=DocumentStatusReadlimits the outgoing data to:
id: intstatus: strThe result might be:
HTTP/1.1 200 OKContent-Type: application/jsonCache-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.
Checking the HTTP response
Section titled “Checking the HTTP response”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.
Parsing JSON
Section titled “Parsing 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.
Updating the page
Section titled “Updating the page”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: completedThere 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.
Handling failure
Section titled “Handling failure”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:
- The browser calls the registered event handler.
- JavaScript changes local loading controls.
fetch()sends an HTTP request.- FastAPI authenticates and authorizes that request.
- SQLAlchemy reads SQLite.
- FastAPI returns a small JSON response.
- JavaScript checks the HTTP status and parses the body.
- JavaScript replaces text in the DOM.
- 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.