Project: Flagsmith (Observability and Analysis / Feature Flagging)
File: locally-api.md

sidebar_label: API title: Flagsmith REST API sidebar_position: 10 Before running the application, you'll need to configure a database for the application. The steps to do this can be found in the following section entitled 'Databases'. ```bash cd api make install make django-migrate make serve ``` You can now visit `http://<your-server-domain:8000>/api/v1/users/config/init/` to create an initial Superuser and provide DNS settings for your installation or run `make test` from the `api` directory to run the test suite. Note: if you're running on on MacOS and you find some issues installing the dependencies (specifically around pyre2), you may need to run the following: ```bash brew install cmake re2 ``` The application can also be run locally using Docker Compose if required, however, it's beneficial to run locally using the above steps as it gives you hot reloading. To run using docker compose, run the following command from the project root: ```bash curl -o docker-compose.yml https://raw.githubusercontent.com/Flagsmith/flagsmith/main/docker-compose.yml docker-compose -f docker-compose.yml up ``` Databases are configured in app/settings/\<env\>.py The app is configured to use PostgreSQL for all environments. When running locally, you'll need a local instance of postgres running. The easiest way to do this is to use docker which is achievable with the following command: `docker-compose -f docker/db.yml up -d` You'll also need to ensure that you have a value for POSTGRES_PASSWORD set as an environment variable on your development machine. When running on a Heroku-ish platform, the application reads the database connection in production from an environment variable called `DATABASE_URL`. This should be configured in the Heroku-ish application configuration. When running the application using Docker, it reads the database configuration from the settings located in `app.settings.production` The application is built using django which comes with a handy set of admin pages available at `/admin/`. To access these, you'll need to create a super user. This user can also be used to access the admin pages or the application itself if you have the frontend application running as well. This user can be created using the instructions below dependent on your installation: ```bash cd api python manage.py createsuperuser ``` Once the app has been deployed, you can initialise your installation by accessing `/api/v1/users/config/init/`. This will show a page with a basic form to set up some initial data for the platform. Each of the parameters in the form are described below. | Parameter name | Description | | | -- | | Username | A unique username to give the installation super user | | Email | The email address to give the installation super user | | Password | The password to give the installation super user | | Site name | A human readable name for the site, e.g. 'Flagsmith' | | Site domain[^1] | The domain that the FE of the site will be running on, e.g. app.flagsmith.com. This will be used for e.g. password reset emails. | Once you've created the super user, you can use the details to log in at `/admin/`. From here, you can create an organisation and either create another user or assign the organisation to your admin user to begin using the application. Further information on the admin pages can be found . of variables used for configuration. If you want to run the entire Flagsmith platform, including the front end dashboard: ```bash curl -o

