Skip to main content

Evaluate Flaggr feature flags from Python with Flaggr's Python SDK, or with the OpenFeature SDK and its OFREP provider

Last updated November 14, 2026

Python SDK

There are two ways to evaluate Flaggr flags from Python:

You can also call the REST API directly.

Installation

The SDK isn't on PyPI yet, so install its v0.1.1 release tag from GitHub:

pip install "flaggr @ git+https://github.com/flaggr-dev/flaggr-python@v0.1.1"

It needs Python 3.9 or later and depends only on httpx. Each release also has the wheel and the source distribution attached.

Quick Start

import os
 
from flaggr import FlaggrClient
 
client = FlaggrClient(
    api_key=os.environ["FLAGGR_TOKEN"],          # a project API token (fgr_...)
    service_id=os.environ["FLAGGR_SERVICE_ID"],  # the service's ID, not its slug
    environment="production",
)
 
if client.get_boolean("checkout-v2", default=False, context={"targeting_key": "user-123"}):
    ...
 
client.close()

The client needs two values from your project:

  • A project API token (fgr_…). A read-only token is enough to evaluate flags. Personal access tokens (fgp_…) can't evaluate flags. See API Tokens.
  • The service's ID, from the service's Connection tab. Its slug or name won't work.

The client raises ValueError when api_key, service_id or environment is empty, and ignores whitespace around them. Create one client when your app starts and reuse it: it keeps a connection pool. with FlaggrClient(...) as client: closes it for you.

Environments

The client evaluates in production unless you pass environment. Each flag has its own configuration in each environment, so the same key can return different values in development, staging and production. (OFREP requests default to development instead; see below.)

Configuration

ArgumentDefaultDescription
api_keyrequiredA project API token
service_idrequiredThe ID of the service the flags belong to
environment"production"The environment to evaluate in
api_url"https://api.flaggr.dev"The API base URL, without /api
timeout5.0Seconds to wait for each request
transportNoneAn httpx transport, such as httpx.HTTPTransport(retries=2) (httpx.AsyncHTTPTransport for the async client), or httpx.MockTransport in tests

The default api_url is Flaggr's data plane. A running experiment assigns its variants only on the control plane, so to evaluate an experiment's flag, set api_url="https://flaggr.dev". The control plane accepts only string, number and boolean context values, and applies rate limits.

Evaluating Flags

Each evaluation sends one POST /api/flags/evaluate request. The client doesn't cache results.

MethodReturns
get_boolean(key, default=False, context=None)bool
get_string(key, default="", context=None)str
get_number(key, default=0, context=None)int or float
get_object(key, default=None, context=None)dict ({} when the default is None)
resolve_boolean, resolve_string, resolve_number, resolve_objectEvaluationDetail

default and context are keyword arguments. You get default back when the flag doesn't exist in that service and environment, or when its value doesn't have the type you asked for.

The resolve_* methods return the value with the reason the API gave for it:

detail = client.resolve_string(
    "checkout-flow-version", default="v1", context={"targeting_key": "user-123"}
)
 
detail.value          # the value for this context, or the default
detail.reason         # "TARGETING_MATCH", "DEFAULT", "DISABLED", "VARIANT", ...
detail.variant        # the variant's name, or ""
detail.error_code     # None, "FLAG_NOT_FOUND" or "TYPE_MISMATCH"
detail.error_message  # why error_code is set

Evaluation Context

The context is a dict of the attributes your targeting rules match on. targeting_key identifies the user or entity: percentage rollouts, variant splits and overrides use it. It's sent as targetingKey, converted to a string. Other attributes should be strings, numbers or booleans; attributes set to None are left out.

client.get_number(
    "discount-percentage",
    default=0,
    context={
        "targeting_key": "user-456",
        "country": "AU",
        "plan": "enterprise",
        "beta_tester": True,
    },
)

Async

AsyncFlaggrClient has the same methods, as coroutines:

import asyncio
import os
 
from flaggr import AsyncFlaggrClient
 
 
async def main() -> None:
    async with AsyncFlaggrClient(
        api_key=os.environ["FLAGGR_TOKEN"],
        service_id=os.environ["FLAGGR_SERVICE_ID"],
    ) as client:
        theme = await client.get_string("app-theme", default="light")
        print(theme)
 
 
asyncio.run(main())

Error Handling

A missing flag isn't an error: you get the default, and resolve_* sets error_code to FLAG_NOT_FOUND. A request that fails raises FlaggrError: a network error, a refused token (401 or 403), rate limiting (429) or a server error. Timeouts raise FlaggrTimeoutError, a subclass. status_code holds the HTTP status, or None when no response arrived.

from flaggr import FlaggrError, FlaggrTimeoutError
 
try:
    enabled = client.get_boolean("checkout-v2", default=False)
except FlaggrTimeoutError:
    enabled = False
except FlaggrError as exc:
    print(f"Flag evaluation failed (HTTP {exc.status_code}): {exc}")
    enabled = False

A 401 or 403 can also mean the service ID is wrong: Flaggr answers the same for a service that doesn't exist and one the token can't read.

Framework Integration

Create the client once at startup, then evaluate wherever you need a flag.

Django

# yourapp/flags.py
import os
 
from flaggr import FlaggrClient
 
flags = FlaggrClient(
    api_key=os.environ["FLAGGR_TOKEN"],
    service_id=os.environ["FLAGGR_SERVICE_ID"],
    environment=os.environ.get("FLAGGR_ENV", "production"),
)
 
