Skip to content

Python SDK Integration

The ConfigBee Python Server Side SDK is a lightweight library that allows you to integrate feature flags and dynamic configurations into your Python applications with real-time updates and async support.

Installation

You can install the ConfigBee Python SDK using pip or uv.

Terminal window
pip install configbee-server-sdk

Initialization

Initialize the ConfigBee client with your account details:

import configbee
# Initialize client
client = configbee.get_client(
account_id="YOUR_ACCOUNT_ID",
project_id="YOUR_PROJECT_ID",
environment_id="YOUR_ENVIRONMENT_ID"
)
# Wait for initial load
client.wait_to_load()
# Your application is now ready to use ConfigBee
print("ConfigBee is ready!")

Async Initialization

For async applications, use the async initialization pattern:

import asyncio
import configbee
async def main():
client = configbee.get_client(
account_id="YOUR_ACCOUNT_ID",
project_id="YOUR_PROJECT_ID",
environment_id="YOUR_ENVIRONMENT_ID"
)
# Wait for initial load (async)
await client.await_to_load()
print("ConfigBee is ready!")
asyncio.run(main())

Core Features

Feature Flags (Boolean Values)

Feature flags let you enable or disable features without code deployments.

# Check if a specific feature is enabled
is_feature_enabled = client.get_flag('new_feature')
if is_feature_enabled:
# Show new feature
print("New feature is enabled!")
else:
# Show original feature
print("Using original feature")
# Get all feature flags
all_flags = client.get_all_flags()
print(all_flags) # {"feature1": True, "feature2": False, ...}

Number Configuration

Use number configurations for thresholds, limits, timeouts, and numeric values.

# Get a specific number configuration
item_limit = client.get_number('item_limit')
print(f"User can add up to {item_limit} items")
# Get request timeout
timeout = client.get_number('request_timeout')
# Get all number configurations
all_numbers = client.get_all_numbers()
print(all_numbers) # {"item_limit": 10, "retry_count": 3, ...}

Text Configuration

Text configurations are useful for messages, API endpoints, labels, and string values.

# Get a specific text configuration
api_endpoint = client.get_text('api_endpoint')
print(f"API endpoint: {api_endpoint}")
# Get welcome message
welcome_message = client.get_text('welcome_message')
# Get all text configurations
all_texts = client.get_all_texts()
print(all_texts) # {"welcome_message": "Welcome!", "api_endpoint": "https://api.example.com", ...}

JSON Configuration

JSON configurations provide structured data for complex settings.

# Get a specific JSON configuration
app_config = client.get_json('app_config')
print(app_config['theme']) # "dark"
# Get user preferences
user_preferences = client.get_json('user_preferences')
# Get all JSON configurations
all_jsons = client.get_all_jsons()
print(all_jsons) # {"app_config": {...}, "user_preferences": {...}, ...}

Advanced Features

Custom Logging

Configure custom logging for better debugging and monitoring:

import logging
import configbee
# Create custom logger
logger = logging.getLogger("my_app.configbee")
logger.setLevel(logging.DEBUG)
client = configbee.get_client(
account_id="YOUR_ACCOUNT_ID",
project_id="YOUR_PROJECT_ID",
environment_id="YOUR_ENVIRONMENT_ID",
logger=logger
)

Multiple Environments

Manage configurations across different environments:

import configbee
# Development environment
dev_client = configbee.get_client("account", "project", "dev")
# Production environment
prod_client = configbee.get_client("account", "project", "prod")
# Clients are automatically cached and reused

Real-time Updates

ConfigBee automatically receives real-time updates with live streaming. Your configuration values will be updated automatically without any additional code:

import time
import configbee
client = configbee.get_client("account", "project", "env")
client.wait_to_load()
# This will automatically reflect updates made in ConfigBee dashboard
while True:
current_limit = client.get_number("rate_limit")
print(f"Current rate limit: {current_limit}")
time.sleep(5)

Framework Integration

FastAPI Integration

ConfigBee works seamlessly with FastAPI applications:

