The Flagsmith REST API
A plain-English guide to the web interface that lets programs create, read, change and audit feature flags: how it is organised, how to sign in safely, how to use it at scale, and how to keep it dependable in production.
Imagine your company has forty services and twelve environments, and a product manager asks you to create the same new flag in all of them before Monday. You could click through the dashboard four hundred and eighty times. Or you could write a small program that does the whole job in a minute, the same way every time, and leaves a record of exactly what it did.
That small program talks to Flagsmith through its REST API. Everything you can do by clicking in the dashboard, and quite a lot you cannot do conveniently by clicking, is available to programs through this interface. It is the foundation for automation, for tools like Terraform, for custom internal portals and for the reports your auditors ask for.
You do not need to know anything about web interfaces, authentication or feature flags to follow this guide. Every new word is explained when it first appears, with an everyday comparison. By the end you will understand what the REST API is, how its pieces are arranged, how programs prove who they are, how to use it safely and efficiently, and what to do when something goes wrong.
1Starting From Zero: What REST Means
Before the Flagsmith part, a calm look at the general idea.
An API is a menu
An API, short for application programming interface, is a set of rules that lets one program ask another program to do something. You never see it directly, yet you rely on it daily. When a payment app shows your balance, it has asked your bank’s system through an API.
Think of a restaurant menu. It lists exactly what you may order and how to ask for it. You do not walk into the kitchen and rearrange the shelves. You choose from the menu, a waiter carries your request, and the kitchen replies. An API is the menu, and the rules about how to order are its documentation.
What “REST” adds
REST stands for representational state transfer, which is a heavy name for a light idea. It is a popular style for designing web APIs around resources, meaning the things the system manages, such as projects, flags and users. Each resource has an address, and a small set of standard actions says what you want to do with it.
The standard actions come from the web itself. They are called HTTP methods. The common ones are easy to remember:
- GET reads something without changing it.
- POST creates something new.
- PUT replaces something with a complete new version.
- PATCH changes only part of something.
- DELETE removes something.
Requests, responses and status codes
Every conversation has two messages. Your program sends a request saying what it wants. The server sends a response with the result. The response always carries a three-digit status code that summarises what happened. Codes starting with 2 mean success, codes starting with 4 mean you made a mistake, and codes starting with 5 mean the server had a problem. You will meet specific ones in later chapters.
The message bodies are usually written in JSON, a simple text format made of labelled values. Almost every programming language can read and write it easily, which is why web APIs love it.
Whenever you meet a new technical word in this guide, ask three questions: what is it, why does it exist, and what would break without it? Those answers explain most of what you need.
2What the Flagsmith REST API Is
A definition, and the reasons behind it.
The definition
Flagsmith is a feature flag and remote configuration service. A feature flag is a switch in software that decides whether a feature is visible. A remote config value is a similar idea where the switch holds a number or text. The Flagsmith REST API is the web interface through which programs manage and read all of this: organisations, projects, environments, flags, segments, users and more.
Two families of endpoints
An endpoint is one address on the API that does one kind of job. Flagsmith’s endpoints fall into two broad families, and keeping them apart in your mind removes a great deal of confusion.
SDK endpoints
Used by your running apps to ask “what are the flags for this user?” They are built for very high volume and speed, and they use an environment key to identify the environment.
Admin endpoints
Used by people and tools to manage things: create flags, change values, edit segments, invite users, read the audit log. They are lower volume and need stronger credentials.
The SDK family is the one covered in guides about the Edge API. This guide focuses mostly on the admin family, which is what people usually mean by “the REST API,” while also explaining how the two families relate.
Why it exists
A dashboard is wonderful for a person making one change. It is a poor tool for making hundreds of consistent changes, for changing things on a schedule, or for connecting flags to other systems. An API solves all three. It also makes Flagsmith a good citizen in a larger toolbox, because anything that can send a web request can work with it.
The dashboard is the front counter of a shop, where a customer talks to a clerk. The API is the loading dock at the back, where trucks deliver and collect in bulk on a schedule. Both reach the same stock room, but they suit very different jobs.
Details such as exact paths, field names and available endpoints change as Flagsmith evolves. This guide teaches the ideas that stay true. Always confirm specifics in the official API documentation and in the interactive reference for your own installation or account.
3The Big Picture: Who Talks to What
One picture, then the details.
flowchart LR Person["Product Manager in Dashboard"] --> Core["Flagsmith Core API"] Script["Automation Script or Terraform"] -->|"admin credentials"| Core Portal["Internal Portal or Chatbot"] -->|"admin credentials"| Core Core --> DB["Main Database"] Core --> Audit["Audit Log"] Core -->|"publishes settings"| Edge["Edge Serving Layer"] App["Mobile or Web App SDK"] -->|"environment key"| Edge Server["Backend Service SDK"] -->|"server key"| Edge
Reading the picture
On the left sit the managers: a person using the dashboard, a script, and an internal portal. The dashboard itself is really just a friendly program that calls the same admin API. All of them talk to the core, which checks permissions, saves changes in the main database and writes an entry in the audit log, the official diary of who changed what and when.
On the right sit the consumers: your apps and backend services. They ask for flags through the serving layer, using a key that identifies an environment. The core publishes settings to that layer whenever something changes, so the apps get fresh answers without ever bothering the core.
Why separate the two sides
Editing flags happens a few times an hour. Reading flags happens thousands of times a second. These are different workloads with different needs. Keeping them apart means that a flood of app traffic cannot slow down your administrators, and a busy administrator cannot slow down your apps. It also lets each side use credentials that fit its risk: public-style keys for reading, strong secrets for writing.
| Question | SDK side | Admin side |
|---|---|---|
| Who calls it | Apps and backend services | People, scripts and automation tools |
| Typical action | Read the flags for a user | Create, change, list and delete things |
| Credential | Environment key | Organisation API key or user token |
| Volume | Very high | Modest |
| Risk if leaked | Lower for client keys, higher for server keys | High, since it can change production |
4The Cast of Resources
Every REST API is a map of things. Here is the map of Flagsmith.
The containers
Flagsmith organises everything in layers, like nested boxes. Knowing the boxes makes every endpoint easier to understand.
Organisation
Your company account. It holds people, billing and projects.
Project
Usually one product or service. It holds flags and segments, and defines environments.
Environment
One stage of a project, such as development, staging or production. Each has its own keys and its own flag states.
Feature
The definition of a flag or config value, shared by the whole project.
Feature state
The value of that feature inside one environment: on or off, plus any value attached.
Features versus feature states
This pair confuses almost every newcomer, so it deserves a clear explanation. A feature is the idea: “there is a flag called new_checkout.” It exists in the project. A feature state is the setting of that idea in one place: “in production, new_checkout is off.” One feature has many feature states, one for each environment.
A hotel has a feature called “air conditioning,” which exists in the building plans. Each room has its own state of it: on in room 101, off in room 102, set to 22 degrees in room 103. The plan is the feature. The setting in each room is the feature state.
This is why creating a flag and turning it on are usually two separate actions in the API. Creating makes the feature. Turning on changes a feature state in a particular environment.
The people and the rules
Segment
A group of users defined by rules over traits, such as “all premium users in India.” Flags can behave differently for a segment.
Identity
One end user known by an ID your app sends, with traits and sometimes personal overrides.
Trait
A small fact about an identity, such as its plan or country.
Tag
A label you attach to flags to group and find them, such as the owning team.
Audit log entry
A record of one change, with who, when and what.
Webhook and integration
Settings that send change events to other tools.
When an endpoint name puzzles you, ask which box it lives in: organisation, project or environment. The answer tells you what identifier you must supply and how far your change reaches.
5How Resources Get Their Addresses
Understanding the shape of an address lets you guess many endpoints without memorising them.
Addresses that read like sentences
REST addresses are built from nouns, usually plural, joined by slashes. The address of a collection ends in the noun, such as the list of projects. The address of one item adds that item’s identifier. Related collections nest beneath their parent. The pattern is easy to read aloud: “the features of project 12” or “the feature states of environment abc.”
The standard methods then give a tidy grid. Reading a collection lists its items. Posting to a collection creates a new item. Reading one item shows it. Patching or putting one item changes it. Deleting one item removes it. Once you know this grid, a new resource feels familiar before you have read a word of its documentation.
| Action wanted | Method | Address pattern |
|---|---|---|
| List all items | GET | The collection address |
| Create an item | POST | The collection address |
| Read one item | GET | The collection address plus the item identifier |
| Change part of an item | PATCH | The item address |
| Replace an item | PUT | The item address |
| Remove an item | DELETE | The item address |
Identifiers: numbers and keys
Two kinds of identifiers appear in Flagsmith addresses. Projects, features and many other resources are identified by a number. Environments are often addressed by their environment key, the same string your apps use, which doubles as a handy public name for the environment. Mixing these up is a common reason for “not found” responses, so check which one each endpoint expects.
Versions in the address
You will see a version marker, such as v1 or v2, near the start of addresses. It lets the service improve its design without breaking programs written against the old shape. When Flagsmith introduces a newer version for a resource, older addresses usually keep working for a long time, but new features may appear only on the newer one. Pay attention to deprecation notes in the documentation so your automation does not stop working unexpectedly.
Street addresses follow a pattern: country, city, street, number. Once you know the pattern, you can find any house without a personal guide. REST addresses follow a similar pattern, and the version marker is like the edition number on a printed street map.
The built-in interactive reference
Flagsmith publishes a browsable reference of its API, in a standard format called OpenAPI, and the interactive version lets you try endpoints from your browser. Self-hosted installations usually serve the same reference from their own address. Use it as your source of truth for exact paths and fields, and keep this guide as your source of understanding.
6Proving Who You Are: Authentication
Every request must answer one question before anything else: who is asking?
Authentication versus authorisation
Authentication means proving identity: “I really am the deployment robot.” Authorisation means checking permission: “the deployment robot is allowed to change flags in staging but not production.” Both happen on every request, in that order. A failure of the first gives an unauthorised response with code 401. A failure of the second gives a forbidden response with code 403.
The credentials Flagsmith uses
Client-side environment key
Safe to place in browser or phone code. It can only read flags for one environment through the SDK endpoints.
Server-side environment key
A secret for trusted backends. It unlocks extra SDK features such as downloading the whole environment for local evaluation.
Organisation API key
A secret credential, not tied to any person, used by scripts and tools to call the admin endpoints. Ideal for robots.
User token
A credential belonging to one human user, obtained by signing in. It acts with that person’s permissions.
How a credential travels
The credential is sent in a header of every request, which is a labelled line of extra information that travels with the message. SDK endpoints expect the environment key in a header named for that purpose. Admin endpoints expect an authorisation header whose value begins with a word that names the scheme, followed by the secret. Check the documentation for the exact words your version expects, since they are easy to mistype and a wrong prefix looks like a wrong key.
A building has visitor passes, staff badges and master keys. A visitor pass opens only the lobby. A staff badge opens the offices that person works in. A master key opens everything, so it is locked in a safe and used rarely. Environment keys, user tokens and organisation keys are the same ladder of trust.
Choosing between a user token and an organisation key
People sometimes automate with their own personal token because it is convenient. This is a trap. When that person leaves the company, their account is switched off, and every pipeline using their token breaks at the worst possible moment. Their actions in the audit log also look like human actions, which confuses reviews. An organisation key, created for one purpose and named for it, avoids both problems.
Treat admin credentials like passwords to your production system, because that is what they are. Never put them in source code, chat messages, screenshots or browser-visible code. Keep them in a secrets manager and inject them into jobs only at run time.
7Internal Working: The Life of One Admin Request
Follow a single change from your script to the saved result.
sequenceDiagram participant S as Your Script participant G as Gateway and Load Balancer participant C as Core API participant P as Permission Check participant D as Main Database participant A as Audit Log participant E as Edge Publisher S->>G: HTTPS request with credential G->>C: Forward to a healthy core instance C->>P: Who is this and may they do this? P-->>C: Allowed C->>C: Validate the submitted data C->>D: Save the change C->>A: Write audit entry C->>E: Queue publish of new settings C-->>S: Success response with saved data
Step by step
The request arrives over HTTPS
HTTPS encrypts the conversation so anyone listening on the network sees only scrambled data. The gateway receives it and passes it to a healthy copy of the core.
The credential is checked
The core looks up the key or token and works out who or what is calling. An unknown or revoked credential ends the story here with a 401 response.
Permissions are checked
The core asks whether this caller may perform this action on this project or environment. A missing permission ends with a 403 response.
The data is validated
The core checks that required fields exist and have sensible values. A bad request ends with a 400 response that explains which field is wrong.
The change is saved and recorded
The new data is stored, an audit entry is written, and any webhooks or integrations are queued.
Settings are published to the serving layer
A background task packages the updated environment settings and sends them to the serving layer, so apps see the change shortly afterwards.
The response returns
The caller receives a success code and the saved version of the item, which is the proof that the change was accepted.
A success response is not instant worldwide
The success response means the core has saved the change. It does not mean every app on Earth already sees it. Publishing to the serving layer and the refresh timers inside SDKs add a short delay, usually seconds. Scripts that change a flag and then immediately test an app may need to wait a moment before asserting the result. This honest delay is called eventual consistency, and it is the price of fast, resilient serving.
When head office posts a new price list, the manager gets a receipt that says “sent.” That receipt does not mean every branch has already pinned it to the wall. A little time passes while couriers deliver. The API response is the receipt, and the SDK refresh is the courier.
8Reading Responses: Status Codes and Errors
Learn to read the replies, and your scripts will fix themselves more often than not.
The status codes you will meet most
| Code | Plain meaning | Usual cause | What to do |
|---|---|---|---|
| 200 | OK, here is your data | A read or update succeeded | Carry on |
| 201 | Created | A new item was made | Store the new identifier |
| 204 | Done, nothing to return | A delete succeeded | Carry on |
| 400 | Your request is malformed | Missing or invalid field | Read the message and fix the data |
| 401 | Who are you? | Missing, wrong or revoked credential | Check key, prefix and environment |
| 403 | You may not do that | Credential lacks permission | Grant the permission or use another credential |
| 404 | Not found | Wrong identifier or path | Check which kind of identifier is expected |
| 409 | Conflict | Item already exists or clashes | Read the existing item instead |
| 429 | Slow down | Rate limit reached | Wait, then retry politely |
| 500 and above | Server trouble | A problem on the service side | Retry with backoff, then report |
Errors that explain themselves
Good APIs explain their complaints, and Flagsmith’s admin endpoints usually return a message naming the field or rule that failed. Your scripts should log that message in full. A log line that says only “request failed” wastes hours. A log line that says which endpoint, which identifier, which status and which message lets the next person fix the problem in minutes.
Retrying wisely
Some failures are temporary. Others never improve. A 400 or 403 will fail forever if you repeat it, so retrying is pointless. A 429 or a 500 may succeed later. When you retry, wait a little between attempts and lengthen the wait each time, an approach called backoff. Add a small random delay too, called jitter, so a hundred scripts that failed together do not all retry together.
If a shop door is locked because the shop is closed, knocking harder does nothing. If it is locked because the owner stepped out for a moment, waiting a few minutes helps. Status codes tell you which kind of locked door you are facing.
Make your scripts stop and report loudly on 4xx errors, and retry quietly on 429 and 5xx errors. That single rule separates mistakes you must fix from hiccups that heal themselves.
9Working With Lists: Pagination and Filtering
Big collections arrive in slices, and you need to know how to ask for the next slice.
Why lists come in pages
Imagine asking for every flag in a company that has ten thousand of them. A single reply would be huge, slow to produce and slow to receive. So the API returns a manageable page of results at a time, together with information telling you how to fetch the next page. This is called pagination.
How pages are described
A list response typically contains the total number of items, a link to the next page, a link to the previous page, and the items for this page. Your code follows the next link until it is empty. You do not construct page numbers yourself unless the documentation says to. Following the supplied link is safer because the service chooses how pages are cut.
flowchart TD
A["Request first page"] --> B["Receive items and next link"]
B --> C["Process items"]
C --> D{"Is there a next link?"}
D -->|"Yes"| E["Request the next link"]
E --> B
D -->|"No"| F["Finished: all items processed"]
Filtering and searching
Many list endpoints accept extra settings in the address, called query parameters, that narrow the results. You might ask only for flags carrying a certain tag, only for archived items, or only for those whose name contains a word. Filtering on the server is better than downloading everything and filtering in your script, because it saves time, bandwidth and rate-limit budget.
Common mistakes with lists
- Reading only the first page and believing the list is complete, so the script silently misses items.
- Building page numbers by hand instead of following the supplied link.
- Changing items while listing, which can shift pages under your feet. Collect first, then change.
- Asking for everything when a filter would have returned a handful.
A library does not hand you every book on a shelf in one armful. It gives you a trolley-load at a time and tells you where the next trolley is. Pagination is the trolley. Stopping after the first one means leaving most of the library unread.
A script that audits “all flags with no owner” but reads only the first page will happily report a clean result. Always test list-handling code against a project with more items than one page holds.
10Managing Flags Through the API
The everyday jobs: create, change, tag, archive and remove.
Creating a flag
Creating a flag means posting a new feature to a project. You supply a name and, optionally, a description, an initial value, tags and whether it is a simple on/off flag or a config value. The reply includes the new feature’s numeric identifier, which you will need for later steps, so store it. Names should follow your team’s convention, because they appear in dashboards, logs and graphs for years.
When a feature is created, Flagsmith also creates its feature state in every environment of the project, starting from defaults you may provide. Newly created flags are normally off in each environment unless told otherwise, which is a safe starting point.
Changing a flag in one environment
Turning a flag on in production is a change to a feature state, not to the feature. You find the feature state for that feature in that environment, then change its enabled setting and, for config flags, its value. Because two different identifiers are involved, the environment and the feature, mistakes here are common. Double-check both before sending a change to production.
flowchart TD A["Find project identifier"] --> B["Find feature identifier by name"] B --> C["Find environment key"] C --> D["Find the feature state for that feature and environment"] D --> E["Change enabled setting or value"] E --> F["Read it back to confirm"]
Tags, descriptions and archiving
Tags and descriptions turn a flat list of flags into something a team can manage. A typical set of tags records the owning team, the type of flag, and whether it is a release flag expected to be removed. Archiving hides a flag from everyday lists without deleting it, which is a gentle step on the way to removal. Deleting is permanent, so make sure code no longer reads the flag before you do it.
Safe habits for write operations
- Read before you write. Fetch the current state, confirm it is what you expect, then change it.
- Read after you write. Fetch again to confirm the saved result matches your intention.
- Prefer partial updates. A PATCH changes only the fields you name. A PUT replaces the whole item, and omitted fields may reset.
- Do one environment at a time when learning, and add loops only after the single case works.
Editing a shared recipe card, a careful cook first reads the existing card, changes one line in pencil, and reads it again. A careless cook photocopies a different card over the top. PATCH is the pencil. PUT is the photocopy.
Test every script against a development environment first, with the same code path and a different environment key. The most expensive mistakes happen when a script meant for staging runs against production.
11Segments, Identities and Traits Through the API
Targeting the right people is also something programs can manage.
Segments as data
A segment is a named group defined by rules. Each rule looks at a trait, compares it to a value using an operator such as equals or contains, and combines with other rules using “all of” or “any of.” Through the API you can create, read, change and delete segments, which makes it possible to keep your segment definitions in version control and apply them consistently across projects.
Segments belong to a project, but the way a flag behaves for a segment is an override stored per environment. This split matters: the same segment can be generous in staging and strict in production.
Identities and their overrides
An identity represents one end user. Through the admin side you can list identities, view their traits, and create identity overrides, which are special rules for one user, such as “turn this feature on for the tester account.” Overrides beat segment rules because they are the most specific.
The SDK side can also create identities automatically: when an app sends an identifier with traits, Flagsmith stores them. Be careful when mixing the two. If your admin script tidies up identities that real apps are still using, users may suddenly lose their personal settings.
Traits and privacy
A trait is a small fact about an identity. Traits are powerful, but anything you send is stored, so keep them small and non-sensitive. Prefer internal IDs over emails, and coarse facts such as a plan name over detailed personal ones. If your rules about personal data are strict, review what your apps send before you design segments around it.
plan = premium
Small, useful and not personal. It supports sensible decisions without exposing anyone.
app_version = 5.2
Lets you hide features from versions that cannot display them.
email address
Personal data that travels to a third-party service and sits in storage. Use an internal ID instead.
health or financial details
Sensitive facts that almost never belong in a flag system. Keep them in your own protected systems.
A name badge at a conference shows your first name and company, not your home address or bank details. It gives staff just enough to treat you correctly. Traits should work like name badges: enough to decide, and no more.
Keep a small list of test identities with fake IDs, such as test-user-001, and use only those when you experiment through the API. They give you repeatable results and protect real customers.
12The SDK Endpoints in Detail
The other half of the API: how apps ask for flags.
Two basic questions
The SDK endpoints answer two questions. The first is “what are the flags for this environment?” The answer is the same for everyone, so it needs only the environment key. The second is “what are the flags for this particular user?” It needs the environment key, a user identifier and optionally some traits, and the answer may differ from person to person because of segments and overrides.
What a response looks like
The reply is a list of flags. Each entry names the feature, says whether it is enabled, and carries its value if it is a config flag. Because the structure is regular, SDKs wrap it into friendly calls such as “is this flag enabled” so your own code seldom touches the raw response.
Why you rarely call these by hand
You can call the SDK endpoints directly from any language, but the official SDKs add valuable behaviour: caching, retries, timeouts, default values, optional live updates and consistent handling of identities. Calling the raw endpoints makes sense for tiny scripts, for languages without an SDK, or for learning. For production apps, use the SDK.
| Need | Use | Why |
|---|---|---|
| Read flags in an app | SDK endpoints through an SDK | Built for volume, with caching and defaults |
| Create or edit flags | Admin endpoints | Needs permissions and an audit trail |
| Quick test from a terminal | SDK endpoint with an environment key | Simple and safe, read-only |
| Bulk reporting | Admin endpoints with filters | Returns rich metadata about every flag |
Do not use admin endpoints inside your app
A frequent beginner mistake is calling the admin endpoints from an app to read flags, because they are easy to find in the documentation. This is slow, expensive, rate-limited and unsafe, since the app would need a powerful credential. Always use the SDK endpoints for runtime reads. They are made for that job, and they are served from the fast, distributed layer rather than the core.
A bank customer checking a balance uses the cash machine, not the manager’s office. The cash machine is fast, safe and designed for crowds. The manager’s office can do far more, but sending every customer there would jam it up.
13Automation: Terraform, Scripts and Pipelines
The real prize of an API is that machines can do the repetitive work for you.
Infrastructure as code
Infrastructure as code means describing your systems in text files that a tool reads and applies, instead of clicking in dashboards. Terraform is a popular tool of this kind, and Flagsmith has a provider that talks to the REST API on your behalf. You describe projects, environments, flags and segments in files. Terraform compares the description to reality and makes only the changes needed.
The benefits are large. Every change gets code review. Every change has history. Setting up a new project becomes copying a template. And mistakes can be undone by reverting a file.
flowchart LR Dev["Engineer edits flag definitions"] --> PR["Pull request and review"] PR --> CI["Pipeline plans the change"] CI --> Approve["Human approves"] Approve --> Apply["Pipeline applies using organisation key"] Apply --> API["Flagsmith REST API"] API --> Audit["Audit log records the robot"]
Choosing one source of truth
If Terraform owns a flag, then editing that flag in the dashboard creates drift, a difference between what the files say and what really exists. The next run may quietly undo the manual change, which surprises the person who made it. Decide clearly which flags are managed by code and which by humans. Many teams let code own the structure, such as projects, environments and segments, while product managers still flip release flags by hand.
Scripts for everyday chores
Even without Terraform, small scripts are valuable. Typical examples include copying a flag configuration from staging to production in a controlled way, listing flags older than ninety days for a cleanup review, finding flags with no owner tag, and exporting the audit log for compliance. Each script is a few dozen lines, uses an organisation key, and saves hours every month.
Pipelines and deployments
Continuous delivery pipelines can use the API to prepare flags before a release, for instance to confirm a required flag exists in the target environment and fail the deployment if it does not. This catches the classic error of shipping code that expects a flag nobody created.
Name organisation keys after the job they do, such as ci-staging-flag-sync. When the audit log shows that name, reviewers instantly know which robot made the change and why.
14Performance, Limits and Scalability
The admin side is built for correctness, so treat it kindly.
Latency, throughput and rate limits
Latency is how long one request takes. Throughput is how many requests are handled each second. Rate limits cap how many requests one caller may make in a period, protecting the service for everyone. Admin endpoints do richer work than SDK endpoints, so they are slower and are more tightly limited. Hosted plans can also include request allowances, so check your current terms.
Why the admin side is not for runtime traffic
Admin endpoints talk to the main database and perform permission checks and audit logging. That is exactly what you want for a change and exactly what you do not want for millions of reads. Sending application traffic there would be slow, expensive and risky for the very system your administrators depend on.
Making your scripts efficient
- Filter on the server so you fetch only what you need.
- Cache lookups, such as the mapping from flag name to identifier, instead of repeating them for every change.
- Limit concurrency. Ten parallel workers are plenty. A hundred may trigger rate limits and gain nothing.
- Honour retry guidance. If a response tells you how long to wait, wait that long.
- Batch thoughtfully. Spread large changes over time, and warn teammates so a burst of audit entries and notifications does not cause alarm.
A busy office has one receptionist who handles special requests and a self-service kiosk for routine ones. If everyone queues at the receptionist for routine questions, the special requests wait for hours. Admin endpoints are the receptionist. SDK endpoints are the kiosk.
Idempotency: safe to repeat
An action is idempotent when doing it twice has the same result as doing it once. Reading is naturally idempotent. Setting a flag to “on” is too. Creating a flag with a given name is not, because the second attempt may fail or create a duplicate. Good scripts are written so that running them again after an interruption causes no harm: check whether the flag exists first, create it only if missing, and set values rather than toggle them.
15Security and Compliance
An API that can change production is a door that deserves a very good lock.
Protect the credentials
Store admin credentials in a secrets manager. Give each automation its own key, so you can revoke one without disturbing the others. Rotate keys on a schedule and immediately when someone who knew them leaves. Scan your repositories for accidentally committed secrets, because attackers do exactly that, constantly and automatically.
Least privilege
Give every credential only the access its job needs. A reporting script that only reads audit logs should not carry the power to delete flags. Flagsmith supports roles and permissions at organisation, project and environment levels, so a robot for staging can be kept far away from production.
Encryption and network safety
Always use HTTPS. Never switch to unencrypted connections to “make debugging easier.” If you self-host, place the service behind a gateway, keep software up to date, and restrict who can reach the admin interface. For especially sensitive setups, allow admin traffic only from known networks.
Audit and accountability
Every change made through the API appears in the audit log with the identity that made it. This is a gift for incident reviews and for audits, but only if identities are meaningful. Shared logins and anonymous robots destroy the value of the log. One named key per job, and one account per person, keeps it honest.
| Risk | Example | Simple defence |
|---|---|---|
| Leaked admin key | Key committed to a public repository | Secrets manager, scanning, quick rotation |
| Over-powerful robot | Reporting script able to delete flags | Least-privilege roles per key |
| Departing employee | Pipeline uses a personal token | Use organisation keys for automation |
| Man in the middle | Traffic over plain HTTP | HTTPS only, verified certificates |
| Silent changes | Shared login hides who acted | Personal accounts and named keys |
A company does not hand every contractor a master key. Each gets a card opening only the doors they need, logged by name, and cancelled when the job ends. Good API security is that same habit applied to software.
If you suspect a key has leaked, revoke it first and investigate second. Creating a replacement takes a minute. A leaked production key left alive for an afternoon can cost far more.
16Monitoring, Logging and Auditing
Automation that nobody watches is a quiet accident waiting to happen.
Three kinds of signals
Metrics are numbers over time. Logs are text records of events. Traces follow one request across several services. Together they let you understand your automation without guessing.
What to record in your own scripts
What was attempted
Endpoint, method, project and environment identifiers, and the change requested.
What happened
Status code, error message and how long the call took.
Success and failure counts
A rise in failures is the earliest sign of an expired key or a changed endpoint.
Run duration
A job that suddenly takes ten times longer may be hitting rate limits.
Job did not run
Silence is a signal. Alert when an expected nightly job produces no log at all.
Unexpected production change
A change outside agreed hours or by an unexpected identity deserves a notification.
The Flagsmith audit log as a source of truth
The audit log records who changed what and when. You can read it through the API, which lets you build reports, feed a compliance archive, or trigger alerts. For legal or regulatory needs, copy audit entries into your own long-term store on a schedule, so your record does not depend on a single system’s retention settings.
Connecting changes to graphs
Flagsmith integrations can push change events to monitoring platforms and chat tools, so that flag changes appear as markers on your dashboards. When a graph jumps, a marker beside the jump answers “what changed?” in seconds. API-driven changes should appear there too, which is another reason to give each robot a clear name.
Write a one-line summary at the end of each automation run: how many items were checked, changed, skipped and failed. It takes seconds to add and is the first thing everyone will want to read later.
17Design Patterns and Anti-Patterns
Habits that make API automation calm, and habits that make it painful.
Patterns worth copying
Read, change, verify
Fetch the current state, apply the change, fetch again and compare. Cheap insurance against surprises.
Dry run first
Let scripts print what they would do without doing it, and require a human to approve the real run for production.
One key per job
Each automation has its own named, least-privilege key that can be revoked on its own.
Idempotent scripts
Running twice leaves the same result as running once, so retries and reruns are safe.
Config as code
Structure lives in reviewed files, applied by a pipeline, with history and easy rollback.
Environment promotion
Changes flow from development to staging to production through the same script with different keys.
Advantages and trade-offs of API-driven management
Advantages
- Consistency across many projects and environments.
- Review and history for every change.
- Saves hours of repetitive clicking.
- Connects flags to the rest of your tools.
- Enables reports and audits on demand.
Trade-offs
- Powerful credentials that must be guarded.
- Scripts can repeat a mistake very quickly.
- Drift if people also edit by hand.
- Extra work to learn identifiers and endpoints.
- Dependence on API versions that may change.
Anti-patterns to avoid
What people do
They put an admin key inside a mobile app or website so the app can read flags directly.
Why it hurts
Anyone can extract the key from the app and use it to change production flags for every user.
Better approach
Use the client-side environment key and the SDK endpoints in apps. Keep admin keys on servers and pipelines only.
What people do
They write a script that toggles a flag, and run it twice by accident.
Why it hurts
The flag ends up back in its original state, and nobody notices until customers do.
Better approach
Write scripts to set a desired state, never to flip the current one.
What people do
They list “all flags” by reading only the first page of results.
Why it hurts
Reports and cleanups quietly miss most items, giving false confidence.
Better approach
Follow the next link until it is empty, and test with a project larger than one page.
18Best Practices and Common Mistakes
A practical checklist drawn from everything so far.
Do these
- Use the right family of endpoints. SDK endpoints for apps, admin endpoints for management.
- Use organisation keys for robots and personal tokens only for people.
- Keep secrets in a secrets manager and rotate them on a schedule.
- Test in development first, with the same code and a different key.
- Handle pagination and rate limits in every list-reading script.
- Log clearly and summarise each run.
- Write idempotent scripts that set states rather than toggle them.
- Check the official reference for exact paths and fields before relying on memory.
Common mistakes and quick cures
| Mistake | What you see | Cure |
|---|---|---|
| Wrong authorisation prefix | Constant 401 responses despite a valid key | Copy the exact scheme word from the documentation |
| Mixing feature and feature state identifiers | 404 responses or changes in the wrong place | Look up each identifier separately and name variables clearly |
| Using PUT for a small change | Other fields reset unexpectedly | Use PATCH for partial updates |
| Ignoring status codes | Scripts report success while changes failed | Check every response, stop on 4xx |
| Hammering the API | 429 responses and slow runs | Limit concurrency and back off |
| Testing against production | Real customers see experiments | Separate keys and a visible environment name in logs |
| No cleanup of old flags | Hundreds of unexplained flags | Tag owners and review quarterly with a script |
19Troubleshooting Guide
When something goes wrong, check in a calm and predictable order.
The usual suspects
401 Unauthorised
The credential is missing, mistyped, revoked, or sent with the wrong prefix. Re-copy it and check which family of endpoint you are calling.
403 Forbidden
The credential is valid but lacks permission for this project or environment. Check roles and the scope of the key.
404 Not found
The path or identifier is wrong. Confirm whether the endpoint wants a numeric identifier or an environment key.
400 Bad request
A field is missing or invalid. Read the error message, which usually names the field.
My change is not visible in the app
Wait a few seconds for publishing, confirm the right environment, and check the SDK’s cache timer.
429 Too many requests
Slow down, reduce parallel workers, add backoff, and filter on the server to make fewer calls.
A calm order of checks
First, read the status code and the message body in full. Second, confirm the address, including the version marker and the exact identifier type. Third, confirm the credential and its prefix. Fourth, confirm the permissions behind the credential. Fifth, try the same request with a trivial, read-only call to prove basic access. Sixth, check the service status page and your own network. This order avoids blaming the service for mistakes in your script.
Reproduce with the smallest request
When a large script fails, shrink it. Try the single failing call by itself, using a tool like the interactive reference in your browser or a simple command-line client. If the small call works, the problem is in your surrounding code. If it fails the same way, the problem is in the credential, the address or the data.
Self-hosted extras
If you run Flagsmith yourself, additional causes appear: the service may be behind a gateway that strips headers, certificates may be expired, a background worker may not be running so changes never publish, or database migrations may be incomplete after an upgrade. When “everything works except changes reaching apps,” suspect the background worker first.
When a lamp does not light, you check the bulb, the switch, the plug and the fuse in that order, not the power station. Troubleshooting an API call follows the same short path from your own end outwards.
Keep a read-only organisation key for diagnostics. It lets you check what really exists without any risk of changing something while you investigate.
20Testing and Rehearsing Your Automation
A script you have never tried on a safe target is only a hope.
Build a safe playground
Create a separate test project, or at least a test environment, with its own keys. Fill it with a handful of flags and fake identities. Run every new script there first. Because the playground mirrors the real structure, a script that works there will almost always work for real, and a script that misbehaves there harms nobody.
A set of simple experiments
Happy path
Run the script against the playground and confirm that every expected change appears, and the audit log names your robot.
Run it twice
Confirm the second run changes nothing and reports that everything is already correct. This proves idempotency.
Wrong key
Use a deliberately wrong credential and confirm the script stops with a clear message instead of carrying on.
Rate limit and slow network
Simulate slow replies or a 429 response and confirm the script backs off and recovers.
Large list
Create more items than one page holds and confirm the script reads all pages.
Dry runs and approvals
A dry run prints exactly what a script would do without doing it. Always provide one. For production, require the dry-run output to be reviewed by a second person before the real run. This mirrors how Terraform separates planning from applying, and it catches wrong environments and wrong names before they cost anything.
Contract checks for API changes
APIs evolve. A nightly test that calls a few key endpoints in your playground and checks that the response still has the fields your scripts rely on will warn you when a change arrives, hours or days before production jobs break. Pair it with a habit of reading release notes.
Never rehearse destructive actions, such as deleting flags, against anything real. Use clearly named throwaway flags in a throwaway project, and tell the team so nobody mistakes the activity for an incident.
21Migration, Import and Export
Moving flags between places is a classic job for an API.
Why you might move flags
Teams move flags for many reasons: promoting a configuration from staging to production, copying a template into a new project, switching from another flag vendor, or moving from a self-hosted installation to the hosted service. Doing this by hand invites mistakes. Doing it through the API, with checks, makes it repeatable.
A safe migration recipe
Inventory the source
List all projects, environments, features, segments and identity overrides, following every page of results.
Map the differences
Note anything that does not translate directly, such as unsupported rule types or differently named concepts.
Create in a test target
Build the structure in a throwaway project first, flags off, and compare results item by item.
Run both in parallel
For a vendor switch, run old and new side by side with a comparison script that checks identical answers for sample users.
Cut over gradually
Point a small slice of traffic at the new system, watch graphs, then expand.
Keep a rollback
Leave the old system intact and ready until the new one has proved itself for a full business cycle.
Exports as insurance
Even if you never plan to move, a regular export of your flag configuration is wise. A nightly job that reads your projects, features, segments and states through the API and saves them to storage gives you a snapshot you can compare, restore from, or show to an auditor. It also helps you answer the question “what did production look like last Tuesday?”
Moving house goes best with an inventory list, labelled boxes and the old keys kept for a week. If something is missing, you check the list. If the new place has a problem, you can still go back. A migration script is the inventory and the labels.
Do not migrate user data casually. Identity and trait data may be personal, so confirm your privacy rules before copying it anywhere new.
22A Worked Example: A Retail Company Cleans Up Its Flags
A made-up company shows how the pieces fit together.
The story below is hypothetical. Imagine a retailer called Maple Market with eight services, three environments each, and about nine hundred flags created over four years. Nobody knows which are still needed. The platform team decides to use the REST API to bring order.
Step one: a read-only inventory
An engineer creates a read-only organisation key named inventory-reader. A script lists every project, then every feature in each project, following all pages. It records the name, creation date, tags and description. The result is a single table of nine hundred rows.
Step two: finding the lonely flags
The table shows that four hundred flags have no owner tag, and three hundred are older than a year. A second pass reads the audit log and finds that two hundred of those have not been changed in over twelve months.
Step three: asking owners
Where a flag has a team tag, the script posts a message to that team’s chat channel asking, “Is this still needed?” For untagged flags, the platform team reviews names and code searches by hand.
Step four: tag and archive
A second key named flag-janitor, with permission to edit tags and archive but not delete, applies the tag “cleanup-candidate” to flags agreed as unused, and archives those with confirmed owners’ consent. Every action is idempotent, and a dry run is reviewed before each batch.
Step five: watching for surprises
For two weeks, the team watches dashboards and error logs. One archived flag turns out to be read by a rarely used report. The team restores it from archive in seconds, tags it as long-lived, and adds the owner. Nobody outside the team notices.
Step six: delete with code
After two quiet weeks, developers remove the unused flag checks from code in normal pull requests. Only then does a final script delete the flags. The audit log records each deletion against the flag-janitor key.
Step seven: make it a habit
The platform team schedules the inventory script every quarter, publishes the results to a shared page, and adds a rule: no new flag without an owner tag and a target removal date. A pipeline check enforces the rule using the API.
What made this smooth
Nothing needed heroics. The team used separate keys with narrow powers, read before writing, ran dry runs, left a quiet period between archiving and deleting, and let the audit log tell the story. Each simple habit covered a different risk, and together they turned a frightening clean-up into a routine chore.
23The Same Ideas in the Wider World
Everything you learned here shows up in nearly every web service you will ever meet.
REST is not special to Flagsmith. It is a family habit shared by payment providers, cloud platforms, chat tools and countless others. Recognising the shared habits lets you learn a new API in an afternoon. The examples below describe publicly known styles in general terms, not any company’s private design.
Cloud platforms
Large cloud providers expose almost every feature through web APIs, with scoped credentials and detailed audit trails, so that infrastructure can be created by programs rather than clicks.
Payment services
Payment providers popularised friendly, well-documented REST APIs, idempotency keys that make retries safe, and separate test and live credentials.
Code platforms
Code hosting services let tools list repositories page by page and update settings with fine-grained tokens, which is the same pagination and scoping story you met here.
Messaging tools
Chat services use tokens with narrow permissions and tell clients to slow down with rate-limit responses, exactly as described for status code 429.
Declarative tools
Tools such as Terraform turn many different vendors’ APIs into a common “describe the desired state” language.
OpenAPI
A shared format for describing web APIs lets documentation, test tools and code generators work with many services in the same way.
The shared pattern
Across all of these, the same few habits repeat. Resources have predictable addresses. Standard methods mean read, create, change and remove. Credentials are scoped and rotated. Lists come in pages. Servers push back with clear status codes. Clients retry with care. Changes are logged. Once you know these habits, any new API feels like a familiar room with different furniture.
Once you can drive one car, you can drive almost any car, because pedals, wheel and mirrors sit in roughly the same places. REST APIs share their controls in the same way, and the Flagsmith one is simply one more model in the car park.
Lessons you can reuse
- Read the reference, but learn the pattern. The pattern lasts longer than any single endpoint.
- Always separate test credentials from live ones.
- Treat every list as possibly longer than one page.
- Assume the network will fail sometimes, and write scripts that cope.
- Log enough to explain yourself to a stranger a year from now.
24Limits: What the Admin API Is Not Meant For
Knowing a tool’s limits is as valuable as knowing its strengths.
Not a runtime data source
The admin endpoints are not meant to serve your application at runtime. They are slower, tightly limited and protected by powerful credentials. Reading flags in an app belongs to the SDK endpoints and the serving layer, which are built for scale.
Not an instant global broadcast
A successful change response means the core has saved the change. Publishing and SDK refresh timers add a short delay. Do not design features that need every user to see a change at the same millisecond. For strict coordination across machines, use tools made for it.
Not a user database
Identities and traits exist to drive flag decisions. They are not a place to store customer profiles. Keep real customer records in your own systems, and send Flagsmith only the small facts needed for targeting.
Not a security boundary for sensitive actions
A flag value delivered to a browser or phone can be inspected by the person holding the device. Do not guard sensitive actions with a client-side flag. Enforce permissions on your server and use flags only to decide what is shown or rolled out.
Not a replacement for testing
Flags make careful releases easier, but they do not remove bugs. Code behind a flag still needs tests in both its on and off states.
| You want to | Use | Not |
|---|---|---|
| Read flags in an app | SDK endpoints through an SDK | Admin endpoints |
| Create many flags consistently | Admin API, scripts or Terraform | Manual clicking |
| Guard a sensitive action | Server-side permission checks | A client-side flag |
| Store customer profiles | Your own database | Identity traits |
| Coordinate machines at an exact moment | Locks and queues | A flag flip |
| Long-term compliance records | A copy of the audit log in your own store | Relying only on retention in one system |
If a design feels awkward, step back and ask whether each part is using the tool for what it does best: the admin API for careful management, the SDK endpoints for fast reading.
25A Plain-English Glossary
Quick definitions of the words used in this guide.
API
A set of rules that lets one program ask another to do something.
REST
A popular style of web API built around resources with addresses and standard actions.
Endpoint
One address on an API that does one kind of job.
HTTP method
The verb of a request: GET, POST, PUT, PATCH or DELETE.
Status code
A three-digit number summarising how a request went.
JSON
A simple text format of labelled values used for request and response bodies.
Authentication
Proving who you are.
Authorisation
Checking what you are allowed to do.
Organisation API key
A robot credential for automation, not tied to any person.
Environment key
The string that identifies one environment for SDK requests.
Feature and feature state
The flag idea in a project, and its setting in one environment.
Segment
A group of users defined by rules over traits.
Pagination
Returning long lists a page at a time with a link to the next page.
Idempotent
Safe to repeat: doing it twice equals doing it once.
Backoff and jitter
Waiting longer between retries, plus a small random delay.
Drift
A difference between what code says should exist and what really exists.
Audit log
The official diary of who changed what and when.
Eventual consistency
Copies may differ briefly but soon agree without manual repair.
26Webhooks and Event-Driven Automation
Instead of asking the API again and again, let it ring a bell when something happens.
Polling versus being told
There are two ways to learn that a flag changed. The first is polling: your program asks the API every minute, “Has anything changed?” Most of the time the answer is no, so most of the questions are wasted. The second is a webhook: Flagsmith sends your program a message the moment something happens. You write a small receiver, give Flagsmith its web address, and the messages arrive on their own.
Waiting for a parcel, you can walk to the front door every five minutes or you can wait for the doorbell. Polling is the walking. A webhook is the doorbell. Both let you collect the parcel, but only one lets you get on with your afternoon.
What webhooks carry
Flagsmith can send webhooks when flags change in an environment, and can also send events when entries are added to the audit log. The message is a small block of JSON describing what happened: which flag, which environment, what changed and who did it. Your receiver reads it and decides what to do, for example refreshing an internal cache, updating a ticket, or posting to a chat room.
How webhooks and the REST API work together
A webhook tells you that something changed. The REST API lets you look at the details. A common pattern is to treat the webhook as a hint and then call the API to read the exact current state. This protects you from messages that arrive late, twice or out of order, because the API always gives the truth as it is now.
| Need | Best tool | Reason |
|---|---|---|
| React quickly to a change | Webhook | You are told at once without wasting requests |
| Know the exact current state | REST API read | Always the truth, regardless of message order |
| Catch up after being offline | REST API list and audit log | Lets you replay what you missed |
| Make a change | REST API write | Webhooks only announce, they do not edit |
Rules for a trustworthy receiver
- Verify the sender. Anyone on the internet can post to your address, so check the signature when you have configured a shared secret.
- Answer quickly. Put the event on a queue, reply with success at once, and do the real work afterwards.
- Be idempotent. Messages can arrive more than once. Handling the same event twice must do no harm.
- Do not trust the order. Use timestamps in the message, or re-read from the API when order matters.
- Use HTTPS so the conversation is encrypted.
Never make your application’s correctness depend on a webhook alone. If one message is lost, a service relying only on webhooks stays wrong until the next change. Keep a slower periodic check as a safety net.
27Governance: Who May Do What, and Who Owns Which Key
Powerful tools need clear rules, or they slowly become a mess.
Why governance is not boring paperwork
Governance is a grown-up word for agreeing who is responsible for what. In a team of three, everybody knows everything. In a company of three hundred, a key may be created by someone who has since changed teams, used by a pipeline nobody remembers, and held with permissions nobody reviewed. Six months later it fails, or worse, it is misused. A short, well-kept register prevents both outcomes.
The key register
Keep a simple list of every automation credential. For each one, record the name, the owner, the purpose, where the secret is stored, which permissions it has, when it was created and when it should next be rotated. Review the list each quarter. Remove anything without an owner or a purpose.
| Key name | Owner | Purpose | Access | Next rotation |
|---|---|---|---|---|
| ci-staging-flag-sync | Platform team | Sync flag definitions to staging | Edit flags in staging only | Quarterly |
| inventory-reader | Platform team | Nightly export for audits | Read-only everywhere | Quarterly |
| flag-janitor | Release manager | Tag and archive stale flags | Edit tags, archive, no delete | Quarterly |
| prod-release-bot | Release manager | Enable approved flags at release | Edit production flags | Monthly |
Roles and permissions
Not everyone needs the power to change production. A sensible arrangement lets most engineers view flags and edit them in development and staging, lets a smaller group change production, and reserves administrative actions such as creating keys for a few trusted people. This follows the old principle of least privilege: each person and each robot gets only the access the job requires.
In a large office, everybody has a pass for the front door, fewer have a pass for the server room, and only a handful hold the master key. Nobody is distrusted. The arrangement simply limits the damage that one mistake or one lost pass can cause.
Change approval for production
For production environments, many companies require a second person to approve changes. Flagsmith supports approval workflows in some plans. When automation makes production changes, mimic the same discipline: a pipeline plans the change, a human approves it, and only then does the robot apply it. The audit log then shows both the request and the robot that carried it out.
Naming and tagging rules
- Begin flag names with the product area, such as checkout or search, and describe the change.
- Tag every flag with an owning team and a type, such as release, experiment or kill switch.
- Give release flags a target removal date in the description.
- Name keys after the job they do, so the audit log explains itself.
Enforce the rules with the API itself. A small pipeline check can fail any change that creates a flag without an owner tag. Rules that machines enforce are followed far more often than rules written on a wiki.
Measure the health of your practice
A few simple measures keep things honest. Count how many flags are older than ninety days. Count how many have no owner. Count how many keys have not been used in thirty days. Track how long it takes to revoke a key in an emergency. A short table updated each quarter shows whether things are improving.
28An Incident Runbook and a Ninety-Day Plan
Two practical tools: what to do when something breaks, and how to adopt all this without overwhelm.
Part one: when automation misbehaves
A runbook is a short, step-by-step guide that a tired person can follow at three in the morning. Here is one for the day a script changes something it should not have.
Stop the robot
Pause the pipeline or scheduled job. If you cannot, revoke the key. A revoked key can be replaced in a minute, but a running mistake keeps growing.
Open the audit log
Filter by the key’s name to see exactly what changed, in which environment, and when it started.
Reverse the harmful changes
For flags, the fastest repair is usually setting the previous value. Use a prepared script or the dashboard, whichever is quicker and safer.
Confirm recovery
Watch your graphs and a test app. Remember the short publishing delay before apps see the repair.
Tell people
Post a short message in the usual channel: what happened, what is fixed, what is still being checked.
Learn and prevent
Write down the cause, add a check to the script, and update the runbook. Aim to make the same mistake impossible, not merely unlikely.
Part two: a ninety-day adoption plan
Look before you touch
Create a read-only key. Write a script that lists every project, flag and tag, with proper pagination. Share the inventory and agree on naming and tagging rules.
Automate the safe chores
Add small, idempotent scripts with dry runs: tag flags with owners, report stale flags, export the audit log nightly. Build a test project to rehearse everything first.
Make it a pipeline
Introduce code-managed structure with Terraform or a similar tool, approvals for production, a key register, quarterly rotation and the runbook above.
How to know it is working
After ninety days, check a few signs. Can a new teammate learn who owns each key in five minutes? Did the number of ownerless flags drop? Did a script catch a mistake before it reached production? Did the last incident end faster because the audit log named the culprit key? If most answers are yes, the automation is earning its keep.
A one-page cheat sheet
- Know your family. SDK endpoints for apps, admin endpoints for management.
- Pick the key by place and job. Never put an admin key anywhere a user can see it.
- Read, change, verify. Every write is sandwiched between two reads.
- Follow every page. Lists continue until the next link is empty.
- Set, never toggle. Scripts should describe the desired state.
- Retry only the right errors. 429 and 5xx with backoff, never 4xx.
- Expect a short delay. Saved is not the same as seen by every app.
- Name everything. Keys, flags and tags should explain themselves to a stranger.
Pin this list beside your team’s runbook. New joiners can read it in two minutes, and experienced engineers will find that it settles most design arguments quickly. Good habits around a powerful interface are what turn raw capability into calm, dependable operations, whatever size your company grows to be.
One last piece of advice concerns patience. Nobody builds the perfect automation on the first attempt. Begin with one read-only script and one safe chore. Watch how they behave for a few weeks, note the surprises, and improve one habit at a time. Teams that grow their practice gradually end up with simpler, sturdier setups than teams that try to automate everything before launch, because every addition is justified by a real need they have already seen.
29Versions, Deprecations and Living With Change
An API is a promise, and promises evolve. Here is how to stay safe while they do.
Why APIs change
Flagsmith keeps growing. New features arrive, old designs are improved, and occasionally an endpoint is replaced by a better one. This is healthy, but it means a script written today may meet a changed world next year. Sensible teams expect change and prepare for it, instead of being surprised by it.
The warning signs to watch for
Release notes
Flagsmith publishes release notes and announcements. Assign someone to skim them monthly, looking for the words deprecated, removed, renamed and changed.
Version markers
A new version marker in an address usually signals a redesigned resource. The old one tends to remain for a while, but new capabilities appear only on the new one.
Response headers and warnings
Some services add hints to responses when you call something that is being retired. Log unusual headers rather than discarding them.
Changed fields
A field may be added, renamed or become required. A nightly contract test in your playground catches this before production jobs do.
Writing scripts that survive change
- Read only the fields you need. If your script ignores extra fields, new additions do not break it.
- Keep addresses in one place. A single configuration file or constant makes a path change a one-line fix.
- Wrap the API in a small helper. Your other code calls “get all flags” and the helper handles pagination, retries and paths. When the API changes, you fix one helper.
- Test against the real service regularly. Mocks drift away from reality. A short scheduled test against a playground project does not.
- Pin tool versions. For Terraform providers and client libraries, pin the version and upgrade deliberately, reading the changelog first.
A house with plumbing hidden behind one tidy panel is easy to repair when a pipe is replaced. A house with taps connected in twenty different rooms is not. A helper layer around the API is that tidy panel.
A change-management routine
Learn early
Read release notes monthly and note anything touching endpoints you use.
Try in the playground
Run your scripts against a test project on the newer behaviour, or after upgrading a self-hosted test copy.
Fix and review
Update the helper, run the dry run, and have a colleague review the diff.
Roll out gradually
Switch non-critical jobs first, then production jobs, watching logs after each step.
Record it
Write a short note in the key register or runbook about what changed and why.
If you self-host
When you run Flagsmith yourself, you decide when to upgrade, which gives you control and responsibility. Read the upgrade notes, back up your database, try the upgrade in a staging copy, run your scripts and contract tests against it, and only then upgrade production. After upgrading, confirm that background workers are running, because changes that save but never reach apps are the classic sign of a stopped worker.
Change is cheap when it is expected and expensive when it is a surprise. A monthly ten-minute look at release notes is one of the best investments an automation owner can make.
Questions to ask before you automate anything
Before writing any new script against the admin API, pause and answer five short questions. Doing so takes a few minutes and prevents most of the problems described in this guide.
What exactly will change?
Name the project, the environment and the flags involved. If you cannot list them, the script is not ready to run.
Who could be affected?
Think about customers, support staff and other teams. Tell them in advance if a change touches production.
How do I undo it?
Decide the reversal before the change. If the answer is “I am not sure,” take a snapshot or export first.
Which key will run it?
Pick the narrowest key that can do the job and confirm its name will make sense in the audit log.
How will I know it worked?
Choose the check in advance: a read-back of the saved state, a graph, or a test app showing the new behaviour.
These five questions work for a ten-line script and for a company-wide migration alike. Teams that make them a habit rarely have dramatic automation failures, because small problems are noticed and fixed while they are still small, long before they can interfere with a launch, an experiment or an incident response.
It also helps to treat your automation like any other product your team ships. Give each script an owner, a short description of its purpose, a place in version control, and a person to contact when it fails. Review the oldest scripts every few months and retire the ones nobody needs. Unused automation holding live credentials is a quiet risk, because it keeps a powerful door unlocked long after the reason for opening it has been forgotten. Small, owned, well-described scripts are easy to trust, easy to fix and easy to remove, and that combination is the real goal of managing flags through an API.
Finally, remember that the people who will inherit your scripts are often tired, in a hurry and unfamiliar with your reasoning. Write comments that explain why a step exists, not just what it does. Include the expected result of a dry run in the description. Link to the ticket that requested the work. A few thoughtful sentences left behind today will save a future colleague, perhaps you, a long and stressful evening.
30Frequently Asked Questions
Quick answers to the questions beginners ask most often.
31Summary and Key Takeaways
The whole guide on one page.
Key Takeaways
- Two families, two jobs. SDK endpoints serve flags to apps quickly with environment keys. Admin endpoints manage projects, flags, segments and users with stronger credentials.
- Know the boxes. Organisation, project, environment, feature and feature state explain nearly every address and identifier you will meet.
- Use the right credential. Client-side keys in apps, server-side keys on servers, organisation keys for robots and personal tokens for people.
- Read the replies. Status codes tell you whether to fix your request or simply retry. Stop on 4xx errors and back off on 429 and 5xx.
- Handle lists properly. Follow the next link until it ends, and filter on the server to make fewer calls.
- Write calm scripts. Read first, set rather than toggle, run a dry run, verify afterwards and log what happened.
- Guard the keys. Use a secrets manager, grant least privilege, name each key for its job, rotate regularly and keep a copy of the audit log.