Skip to content

FastAPI

How a FastAPI app embeds droplets: a route fetches each fragment with httpx and a Jinja template prints it into the page.

# 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() sends GET /droplets/<id>?<params> to SHOP_INTERNAL_URL with accept: text/html and x-droplet-location set to SHOP_ORIGIN, the origin of SHOP_PUBLIC_URL. It passes on the browser’s Cookie cut down to the shop’s own cart_id and shop_admin, and the page’s URL as referer: SHOP_ORIGIN plus the path and query as the browser sent them (_raw_target() reads raw_path and query_string from 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 (a CookieJar that accepts no domain). render sends the fragments’ Set-Cookie with the page; a fragment’s redirect answers the whole page with that status and location.
  • Only a text/html answer (a 2xx, or a 500 carrying the droplet’s error page) becomes Markup, which Jinja prints unescaped.
  • templates/shop/layout.html loads /index.js once. One handler, proxy, passes /index.js, /env.js, /index.css, /droplets/*, /assets/* and /api/* on to the shop.

The shop demo on FastAPI, recorded by the end-to-end test. How the pieces fit has the diagram.

The shop flow on FastAPI, recorded by the end-to-end test.
  • The gallery, on FastAPIThe gallery
  • A product in the cart, on FastAPIA product in the cart
  • The admin: stock set to 0, on FastAPIThe admin: stock set to 0
  • The product page: out of stock, on FastAPIThe product page: out of stock

The shop flow on FastAPI

The code is examples/hosts/fastapi/shop.py (a router main.py includes) and the Jinja templates in templates/shop/.

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

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.

shop.py
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.

  • The shared httpx client must not keep cookies. Its default jar would store the first visitor’s cart_id (or admin session) from a proxied answer and send it with everyone else’s requests. The client gets a CookieJar that accepts no domain; what goes out is the browser’s own Cookie, cut down to cart_id and shop_admin.
  • Markup only for the shop’s HTML. Jinja escapes everything else; the “unavailable” note is built with Markup.format, so the droplet’s id is escaped. See For hosts.
  • The page is private, no-store. render sets it on every shop page and redirect: their fragments were rendered with the visitor’s cookies.
Terminal window
cd examples/hosts/fastapi
docker compose up --build
open http://localhost:8001/gallery # log in as admin / droplets

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