from fastapi import FastAPI, HTTPException
from contextlib import asynccontextmanager
import configbee
# Global client instance
cb_client = None
@asynccontextmanager
async def lifespan(app: FastAPI):
global cb_client
# Initialize ConfigBee client on startup
cb_client = configbee.get_client(
account_id="YOUR_ACCOUNT_ID",
project_id="YOUR_PROJECT_ID",
environment_id="YOUR_ENVIRONMENT_ID"
)
# Wait for initial configuration load
await cb_client.await_to_load()
print("ConfigBee client initialized")
yield
# Cleanup on shutdown
print("Shutting down ConfigBee client")
app = FastAPI(lifespan=lifespan)
@app.get("/")
async def read_root():
# Use feature flags in your endpoints
if cb_client.get_flag("maintenance_mode"):
raise HTTPException(status_code=503, detail="Service under maintenance")
return {"message": "Hello World"}
@app.get("/config")
async def get_config():
# Return current configuration
return {
"api_version": cb_client.get_text("api_version"),
"max_requests": cb_client.get_number("max_requests"),
"features": cb_client.get_all_flags()
}

Dependency Injection Pattern

For better organization, use FastAPI’s dependency injection:

from fastapi import FastAPI, Depends, HTTPException
import configbee
cb_client = None
async def get_configbee_client():
global cb_client
if cb_client is None:
raise HTTPException(status_code=500, detail="ConfigBee client not initialized")
return cb_client
@app.get("/feature-status")
async def feature_status(client: configbee.ConfigbeeClient = Depends(get_configbee_client)):
return {
"beta_features": client.get_flag("beta_features"),
"new_ui": client.get_flag("new_ui_enabled")
}

Error Handling

The SDK includes comprehensive error handling and automatic retries:

import configbee
import logging
# Set up logging to see error details
logging.basicConfig(level=logging.INFO)
try:
client = configbee.get_client("account", "project", "environment")
client.wait_to_load(timeout=30)
# Safe configuration access
feature_enabled = client.get_flag("my_feature")
if feature_enabled is None:
print("Feature flag not found or client not ready")
except Exception as e:
print(f"ConfigBee initialization failed: {e}")

Best Practices

  1. Initialize Early: Initialize ConfigBee as early as possible in your application lifecycle.

  2. Handle Loading State: Always wait for the client to load before accessing configurations.

  3. Use Meaningful Names: Use descriptive, consistent naming conventions for your configurations.

  4. Error Handling: Always handle cases where configurations might not be available.

  5. Async Support: Use async methods in async applications for better performance.

API Reference

Client Initialization

configbee.get_client(account_id, project_id, environment_id, logger=None)

Creates or returns an existing ConfigBee client instance.

Parameters:

  • account_id (str): Your ConfigBee account ID
  • project_id (str): Your ConfigBee project ID
  • environment_id (str): Your ConfigBee environment ID
  • logger (logging.Logger, optional): Custom logger instance

Returns: ConfigbeeClient instance

Configuration Methods

get_flag(key)Optional[bool]

Retrieves a boolean feature flag value.

get_text(key)Optional[str]

Retrieves a text configuration value.

get_number(key)Optional[float]

Retrieves a numeric configuration value.

get_json(key)Optional[object]

Retrieves a JSON configuration value.

Bulk Retrieval Methods

get_all_flags()Optional[Dict[str, bool]]

Retrieves all feature flags.

get_all_texts()Optional[Dict[str, str]]

Retrieves all text configurations.

get_all_numbers()Optional[Dict[str, float]]

Retrieves all numeric configurations.

get_all_jsons()Optional[Dict[str, object]]

Retrieves all JSON configurations.

Loading Methods

wait_to_load(timeout=40)

Blocks until the client is loaded or timeout occurs.

await_to_load(timeout=40)

Async version of wait_to_load().

Status Property

statusConfigbeeStatus

Returns the current client status:

  • INITIALIZING: Client is loading initial configuration
  • ACTIVE: Client is ready and receiving updates
  • DEACTIVE: Client is inactive
  • ERROR: Client encountered an error

Configuration Types

ConfigBee supports four configuration types:

TypeMethodPython TypeUse Case
FLAGget_flag()boolFeature toggles, A/B testing
TEXTget_text()strAPI endpoints, messages
NUMBERget_number()floatTimeouts, limits, percentages
JSONget_json()objectComplex configurations

Key Features

  • 🚀 Real-time Updates: Automatic configuration updates with live streaming
  • 🔧 Multiple Data Types: Support for boolean flags, text, numbers, and JSON configurations
  • 🎯 Hyper Availability: Intelligent fallback across multiple cloud endpoints
  • 🔄 Async/Await Support: Full async support with thread-safe synchronous methods
  • 📦 Lightweight: Minimal dependencies with efficient caching
  • 🛡️ Error Handling: Robust error handling and automatic retries

Resources