# Organizations (/docs/api/agents/organizations)

Everything in Improve belongs to an organization, which has one or more [spaces](/docs/terminology#space): one site or project each. Tests and flags belong to one of a space's three environments, `develop`, `staging` and `production`; audiences and API tokens to the space. Its allowed origins are shared with every product and managed on www. The dashboard remembers which space and environment you are editing. The agent API names them in the path instead:

```
/api/agent/organizations/{organizationId}/spaces/{spaceId}/{environment}/...
```

Things of the whole space, such as audiences and API tokens, leave out the environment, and things of the organization, such as its members, the space too:

```
/api/agent/organizations/{organizationId}/spaces/{spaceId}/...
/api/agent/organizations/{organizationId}/...
```

The paths from before spaces, without `/spaces/{spaceId}`, still work: they use the organization's first space.

All of these need a [bearer token](/docs/api/agents#use-the-token).

## List your organizations [#list-your-organizations]

```bash
curl https://improve.obelism.studio/api/agent/organizations \
  -H "Authorization: Bearer $TOKEN"
```

```json
{
	"organizations": [
		{
			"organizationId": "org_01H8XYZ",
			"name": "Acme",
			"slug": "acme",
			"plan": "pro",
			"role": "editor"
		}
	]
}
```

`GET /api/agent/organizations/{organizationId}` returns one organization, plus the `environments` every space has.

## List its spaces [#list-its-spaces]

`GET /api/agent/organizations/{organizationId}/spaces` returns the spaces you can work in, with the `spaceId` the other paths take. `first` marks the space that paths and SDK calls naming only the organization use.

```json
{
	"spaces": [
		{
			"spaceId": "space_01H8XYZ",
			"name": "Website",
			"slug": "website",
			"first": true
		}
	]
}
```

## Create, rename, delete and transfer spaces [#create-rename-delete-and-transfer-spaces]

Spaces are shared by every Obelism product, so they are managed on `www.obelism.studio`, like the organization's page (Improve redirects these requests there with a `308`). Each answers the space as `{ "space": { "spaceId", "organizationId", "name", "slug", "first" } }`.

- `POST /api/agent/organizations/{organizationId}/spaces` with `{"name":"Help centre"}` creates one. Its slug follows the name, with `-2`, `-3`… when the organization already has it. Needs `developer` or `admin`.
- `PATCH /api/agent/organizations/{organizationId}/spaces/{spaceId}` with `{"name":"…"}` renames it. The slug stays, so links and sites keep working. Needs `developer` or `admin` in the space.
- `DELETE /api/agent/organizations/{organizationId}/spaces/{spaceId}?confirm={slug}` deletes it with everything in it, in every product: tests, flags, audiences, API tokens, events, and its content and files in Obelism Content. Needs `admin`. The last space of an organization can't be deleted. This cannot be undone.
- `POST /api/agent/organizations/{organizationId}/spaces/{spaceId}/transfer` with `{"targetOrganizationId":"org_…","confirm":"{slug}"}` moves it with everything in it to another organization. API tokens, allowed origins, webhooks and the Shopify store stay connected; roles per space don't. Needs `admin` in both organizations. The first space can't be transferred, since paths naming only the organization use it.

```bash
curl -X POST https://www.obelism.studio/api/agent/organizations/$ORG/spaces \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name":"Help centre"}'
```

## Create an organization [#create-an-organization]

Creating an organization needs either a plan bought at a checkout on www, or an **organization key**, which is emailed when an [application for access](/docs/api/agents#apply-for-access) is approved. An agent cannot go through a checkout, so it always needs the key. Your account becomes its admin. Organizations are shared by every Obelism product, so creating, deleting and staffing them happens on `www.obelism.studio` (Improve redirects these requests there with a `308`).

```bash
curl -X POST https://www.obelism.studio/api/agent/organizations \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name":"Acme","organizationKey":"…"}'
```

A new organization starts with no space. Whatever works in a space, create its first one through `POST /api/agent/organizations/{organizationId}/spaces` before using it.

To delete one, an admin sends `DELETE https://www.obelism.studio/api/agent/organizations/{organizationId}?confirm={slug}`. The slug is the confirmation, like typing it in the dashboard. This deletes everything in it and cannot be undone.

## API tokens and allowed origins [#api-tokens-and-allowed-origins]

These decide who may fetch a space's [datafile](/docs/api/datafile) and post [analytics](/docs/api/analytics) for it: servers send an API token, browsers must come from an allowed origin. Each space has its own tokens; its allowed origins are shared with every product and managed on www. They need the `developer` or `admin` role, including to read them.

`GET .../security` returns, per environment, whether it has an API token (`hasApiToken`), its allowed origins and whether it accepts any origin (`allowAnyOrigin`). Tokens are stored hashed, so they can't be read back. `PATCH .../security` replaces the allowed origins of the environments you send, and can turn `allowAnyOrigin` on or off; it is served by www, where the shared list lives, and returns the origins without the token state:

```bash
curl -X PATCH https://www.obelism.studio/api/agent/organizations/$ORG/spaces/$SPACE/security \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"staging":{"allowAnyOrigin":true},"production":{"allowedOrigins":["https://shop.example.com","https://www.example.com"]}}'
```

Each origin must be exact, such as `https://shop.example.com`, with no path or trailing slash, because browsers send it that way. `allowAnyOrigin` is the dashboard's switch: handy for develop and staging, where every preview deployment has its own URL. The agent API only turns it on for those two; production's switch stays in the dashboard, behind its confirmation.

API tokens belong to an environment, under `/api/agent/organizations/{organizationId}/spaces/{spaceId}/{environment}`:

| Method | Path                           | Does                                                                                                                               |
| ------ | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- |
| `GET`  | `/api-tokens`                  | The tokens, newest first: name, last characters (`hint`), last used, expiry, revoked                                               |
| `POST` | `/api-tokens`                  | Create one with `{"name":"Website","expiresIn":"90d"}` (`30d`, `90d`, `1y` the default, `never`); the response has its value, once |
| `POST` | `/api-tokens/{tokenId}/revoke` | Revoke one                                                                                                                         |
| `POST` | `/api-token`                   | Revoke every active token and create one, from when there was one per environment                                                  |

Several tokens can be active, so a server can switch to a new one before the old one is revoked. A new or revoked token takes effect within about a minute.

Connected deployments reach Improve and Content with their host's OIDC token instead of an API token (see [API](/docs/api#without-a-stored-token)). They are served by `www.obelism.studio`, under `/api/agent/organizations/{organizationId}/spaces/{spaceId}/connections`, and need the `developer` or `admin` role:

| Method   | Path                          | What it does                                                                                                                                                                                                                                                       |
| -------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `GET`    | `/connections`                | The connections, newest first, each with its ids, `rules` and `revision` (`listConnections`)                                                                                                                                                                       |
| `POST`   | `/connections`                | Save a whole connection (`saveConnection`): `name`, `issuer` (`vercel` with `ownerId` and `projectId`, or `github` with `repositoryId`) and `rules`; `connectionId` and `baseRevision` replace one, else it is created (`201`). A stale revision is `409 conflict` |
| `DELETE` | `/connections/{connectionId}` | Disconnect one (`deleteConnection`)                                                                                                                                                                                                                                |

A rule maps a host environment (`host`: a Vercel environment, a GitHub environment or full ref, or `any` for the rest) to one space environment (`environment`), with `content` (`off`, `published`, `drafts`, or `management` with `scopes`) and `improve` (`true` also lets it send Numbers events):

```json
{
	"name": "Website on Vercel",
	"issuer": "vercel",
	"ownerId": "team_AbC123",
	"projectId": "prj_XyZ789",
	"rules": [
		{
			"host": "production",
			"environment": "production",
			"content": "published",
			"improve": true
		},
		{
			"host": "preview",
			"environment": "staging",
			"content": "drafts",
			"improve": true
		}
	]
}
```

## Members and invites [#members-and-invites]

Managing members needs the `admin` role. These endpoints are on `www.obelism.studio`, where the organization's page is too.

| Method   | Path                                         | Does                                  |
| -------- | -------------------------------------------- | ------------------------------------- |
| `GET`    | `/organizations/{id}/members`                | Members, and invites not accepted yet |
| `POST`   | `/organizations/{id}/members`                | Invite people by email                |
| `PATCH`  | `/organizations/{id}/members/{membershipId}` | Change a role or products             |
| `DELETE` | `/organizations/{id}/members/{membershipId}` | Remove a member or withdraw an invite |

```bash
curl -X POST https://www.obelism.studio/api/agent/organizations/$ORG/members \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"invites":[{"email":"sam@example.com","role":"editor"}]}'
```

`PATCH` takes `{ "role" }`, `{ "products" }` and/or `{ "spaces" }`: a role per space id, or `null` for every space with the organization role. `products` lists the products the member may use (`improve`, `content`, which includes media, and `numbers`), or is `null` for every product; in a product they are left out of, they aren't a member at all.

Each person gets an email with a link to join, valid for 72 hours. Emails that are already a member or invited come back under `skipped`. A change that would leave the organization without an admin who has joined is refused.

To join an organization yourself, `GET /api/agent/me/invites` (on `www.obelism.studio`) lists the organizations that invited your email, and `POST /api/agent/me/invites/accept` joins one, with either its `organizationId` or the `token` from the link in the invite email. Your email has to be verified first, since invites are matched by it.

## Usage [#usage]

`GET /api/agent/organizations/{organizationId}/spaces/{spaceId}/{environment}/usage` returns this month's usage against the plan: `events`, the organization's event pool, and `storage` and `bandwidth`, Media's, which only a Content plan includes. Each has `used`, `limit`, `state` (`ok`, `warning`, `over` or `blocked`) and `blockAt`; `blockedProducts` lists the products that are read-only right now. A quota covers the whole organization, so the numbers are all three environments combined whichever environment is in the path. A limit of `-1` is unlimited.

Past a limit (`over`) everything still works, and the organization's admins get an email. Past `blockAt`, the limit plus the plan's buffer, the product is `blocked`: [results](/docs/api/agents/results) freeze and the datafile is frozen at its last version until the next month or an upgrade. Sites keep working throughout.

## Roles [#roles]

Your role decides what you can do in an organization, the same as in the dashboard:

| Role        | Can                                                     |
| ----------- | ------------------------------------------------------- |
| `reader`    | View tests, flags, audiences and results                |
| `editor`    | Also create, edit and delete tests, flags and audiences |
| `developer` | Also manage API tokens and allowed origins              |
| `admin`     | Everything, including members and deleting the org      |

An action your role doesn't allow answers `403 insufficient_role`. An organization you are not a member of answers `404 unknown_organization`, the same as one that doesn't exist.