https://raw.githubusercontent.com/Flagsmith/flagsmith/main/docker-compose.yml docker-compose -f docker-compose.yml up ``` This will use some default settings created in the `docker-compose.yml` file located in the root of the project. These should be changed before using in any production environments. The docker container also accepts an argument that sets the access log file location for gunicorn. By default this is set to /dev/null to maintain the default behaviour of gunicorn. It can either be set to `"-"` to redirect the logs to stdout or to a location on the file system as required. The application relies on the following environment variables to run: `DATABASE_URL`: (required) configure the database to connect to. Should be a standard format database url e.g. postgres://user:password@host:port/db_name `REPLICADATABASEURLS`: (optional) configure an optional number of read replicas. Should be a comma separated list of standard format database urls. e.g. postgres://user:password@replica1.db.host/flagsmith,postgres://user:password@replica2.db.host/flagsmith `REPLICADATABASEURLS_DELIMITER`: (optional) set the delimiter to use for separating replica database urls when using `REPLICADATABASEURLS` variable. Defaults to `,`. This is useful if, for example, the comma character appears in one or more passwords. You can also provide individual variables as below. Note that if a `DATABASE_URL` is defined, it will take precedent and the below variables will be ignored. `DJANGODBHOST`: Database hostname `DJANGODBNAME`: Database name `DJANGODBUSER`: Database username `DJANGODBPASSWORD`: Database password `DJANGODBPORT`: Database port `GITHUBCLIENTID`: Used for GitHub OAuth configuration, provided in your OAuth Apps settings. `GITHUBCLIENTSECRET`: Used for GitHub OAuth configuration, provided in your OAuth Apps settings. `ENVIRONMENT`: string representing the current running environment, such as "local", "dev", "staging" or "production". Defaults to 'local' `DJANGOSECRETKEY`: secret key required by Django, if one isn't provided one will be created using `django.core.management.utils.getrandomsecret_key`. WARNING: If running multiple API instances, its vital that you define a shared DJANGOSECRETKEY. `LOG_LEVEL`: DJANGO logging level. Can be one of `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL` `LOG_FORMAT`: Can be `generic` (plain-text) or `json`. Defaults to `generic`. `GUNICORNCMDARGS`: Gunicorn command line arguments. Overrides Flagsmith's defaults. See for reference. `ACCESSLOGFORMAT`: Message format for Gunicorn's access log. See to define your own format. `ACCESSLOGLOCATION`: The location to store web logs generated by Gunicorn if running as a Docker container. If not set, no logs will be stored. If set to `-`, the logs will be sent to `stdout`. `DJANGOSETTINGSMODULE`: python path to settings file for the given environment, e.g. "app.settings.develop" `ALLOWADMININITIATIONVIACLI`: Enables the `bootstrap` management command which creates default admin user, organisation, and project. `ADMIN_EMAIL`: Email to use for the default superuser creation. `ORGANISATION_NAME`: Organisation name to use for the default organisation. `PROJECT_NAME` Project name to use for the default project. `ENABLEGZIPCOMPRESSION`: If Django should gzip compress HTTP responses. Defaults to `False`. `GOOGLEANALYTICSKEY`: if google analytics is required, add your tracking code `GOOGLESERVICEACCOUNT`: service account json for accessing the google API, used for getting usage of an organisation - needs access to analytics.readonly scope `INFLUXDB_TOKEN`: If you want to send API events to InfluxDB, specify this write token. `INFLUXDB_URL`: The URL for your InfluxDB database `INFLUXDB_ORG`: The organisation string for your InfluxDB API call. `GATABLEID`: GA table ID (view) to query when looking for organisation usage `USERCREATEPERMISSIONS`: set the permissions for creating new users, using a comma separated list of djoser or rest_framework permissions. Use this to turn off public user creation for self hosting. e.g. `'djoser.permissions.CurrentUserOrAdmin'` Defaults to `'rest_framework.permissions.AllowAny'`. `ALLOWREGISTRATIONWITHOUT_INVITE`: Determines whether users can register without an invite. Defaults to

Set to False or 0 to disable. Note that if disabled, new users must be invited via email. `ENABLEEMAILACTIVATION`: new user registration will go via email activation flow, default False `SENTRYSDKDSN`: If using Sentry, set the project DSN here. `SENTRYTRACESAMPLE_RATE`: Float. If using Sentry, sets the trace sample rate. Defaults to 1.0. `DEFAULTORGSTORETRAITSVALUE`: Boolean. Set this flag to ensure new organisations default to not persisting traits. Useful for data sensitive installations that don't want persistent traits. `OAUTHCLIENTID`: Google OAuth Client ID to enable accessing django admin pages via Google OAuth. See the for information on how to set users up to access the admin pages via SSO. `OAUTHCLIENTSECRET`: Google OAuth Secret to enable accessing django admin pages via Google OAuth. `ENABLEADMINACCESSUSERPASS`: Boolean. Set this flag to enable login to admin panel using username and password. `USEXFORWARDED_HOST`: Boolean. Default `False`. Specifies whether to use the X-Forwarded-Host header in preference to the Host header. This should only be enabled if a proxy which sets this header is in use. . `SECUREPROXYSSLHEADERNAME`: String. The name of the header looked for by Django's . Defaults to `HTTPXFORWARDED_PROTO`. `SECUREPROXYSSLHEADERVALUE`: String. The value of the header looked for by Django's . Defaults to `https`. `DJANGOSECUREREDIRECT_EXEMPT`: List. Passthrough of Django's . Defaults to an empty list `[]`. `DJANGOSECUREREFERRER_POLICY`: String. Passthrough of Django's . Defaults to `same-origin`. `DJANGOSECURESSL_HOST`: String. Passthrough of Django's . Defaults to `None`. `DJANGOSECURESSL_REDIRECT`: Boolean. Passthrough of Django's . Defaults to `False`. . String. Connection string to set up Flagsmith to send telemetry to Azure Application Insights. : Float. The tracer sample rate. `RESTRICTORGCREATETOSUPERUSERS`: Restricts all users from creating organisations unless they are . `FLAGSMITHCORSEXTRAALLOWHEADERS`: Comma separated list of extra headers to allow when operating across domains. e.g. `'my-custom-header-1,my-custom-header-2'`. Defaults to `'sentry-trace,'`. `FLAGSMITH_DOMAIN`: A custom domain for URLs pointing to your Flagsmith instance in email notifications. Note: if set, the domain provided during will be ignored. `DISABLEFLAGSMITHUI`: Disable the Flagsmith UI which can be rendered by the API containers in a single container environment. Use `True` to disable, defaults to `False`. `SEGMENTCONDITIONVALUE_LIMIT`: Configure the size of the segment condition value in bytes. Default is 1000. Minimum 0. Maximum 2000000 (2MB). Note that this environment variable changes the length of the column in the database and hence should not be modified for already running instances of flagsmith. It should only be used for new installations, and should not be modified. WARNING: setting this to a higher limit may prevent imports to our SaaS platform if required in the future. `ENABLEAPIUSAGE_TRACKING`: Enable tracking of all API requests in Postgres / Influx. Default is True. Setting to False will mean that the Usage tab in the Organisation Settings will not show any data. Useful when using Postgres for analytics in high traffic environments to limit the size of database. `ALLOWEDADMINIP_ADDRESSES`: restrict access to the django admin console to a comma separated list of IP addresses (e.g. `127.0.0.1,127.0.0.2`) `DJANGOALLOWEDHOSTS`: comma separated list of hosts the application will run on in the given environment `DJANGOCSRFTRUSTED_ORIGINS`: comma separated list of hosts to allow unsafe (POST, PUT) requests from. Useful for allowing localhost to set traits in development. `AXESONLYUSER_FAILURES`: If True, only lock based on username, and never lock based on IP if attempts exceed the limit. Otherwise utilize the existing IP and user locking logic. Defaults to