# yourapp/views.py
from django.shortcuts import render
from flaggr import FlaggrError
 
from yourapp.flags import flags
 
def checkout_view(request):
    context = {"targeting_key": str(request.user.id), "plan": request.user.profile.plan}
    try:
        use_v2 = flags.get_boolean("checkout-v2", default=False, context=context)
    except FlaggrError:
        use_v2 = False
    return render(request, "checkout_v2.html" if use_v2 else "checkout.html")

FastAPI

Use AsyncFlaggrClient, so evaluations don't block the event loop:

import os
from contextlib import asynccontextmanager
 
from fastapi import FastAPI, Request
from flaggr import AsyncFlaggrClient, FlaggrError
 
@asynccontextmanager
async def lifespan(app: FastAPI):
    async with AsyncFlaggrClient(
        api_key=os.environ["FLAGGR_TOKEN"],
        service_id=os.environ["FLAGGR_SERVICE_ID"],
        environment="production",
    ) as flags:
        app.state.flags = flags
        yield
 
app = FastAPI(lifespan=lifespan)
 
@app.get("/checkout")
async def checkout(request: Request, user_id: str):
    try:
        use_v2 = await request.app.state.flags.get_boolean(
            "checkout-v2", default=False, context={"targeting_key": user_id}
        )
    except FlaggrError:
        use_v2 = False
    return {"version": "v2" if use_v2 else "v1"}

OpenFeature (OFREP)

The OpenFeature Python SDK evaluates Flaggr flags through its OFREP provider.

Install the SDK and provider

pip install openfeature-sdk openfeature-provider-ofrep

Configure the provider

import os
from openfeature import api
from openfeature.contrib.provider.ofrep import OFREPProvider
from openfeature.evaluation_context import EvaluationContext
 
api.set_provider(OFREPProvider(
    "https://api.flaggr.dev/api",
    headers_factory=lambda: {
        "Authorization": f"Bearer {os.environ['FLAGGR_TOKEN']}",
        "X-Service-Id": os.environ["FLAGGR_SERVICE_ID"],
        "X-Environment": os.environ.get("FLAGGR_ENV", "production"),
    },
))
client = api.get_client()
enabled = client.get_boolean_value("checkout-v2", False, EvaluationContext("user-123"))

Three settings connect the provider to Flaggr:

  • Base URL https://api.flaggr.dev/api. The provider appends /ofrep/v1/evaluate/flags/{key} itself, so a base URL ending in /ofrep or /ofrep/v1 returns 404.
  • headers_factory returns the headers for every request: the API token as a bearer token, X-Service-Id naming your service and X-Environment choosing the environment. Without X-Environment, flags evaluate in development. The provider has no headers= argument.
  • The token comes from the environment (FLAGGR_TOKEN here). A read-only project API token is enough to evaluate flags.

Evaluate with OpenFeature

from openfeature import api
from openfeature.evaluation_context import EvaluationContext
 
client = api.get_client()
ctx = EvaluationContext(
    targeting_key="user-123",
    attributes={"plan": "enterprise", "country": "AU"},
)
 
is_enabled = client.get_boolean_value("checkout-v2", False, ctx)
theme = client.get_string_value("app-theme", "light", ctx)
max_retries = client.get_integer_value("max-retries", 3, ctx)
sample_rate = client.get_float_value("sample-rate", 0.25, ctx)
banner = client.get_object_value("promo-banner", {"text": "", "color": "blue"}, ctx)

Each evaluation is one HTTP request to Flaggr's data plane. The provider doesn't cache results.

The *_details methods return the value along with the reason, the variant and any error:

details = client.get_boolean_details("checkout-v2", False, ctx)
 
print(f"Value: {details.value}")
print(f"Reason: {details.reason}")      # TARGETING_MATCH, DEFAULT, DISABLED, ...
print(f"Variant: {details.variant}")
print(f"Error code: {details.error_code}")
print(f"Error message: {details.error_message}")

Attributes that apply to every evaluation can be set once, globally. They merge with the context passed to each call:

api.set_evaluation_context(EvaluationContext(attributes={"region": "ap-southeast-2"}))

OpenFeature evaluation doesn't raise. If the flag doesn't exist, the token is rejected or Flaggr can't be reached, you get the default value back, and the *_details methods say why. The provider waits up to 5 seconds for each request; pass timeout= (in seconds) to OFREPProvider to change it. When Flaggr answers 429 Too Many Requests, the provider returns defaults until the Retry-After time has passed.

The provider makes blocking HTTP requests: in FastAPI, evaluate in plain def routes, which FastAPI runs in a worker thread.

REST API Direct Usage

To call the REST API without an SDK:

import os
 
import requests
 
response = requests.post(
    "https://api.flaggr.dev/api/flags/evaluate",
    headers={
        "Authorization": f"Bearer {os.environ['FLAGGR_TOKEN']}",
        "Content-Type": "application/json",
    },
    json={
        "flagKey": "checkout-v2",
        "serviceId": os.environ["FLAGGR_SERVICE_ID"],
        "environment": "production",
        "defaultValue": False,
        "context": {
            "targetingKey": "user-123",
            "plan": "enterprise",
        },
    },
)
 
result = response.json()
print(f"Value: {result['value']}, Reason: {result['reason']}")