From 1c11ea247a42e83dea27d14ada7e33c99a0357f1 Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:43:34 +0000 Subject: [PATCH 1/5] docs: add runnable FastAPI README example --- README.md | 66 ++++++++++++++++++++++++++++++++++++++++++ tests/test_examples.py | 38 ++++++++++++++++++++++++ 2 files changed, 104 insertions(+) diff --git a/README.md b/README.md index 2315233..1b227bb 100644 --- a/README.md +++ b/README.md @@ -46,3 +46,69 @@ Flag reads remain synchronous: do **not** await `get_flag()`. Context/check telemetry is enabled by default; use `client.bind(context, telemetry=False)` to opt out. Keep the secret key on the server, never in browser code. + +## FastAPI + +Install the SDK and web server, then set your server-side secret key: + +```bash +pip install reflag fastapi uvicorn +export REFLAG_SECRET_KEY="your-server-secret-key" +``` + +Create `app.py`: + +```python +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager + +from fastapi import FastAPI, Request + +from reflag import AsyncClient + + +@asynccontextmanager +async def lifespan(app: FastAPI) -> AsyncIterator[None]: + # One shared client per worker, initialized at startup and closed at shutdown. + async with AsyncClient() as client: + app.state.reflag = client + yield + + +app = FastAPI(lifespan=lifespan) + + +@app.get("/companies/{company_id}/dashboard") +async def dashboard(company_id: str, request: Request) -> dict[str, object]: + client: AsyncClient = request.app.state.reflag + flags = client.bind({"company": {"id": company_id}}) + + # Boolean flag; defaults to False. + enabled = flags.get_flag("new-dashboard") + + # JSON flag with an object fallback. + settings = flags.get_flag("dashboard-settings", default={"theme": "light"}) + + return { + "dashboard": "new" if enabled else "classic", + "settings": settings, + } +``` + +Start the application: + +```bash +uvicorn app:app +``` + +Then, in another terminal: + +```bash +curl http://localhost:8000/companies/company-123/dashboard +``` + +Replace the flag keys and company ID with your own. In a production application, +bind user/company IDs from your authenticated, authorized request context. + +The shared client keeps flag definitions up to date. Flag reads are local and +synchronous, so `get_flag()` does not need `await`. diff --git a/tests/test_examples.py b/tests/test_examples.py index 4f70e0a..08eec56 100644 --- a/tests/test_examples.py +++ b/tests/test_examples.py @@ -29,3 +29,41 @@ async def test_fastapi_lifespan_and_real_endpoint(monkeypatch): assert response.json() == {"enabled": False, "model": {"name": "small"}} assert module.app.state.reflag.status == "offline" assert module.app.state.reflag.status == "closed" + + +async def test_readme_fastapi_lifespan_and_endpoint(monkeypatch): + pytest.importorskip("fastapi") + monkeypatch.setenv("REFLAG_OFFLINE", "true") + readme = Path(__file__).parents[1] / "README.md" + section = readme.read_text(encoding="utf-8").split("## FastAPI\n", 1)[1] + code = section.split("```python\n", 1)[1].split("```", 1)[0] + namespace = {"__name__": "readme_fastapi_example"} + exec(compile(code, str(readme), "exec"), namespace) + app = namespace["app"] + + async with app.router.lifespan_context(app): + client = app.state.reflag + assert client.status == "offline" + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://asgi.test" + ) as http: + response = await http.get("/companies/company-123/dashboard") + assert response.status_code == 200 + assert response.json() == {"dashboard": "classic", "settings": {"theme": "light"}} + + client.set_flag_overrides( + lambda context: { + "new-dashboard": context["company"]["id"] == "company-123", + "dashboard-settings": {"theme": "dark"}, + } + ) + response = await http.get("/companies/company-123/dashboard") + assert response.status_code == 200 + assert response.json() == {"dashboard": "new", "settings": {"theme": "dark"}} + + response = await http.get("/companies/company-456/dashboard") + assert response.status_code == 200 + assert response.json() == {"dashboard": "classic", "settings": {"theme": "dark"}} + assert app.state.reflag is client + + assert client.status == "closed" From e7f59346d363533a42654b2165b016a417305bb4 Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:48:59 +0000 Subject: [PATCH 2/5] docs: improve Getting started flow --- README.md | 40 ++++++++++++++++++++++++++++------------ tests/test_examples.py | 12 ++++++++++++ 2 files changed, 40 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 1b227bb..3a106df 100644 --- a/README.md +++ b/README.md @@ -17,35 +17,51 @@ pip install reflag ## Getting started -Set your server-side secret key in the application environment: +Set your server-side secret key: ```bash export REFLAG_SECRET_KEY="your-server-secret-key" ``` +Create **one client per application worker** and reuse it across requests. Initialize +it at startup and close it at shutdown. The `with` block below represents that +application lifetime, not a single request. + ```python from reflag import Client with Client() as client: - flags = client.bind({"user": {"id": "user-123"}, "company": {"id": "company-123"}}) + flags = client.bind( + { + "user": {"id": "user-123"}, + "company": {"id": "company-123"}, + } + ) + + # Boolean flag, with False as the fallback. enabled = flags.get_flag("my-flag") + + # JSON flag, with an object as the fallback. settings = flags.get_flag("settings", default={"theme": "light"}) ``` -Omitting `default` is equivalent to `default=False` and returns a `bool`. +Replace the flag keys and IDs with your own. Use `client.bind(...)` for each request's +user/company context; it reuses the underlying client. + +Initialization loads flag definitions. Subsequent flag reads are local and in-memory. + +### Async applications -Replace the flag keys and IDs with your own. +Use `AsyncClient` with `async with` in your application's lifespan. Flag reads remain +synchronous: call `flags.get_flag(...)` without `await`. See the [FastAPI example](#fastapi) +for a complete web application. -Create and initialize **one client per application worker** at startup, reuse it -across requests, and close it at shutdown. Do not create a new client for each request -or flag check. Use `client.bind(...)` for request-specific user/company context. -Initialization loads definitions; subsequent flag reads are local and in-memory. +### Telemetry -For async applications, use `async with AsyncClient()` in the application lifespan. -Flag reads remain synchronous: do **not** await `get_flag()`. +Context and flag-check telemetry is enabled by default. To disable it for a bound +context, use `client.bind(context, telemetry=False)`. -Context/check telemetry is enabled by default; use `client.bind(context, telemetry=False)` -to opt out. Keep the secret key on the server, never in browser code. +Keep your secret key on the server, never in browser code. ## FastAPI diff --git a/tests/test_examples.py b/tests/test_examples.py index 08eec56..0658638 100644 --- a/tests/test_examples.py +++ b/tests/test_examples.py @@ -31,6 +31,18 @@ async def test_fastapi_lifespan_and_real_endpoint(monkeypatch): assert module.app.state.reflag.status == "closed" +def test_readme_getting_started_is_runnable_offline(monkeypatch): + monkeypatch.setenv("REFLAG_OFFLINE", "true") + readme = Path(__file__).parents[1] / "README.md" + section = readme.read_text(encoding="utf-8").split("## Getting started\n", 1)[1] + code = section.split("```python\n", 1)[1].split("```", 1)[0] + namespace = {"__name__": "readme_getting_started_example"} + exec(compile(code, str(readme), "exec"), namespace) + assert namespace["enabled"] is False + assert namespace["settings"] == {"theme": "light"} + assert namespace["client"].status == "closed" + + async def test_readme_fastapi_lifespan_and_endpoint(monkeypatch): pytest.importorskip("fastapi") monkeypatch.setenv("REFLAG_OFFLINE", "true") From c522bf7f64db94e28c19365055f4345302889801 Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:52:47 +0000 Subject: [PATCH 3/5] docs: remove redundant quickstart instruction --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3a106df..7def9dd 100644 --- a/README.md +++ b/README.md @@ -45,8 +45,8 @@ with Client() as client: settings = flags.get_flag("settings", default={"theme": "light"}) ``` -Replace the flag keys and IDs with your own. Use `client.bind(...)` for each request's -user/company context; it reuses the underlying client. +Use `client.bind(...)` for each request's user/company context; it reuses the +underlying client. Initialization loads flag definitions. Subsequent flag reads are local and in-memory. From 94ad517b3366913ced27e71a2ac9d9dc23bb1db1 Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:54:12 +0000 Subject: [PATCH 4/5] docs: trim FastAPI example instructions --- README.md | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/README.md b/README.md index 7def9dd..b2f951f 100644 --- a/README.md +++ b/README.md @@ -111,20 +111,5 @@ async def dashboard(company_id: str, request: Request) -> dict[str, object]: } ``` -Start the application: - -```bash -uvicorn app:app -``` - -Then, in another terminal: - -```bash -curl http://localhost:8000/companies/company-123/dashboard -``` - -Replace the flag keys and company ID with your own. In a production application, -bind user/company IDs from your authenticated, authorized request context. - The shared client keeps flag definitions up to date. Flag reads are local and synchronous, so `get_flag()` does not need `await`. From 1efaf8c98ab305444a5af63cca93c45a9743142e Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:06:39 +0000 Subject: [PATCH 5/5] test: share README example loading --- tests/test_examples.py | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/tests/test_examples.py b/tests/test_examples.py index 0658638..8f91ca2 100644 --- a/tests/test_examples.py +++ b/tests/test_examples.py @@ -1,11 +1,21 @@ import importlib.util import runpy from pathlib import Path +from typing import Any import httpx import pytest +def _load_readme_example(heading: str, module_name: str) -> dict[str, Any]: + readme = Path(__file__).parents[1] / "README.md" + section = readme.read_text(encoding="utf-8").split(f"## {heading}\n", 1)[1] + code = section.split("```python\n", 1)[1].split("```", 1)[0] + namespace: dict[str, Any] = {"__name__": module_name} + exec(compile(code, str(readme), "exec"), namespace) + return namespace + + def test_basic_example_is_runnable_offline(monkeypatch, capsys): monkeypatch.setenv("REFLAG_OFFLINE", "true") runpy.run_path(str(Path(__file__).parents[1] / "examples/basic.py"), run_name="__main__") @@ -33,11 +43,7 @@ async def test_fastapi_lifespan_and_real_endpoint(monkeypatch): def test_readme_getting_started_is_runnable_offline(monkeypatch): monkeypatch.setenv("REFLAG_OFFLINE", "true") - readme = Path(__file__).parents[1] / "README.md" - section = readme.read_text(encoding="utf-8").split("## Getting started\n", 1)[1] - code = section.split("```python\n", 1)[1].split("```", 1)[0] - namespace = {"__name__": "readme_getting_started_example"} - exec(compile(code, str(readme), "exec"), namespace) + namespace = _load_readme_example("Getting started", "readme_getting_started_example") assert namespace["enabled"] is False assert namespace["settings"] == {"theme": "light"} assert namespace["client"].status == "closed" @@ -46,11 +52,7 @@ def test_readme_getting_started_is_runnable_offline(monkeypatch): async def test_readme_fastapi_lifespan_and_endpoint(monkeypatch): pytest.importorskip("fastapi") monkeypatch.setenv("REFLAG_OFFLINE", "true") - readme = Path(__file__).parents[1] / "README.md" - section = readme.read_text(encoding="utf-8").split("## FastAPI\n", 1)[1] - code = section.split("```python\n", 1)[1].split("```", 1)[0] - namespace = {"__name__": "readme_fastapi_example"} - exec(compile(code, str(readme), "exec"), namespace) + namespace = _load_readme_example("FastAPI", "readme_fastapi_example") app = namespace["app"] async with app.router.lifespan_context(app):