`AXESFAILURELIMIT`: The integer number of login attempts allowed before a record is created for the failed logins. Defaults to `10`. :::note You can self host Flagsmith without setting up an email server/gateway. You can invite additional users to the platform using invitation links, and the platform will run fine without email. ::: :::tip Flagsmith makes use of the `django_site` table to provide the domain name for email template links. You will need to configure the record in this table to point to your domain for email links to work. ::: `SENDER_EMAIL`: Email address from which emails are sent `EMAIL_BACKEND`: One of: `django.core.mail.backends.smtp.EmailBackend` `sgbackend.SendGridBackend` `django_ses.SESBackend` If using `django.core.mail.backends.smtp.EmailBackend` you will need to configure: `EMAILHOST` = env("EMAILHOST", default='localhost') `EMAILHOSTUSER` = env("EMAILHOSTUSER", default=None) `EMAILHOSTPASSWORD` = env("EMAILHOSTPASSWORD", default=None) `EMAILPORT` = env("EMAILPORT", default=587) `EMAILUSETLS` = env.bool("EMAILUSETLS", default=True) If using `sgbackend.SendGridBackend` you will need to configure: `SENDGRIDAPIKEY`: API key for the Sendgrid account If using AWS SES you will need to configure: `AWSSESREGION_NAME`: If using Amazon SES as the email provider, specify the region (e.g. eu-central-1) that contains your verified sender e-mail address. Defaults to us-east-1 `AWSSESREGION_ENDPOINT`: ses region endpoint, e.g. email.eu-central-1.amazonaws.com. Required when using SES. `AWSACCESSKEY_ID`: If using Amazon SES, these form part of your SES credentials. `AWSSECRETACCESS_KEY`: If using Amazon SES, these form part of your SES credentials. Flagsmith collects information about self hosted installations. This helps us understand how the platform is being used. This data is never shared outside of the organisation, and is anonymous by design. You can opt out of sending this telemetry on startup by setting the `ENABLE_TELEMETRY` environment variable to `False`. We collect the following data on startup per API server instance: Total number of Organisations Total number of Projects Total number of Environments Total number of Features Total number of Segments Total number of Users DEBUG django variable ENV django variable API server external IP address It is important to also set an environment variable on whatever platform you are using for `DJANGOSECRETKEY`. If one is not set then Django will create one for you each time the application starts up, however, this will cause unexpected behaviour as it is used by Django for encryption of e.g. session tokens, etc. To avoid these issues, please create set the `DJANGOSECRETKEY` variable. Django recommends that this key should be at least 50 characters in length, however, it is up to you to configure the key how you wish. Check the `getrandomsecret_key()` method in the Django source code if you want more information on what the key should look like. The application is run using python's gunicorn. As such, we are able to tell it to send statsd metrics to a given host for monitoring purposes. Using our docker image, this can be done and configured by providing the following environment variables. `STATSD_HOST`: the URL of the host that will collect the statsd metrics `STATSD_PORT`: optionally define the port on the host which is listening for statsd metrics (default: 8125) `STATSD_PREFIX`: optionally define a prefix for the statsd metrics (default: flagsmith.api) Below is an example docker compose setup for using statsd with datadog. Note that it's important to set the `DDDOGSTATSDNONLOCALTRAFFIC` environment variable to `true` to ensure that your datadog agent is able to accept metrics from external services. ```yaml version: '3' services: postgres: image:

environment: POSTGRES_PASSWORD: password POSTGRES_DB: flagsmith containername: flagsmithpostgres api: build: dockerfile: Dockerfile context: ../../api environment: DATABASE_URL: postgres://postgres:password@postgres:5432/flagsmith DJANGOSETTINGSMODULE: app.settings.local STATSD_HOST: datadog ports: '8000:8000' depends_on: postgres links: postgres datadog datadog: image: gcr.io/datadoghq/agent:7 environment: DDAPIKEY=<API KEY> DD_SITE=datadoghq.eu DDDOGSTATSDNONLOCALTRAFFIC=true volumes: /var/run/docker.sock:/var/run/docker.sock /proc/:/host/proc/:ro /sys/fs/cgroup:/host/sys/fs/cgroup:ro /var/lib/docker/containers:/var/lib/docker/containers:ro ``` If not running our application via docker, you can find gunicorn's documentation on statsd instrumentation The application makes use of caching in a couple of locations: Environment authentication - the application utilises caching for the environment object on all endpoints that use the X-Environment-Key header. By default, this is configured to use an in-memory cache. This can be configured using the options defined below. Environment flags - the application utilises an in memory cache for the flags returned when calling /flags. The number of seconds this is cached for is configurable using the environment variable `"CACHEFLAGSSECONDS"` Project Segments - the application utilises an in memory cache for returning the segments for a given project. The number of seconds this is cached for is configurable using the environment variable `"CACHEPROJECTSEGMENTS_SECONDS"`. Flags and Identities endpoint caching - the application provides the ability to cache the responses to the GET /flags and GET /identities endpoints. The application exposes the configuration to allow the caching to be handled in a manner chosen by the developer. The configuration options are explained in more detail below. To enable caching on the flags and identities endpoints (GET requests only), you must set the following environment variables: | Environment Variable | Description | Example value | Default | | | | | | | <code>GET\[FLAGS&#124;IDENTITIES]\ENDPOINTCACHESECONDS</code> | Number of seconds to cache the response to `GET /api/v1/flags` | `60` | `0` | | <code>GET\_. | `django.core.cache.backends.memcached.PyMemcacheCache` | `django.core.cache.backends.dummy.DummyCache` | | <code>GET\. | `127.0.0.1:11211` | `getflagsendpointcache` | An example configuration to cache both flags and identities requests for 30 seconds in a memcached instance hosted at `memcached-container`: ``` GETFLAGSENDPOINTCACHESECONDS: 30 GETFLAGSENDPOINTCACHEBACKEND: django.core.cache.backends.memcached.PyMemcacheCache GETFLAGSENDPOINTCACHELOCATION: memcached-container:11211 GETIDENTITIESENDPOINTCACHESECONDS: 30 GETIDENTITIESENDPOINTCACHEBACKEND: django.core.cache.backends.memcached.PyMemcacheCache GETIDENTITIESENDPOINTCACHELOCATION: memcached-container:11211 ``` On each request using the X-Environment-Key header, the flagsmith application retrieves the environment to perform the relevant caching. This can be configured using environment variables to create a shared cache with a longer timeout. The cache will be cleared automatically by certain actions in the platform when the environment changes. | Environment Variable | Description | Example value | Default | | - | | | | | `ENVIRONMENTCACHESECONDS` | Number of seconds to cache the environment for | `60` | `86400` ( = 24h) | | `ENVIRONMENTCACHEBACKEND` | Python path to the django cache backend chosen. See documentation . | `django.core.cache.backends.memcached.PyMemcacheCache` | `django.core.cache.backends.dummy.DummyCache` | | `ENVIRONMENTCACHELOCATION` | The location for the cache. See documentation . | `127.0.0.1:11211` | `environment-objects` | You can run Flagsmith as a single application/docker container using our unified builds. These are available on but you can also run the front end as part of the Django Application. Steps to do this: ```bash cd frontend npm install npm run bundledjango cd ../api python manage.py collectstatic python manage.py runserver ``` Webpack compiles a front end build, sourcing `api/app/templates/index.html`. It places the compiled JS and CSS assets to `api/static` then copies the annotated `index.html` page to `api/app/templates/webpack/index.html`. The Django `collectstatic` command then copies all the additional static assets that Django needs, including `api/app/templates/webpack/index.html`, into `api/static`. Python Django Django Rest Framework We're using to manage packages and dependencies, using Poetry standard workflows.