FastAPI
How a FastAPI app embeds droplets: a route fetches each fragment with httpx
and a Jinja template prints it into the page.
The pattern in FastAPI
Section titled “The pattern in FastAPI”# shop.py (trimmed)client = httpx.AsyncClient( timeout=10.0, follow_redirects=False, cookies=CookieJar(policy=DefaultCookiePolicy(allowed_domains=[])),)
async def fragment(request: Request, droplet: str, params: list[tuple[str, str]] | None = None) -> dict: url = f"{SHOP_INTERNAL_URL}/droplets/{quote(droplet, safe='')}?{urlencode(params or [])}" headers = {"accept": "text/html", "x-droplet-location": SHOP_ORIGIN, "referer": SHOP_ORIGIN + _raw_target(request)} cookie = _shop_cookies(request) if cookie: headers["cookie"] = cookie result = {"html": Markup(""), "status": 502, "location": None, "cookies": [], "link": None} response = await client.get(url, headers=headers) result["status"] = response.status_code result["cookies"] = response.headers.get_list("set-cookie") content_type = response.headers.get("content-type", "") if 300 <= response.status_code < 400: result["location"] = response.headers.get("location") elif (response.is_success or response.status_code == 500) and content_type.startswith("text/html"): result["html"] = Markup(response.text) return result # … anything else: result["html"] becomes a "droplet is unavailable" note return result{# templates/shop/layout.html, in <head>: once per page #}<script type="module" src="/index.js"></script>{# templates/shop/gallery.html: the fragment's HTML, as it came #}<aside>{{ fragments[0] }}</aside>fragment()sendsGET /droplets/<id>?<params>toSHOP_INTERNAL_URLwithaccept: text/htmlandx-droplet-locationset toSHOP_ORIGIN, the origin ofSHOP_PUBLIC_URL. It passes on the browser’sCookiecut down to the shop’s owncart_idandshop_admin, and the page’s URL asreferer:SHOP_ORIGINplus the path and query as the browser sent them (_raw_target()readsraw_pathandquery_stringfrom the ASGI scope).- The shared client never follows a redirect (
follow_redirects=False), so a droplet’s 3xx is answered as it is, and never keeps a cookie (aCookieJarthat accepts no domain).rendersends the fragments’Set-Cookiewith the page; a fragment’s redirect answers the whole page with that status andlocation. - Only a
text/htmlanswer (a 2xx, or a 500 carrying the droplet’s error page) becomesMarkup, which Jinja prints unescaped. templates/shop/layout.htmlloads/index.jsonce. One handler,proxy, passes/index.js,/env.js,/index.css,/droplets/*,/assets/*and/api/*on to the shop.
The shop demo, recorded
Section titled “The shop demo, recorded”The shop demo on FastAPI, recorded by the end-to-end test. How the pieces fit has the diagram.
The code is examples/hosts/fastapi/shop.py (a router main.py includes)
and the Jinja templates in templates/shop/.
Pieces and ports
Section titled “Pieces and ports”docker-compose.yml starts three services:
| Service | Port | What it is |
|---|---|---|
web |
8001, public | FastAPI: the shop’s pages, the proxy, and the basic page at / |
shop |
8300, internal only | the shop’s droplets server (examples/shop) |
droplets |
8000, public | the Svelte example’s droplets server, for / only |
On web |
Value | Used for |
|---|---|---|
SHOP_INTERNAL_URL |
http://shop:8300 |
internal: fragment fetches and the proxy |
SHOP_PUBLIC_URL |
http://localhost:8001 |
public: this host’s own origin, sent as x-droplet-location |
DROPLETS_INTERNAL_URL, DROPLETS_PUBLIC_URL |
http://droplets:8000, http://localhost:8000 |
the same pair, for the basic page |
How a page gets a droplet
Section titled “How a page gets a droplet”A server fetch with httpx, all of a page’s fragments at once
(asyncio.gather), printed by a Jinja template. The fetch is fragment()
and the template is templates/shop/gallery.html, both shown in the pattern
above; the fragments’ Link preloads go into <head>.
referer is the page’s URL, query included. The shop’s handle reads it
with hostFrom, so it is the droplet’s
host, and after
a form posted without JavaScript its query carries the form’s result.
templates/shop/layout.html loads <script type="module" src="/index.js">
once, through the proxy, and each droplet hydrates itself. render fetches
the toasts and the header’s cart badge with every page’s fragments
(asyncio.gather); the toast-center fragment comes first in the body, and
/index.js installs window.shopMessageQueue before any droplet starts (the
shop’s src/hooks.client.ts):
{# templates/shop/layout.html #}<body class="shop">{{ toasts }}<header class="shop-header">…<div class="shop-cart">{{ cart }}</div>…</header>The product page first reads the product from the shop’s public
GET /droplets/product-page/_data?slug=<slug>; an unknown slug answers the
not-found template with 404. The pages pass on only the query keys
each droplet takes: the whole query to product-filter and
product-library, order, page and showing (plus productId) to
product-comments, slug and v to product-page, next to login,
view and id to product-admin.
What it proxies
Section titled “What it proxies”METHODS = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]
@router.api_route("/index.js", methods=METHODS, include_in_schema=False)@router.api_route("/env.js", methods=METHODS, include_in_schema=False)@router.api_route("/index.css", methods=METHODS, include_in_schema=False)@router.api_route("/droplets/{rest:path}", methods=METHODS, include_in_schema=False)@router.api_route("/assets/{rest:path}", methods=METHODS, include_in_schema=False)@router.api_route("/api/{rest:path}", methods=METHODS, include_in_schema=False)async def proxy(request: Request) -> Response: headers = {"x-droplet-location": SHOP_ORIGIN} …proxy covers /index.js, /env.js, /index.css, /droplets/* (fragments, _data, form
actions), /assets/* and /api/*. It sends the shop x-droplet-location
written out and only these of the browser’s headers: accept,
accept-language, content-type, if-none-match, origin, referer,
user-agent, x-droplet-props and x-droplets-build, plus cookie cut
down to the shop’s own cart_id and shop_admin, so another app’s cookie
on this origin stays here. The target is the raw path and query
concatenated onto SHOP_INTERNAL_URL, never resolved, so //elsewhere stays
a path on the shop; a path with a . or .. segment, once decoded, is
refused with 400. The request body and the
answer are streamed (client.send(…, stream=True) into a
StreamingResponse); the answer keeps its status, every Set-Cookie and
any redirect, without connection, keep-alive, transfer-encoding,
content-encoding and content-length, which no longer hold once httpx has
decoded the body. A shop that cannot be reached answers 502
The shop is unreachable.
The shop’s cookies (cart_id, shop_admin) are first-party, and nothing
is cross-origin; the shop sets them only from form actions and /api,
which come through here.
Gotchas
Section titled “Gotchas”- The shared
httpxclient must not keep cookies. Its default jar would store the first visitor’scart_id(or admin session) from a proxied answer and send it with everyone else’s requests. The client gets aCookieJarthat accepts no domain; what goes out is the browser’s ownCookie, cut down tocart_idandshop_admin. Markuponly for the shop’s HTML. Jinja escapes everything else; the “unavailable” note is built withMarkup.format, so the droplet’s id is escaped. See For hosts.- The page is
private, no-store.rendersets it on every shop page and redirect: their fragments were rendered with the visitor’s cookies.
Run it
Section titled “Run it”cd examples/hosts/fastapidocker compose up --buildopen http://localhost:8001/gallery # log in as admin / dropletsSet SHOP_SECRET and DROPLETS_SECRET first; compose refuses to start
without them. The shop trusts one origin besides its own,
DROPLETS_TRUSTED_ORIGINS: http://localhost:8001, this host’s; the rest of
its environment is the same on every host: see
Running a host.
The Svelte example
Section titled “The Svelte example”The same app serves the Svelte example at /: its three droplets, one per
mode, from examples/frameworks/svelte (the droplets service). No
JavaScript runs on the host: Python fetches the fragments and a template
prints them.
# main.py (trimmed)DROPLETS_INTERNAL_URL = os.environ.get("DROPLETS_INTERNAL_URL", "http://localhost:8000")DROPLETS_PUBLIC_URL = os.environ.get("DROPLETS_PUBLIC_URL", "http://localhost:8000")
IDS = ["client", "ssr-hydrate", "ssr-nohydrate"]
async def fetch_droplet(client: httpx.AsyncClient, droplet: str, **props: str) -> Markup: query = f"?{urlencode(props)}" if props else "" try: # Never follows a redirect (the client's default). response = await client.get( f"{DROPLETS_INTERNAL_URL}/droplets/{quote(droplet, safe='')}{query}", headers={"accept": "text/html", "x-droplet-location": DROPLETS_PUBLIC_URL}, timeout=5.0, ) except httpx.HTTPError as error: # The error names the internal URL: it goes to the log, not the page. print(f"[droplets] {droplet}: {error!r}") return Markup('<p class="error">droplet "{}" unavailable</p>').format(droplet) # Only an HTML answer is a fragment (a 500 carries the droplet's error # page); anything else may echo the props, so it is never pasted. is_html = response.headers.get("content-type", "").startswith("text/html") if (response.is_success or response.status_code == 500) and is_html: return Markup(response.text) return Markup('<p class="error">droplet "{}" unavailable: HTTP {}</p>').format(droplet, response.status_code)
@app.get("/", response_class=HTMLResponse)async def index(request: Request, who: str = "FastAPI") -> HTMLResponse: async with httpx.AsyncClient() as client: fragments = await asyncio.gather( *(fetch_droplet(client, droplet, who=who) for droplet in IDS) ) return templates.TemplateResponse(request, "index.html", { "droplets_public_url": DROPLETS_PUBLIC_URL, "fragments": fragments, }){# templates/index.html #}<script type="module" src="{{ droplets_public_url }}/index.js"></script>…{% for fragment in fragments %} {{ fragment }}{% endfor %}Markup marks the fragment as safe, so Jinja does not escape it. Only a
text/html answer is pasted (a 2xx, or a 500 carrying the droplet’s error
page); any other answer prints an error paragraph with its status, built
with Markup.format so the id is escaped. A failed request
(httpx.HTTPError) prints a fixed one and logs the error, since its message
names the internal URL. Here the page loads /index.js from the droplets
server’s public URL, another origin than the page, so the Svelte example
runs with cors: true and DROPLETS_TRUSTED_ORIGINS lists both
DROPLETS_URL and this host’s WEB_URL. The same fetch works from Flask,
Django or any other Python server that can make an HTTP request and print a
string.



