> For the complete documentation index, see [llms.txt](https://docs.reflag.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.reflag.com/supported-languages/python-sdk.md). Agents can also search and read this documentation through its [MCP server](https://docs.reflag.com/~gitbook/mcp).

# Python SDK

Use Reflag feature flags in Python applications.

Typed, server-side Boolean and JSON feature flags.

Remote config is not supported by this SDK. Use multivariate flags for configuration values instead.

## Installation

Install from PyPI:

```bash
pip install reflag
```

## Support

* Python **3.11+**, including tested Python **3.14**.
* Works with synchronous and async applications, including FastAPI.

## Getting started

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"},
        }
    )

    # 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"})
```

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

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.

### Telemetry

Context and flag-check telemetry is enabled by default. To disable it for a bound context, use `client.bind(context, telemetry=False)`.

Keep your 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,
    }
```

The shared client keeps flag definitions up to date. Flag reads are local and synchronous, so `get_flag()` does not need `await`.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.reflag.com/supported-languages/python-sdk.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
