Evaluate a feature flag for a user using the LaunchDarkly API
Prerequisite You should have a LaunchDarkly account and have created a feature flag called dark-mode that allows anyone with example.com email address to true, and everyone else to false. Ensure you have an API key from LaunchDarkly and have it stored in a .env file.
This guide demonstrates how to evaluate a feature flag for a user using the LaunchDarkly API. You’ll learn how to set up your environment, configure your API key, and evaluate a feature flag.
launchdarkly-feature-flag.py
import osimport ldclientfrom ldclient.config import Configfrom ldclient.context import Contextfrom dotenv import load_dotenv# Load environment variables from .env fileload_dotenv()defevaluate_flag(sdk_key, feature_flag_key, user_email):# Initialize LaunchDarkly client ldclient.set_config(Config(sdk_key))# Specify the user and email to LaunchDarkly as a Context context = Context.builder(user_email).kind('user').set("email", user_email).build()# Obtain the feature flag evaluated value flag_value = ldclient.get().variation(feature_flag_key, context,False)# Close the LaunchDarkly client ldclient.get().close()return flag_value# Example usageif __name__ =="__main__": sdk_key = os.getenv("LAUNCHDARKLY_API_KEY") feature_flag_key ="dark-mode" user_email ="hello@example.com" flag_status = evaluate_flag(sdk_key, feature_flag_key, user_email)print(f"Feature flag '{feature_flag_key}' for user '{user_email}': {flag_status}")
Create a Python script named launchdarkly-feature-flag.py with the following content:
launchdarkly-feature-flag.py
import osimport ldclientfrom ldclient.config import Configfrom ldclient.context import Contextfrom dotenv import load_dotenv# Load environment variables from .env fileload_dotenv()defevaluate_flag(sdk_key, feature_flag_key, user_email):# Initialize LaunchDarkly client ldclient.set_config(Config(sdk_key))# Specify the user and email to LaunchDarkly as a Context context = Context.builder(user_email).kind('user').set("email", user_email).build()# Obtain the feature flag evaluated value flag_value = ldclient.get().variation(feature_flag_key, context,False)# Close the LaunchDarkly client ldclient.get().close()return flag_value# Example usageif __name__ =="__main__": sdk_key = os.getenv("LAUNCHDARKLY_API_KEY") feature_flag_key ="dark-mode" user_email ="hello@example.com" flag_status = evaluate_flag(sdk_key, feature_flag_key, user_email)print(f"Feature flag '{feature_flag_key}' for user '{user_email}': {flag_status}")
You have successfully evaluated a feature flag for a user using the LaunchDarkly API! This guide provided a basic example to get you started. You can now expand on this by customizing the feature flag evaluation and handling different user contexts.