# Getting Started with the Management SDK

> Source: https://agilitycms.com/docs/javascript/management-sdk/getting-started

Managing content from outside the CMS has never been easier. The **Agility Management SDK** lets you create and update content, apply workflow actions, and manage pages, models, containers, and assets through the Agility Management API.

The SDK ships for **JavaScript/TypeScript** and **.NET**. This section documents both — use the tabs in each code sample to switch languages, and your choice is remembered as you read.

## Use cases

- Importing content from external systems
- Implementing custom approval workflows
- Keeping content in sync with other platforms
- Bulk updating or publishing content lists
- Managing pages programmatically

---

## Installation

<div class="code-tabs" data-tabs="JavaScript,.NET">

```bash
npm install @agility/management-sdk
```

```bash
dotnet add package Agility.Management.SDK
```

</div>

> **.NET: use version 2.0.** The NuGet package id is `Agility.Management.SDK`. Version 2.0.0 is a stable release, so you don't need `--prerelease`. It targets .NET 10, and its namespace is `Agility.Management.Sdk`. Projects on .NET 6 to 9 can stay on 1.x; see [Management SDK - Intro](/docs/dotNet/management-sdk-dotnet-intro).

Both SDKs are open source:

- JavaScript/TypeScript: [agility-cms-management-sdk-typescript](https://github.com/agility/agility-cms-management-sdk-typescript)
- .NET: [agility-cms-management-sdk-dotnet](https://github.com/agility/agility-cms-management-sdk-dotnet) (version 2.0 targets .NET 10. Upgrading from 1.x? See [Migrating to 2.0](/docs/dotNet/management-sdk-dotnet-migrating-to-2).)

---

## Authentication

Every request needs an access token. The SDK supports two ways to get one: **OAuth 2.0** (for interactive apps) and **Personal Access Tokens** (for automation — see below).

### Step 1 — Start the authorization flow

Send the user to the authorize endpoint. Add the `offline_access` scope if you want a refresh token so the integration can run unattended:

```
GET https://mgmt.aglty.io/oauth/authorize
  ?response_type=code
  &redirect_uri=YOUR_REDIRECT_URI
  &state=YOUR_STATE
  &scope=openid profile email offline_access
```

### Step 2 — Exchange the code for a token

Your redirect URI receives an authorization code. Exchange it for an access token:

<div class="code-tabs" data-tabs="JavaScript,.NET">

```ts
const response = await fetch("https://mgmt.aglty.io/oauth/token", {
  method: "POST",
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
  body: new URLSearchParams({ code: "YOUR_AUTHORIZATION_CODE" }),
})

const { access_token, refresh_token, expires_in } = await response.json()
```

```csharp
using Agility.Management.Sdk;
using Agility.Management.Sdk.Models;

// The sign-in calls need no credentials, so the options can be empty
using var client = new AgilityManagementClient(new AgilityManagementOptions());

// POST /oauth/token
TokenResponseData tokens = await client.OAuth.ExchangeCodeAsync("YOUR_AUTHORIZATION_CODE");
// tokens.AccessToken, tokens.RefreshToken, tokens.ExpiresIn
```

</div>

The response is the same shape either way: `access_token`, `token_type`, `expires_in`, and — when you asked for `offline_access` — `refresh_token`.

### Step 3 — Refresh an expired token

```
POST https://mgmt.aglty.io/oauth/refresh?refresh_token=YOUR_REFRESH_TOKEN
```

> **Token lifetimes.** Access tokens last **24 hours** — after that, requests return `401 Unauthorized`. Refresh tokens last **30 days**, and only exist if you authorized with the `offline_access` scope. Store both securely and never expose them in client-side code.

---

## Setting up the client

With a token in hand, initialize the client and make your first request:

<div class="code-tabs" data-tabs="JavaScript,.NET">

```ts
import * as mgmtApi from "@agility/management-sdk"

// Initialize the Options class
const options = new mgmtApi.Options()
options.token = "<<your-access-token>>"

// Initialize the ApiClient
const apiClient = new mgmtApi.ApiClient(options)

const guid = "<<your-instance-guid>>"
const locale = "en-us"

// Get the content item with ID 22
const contentItem = await apiClient.contentMethods.getContentItem(22, guid, locale)
console.log(JSON.stringify(contentItem))
```

```csharp
using Agility.Management.Sdk;

// Create one client and reuse it
using var client = new AgilityManagementClient(new AgilityManagementOptions
{
    AccessToken = "<<your-access-token>>"
});

var guid = "<<your-instance-guid>>";
var locale = "en-us";

// Get the content item with ID 22 (the instance GUID comes first)
var contentItem = await client.Content.GetContentItemAsync(guid, locale, 22);
Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(contentItem));
```

</div>

In .NET 2.0 the namespace is `Agility.Management.Sdk` (model types such as `TokenResponseData` are in `Agility.Management.Sdk.Models`), and every instance-level method takes the instance GUID first, then the locale, then IDs. The 1.x names (`management.api.sdk`, `ClientInstance`, `contentMethods`) are gone in 2.0; see [Migrating to 2.0](/docs/dotNet/management-sdk-dotnet-migrating-to-2).

### Options fields

| Field | Purpose |
| --- | --- |
| `token` | OAuth access token or PAT (**required**) |
| `baseUrl` | Override the API base URL (optional) |
| `refresh_token` | OAuth refresh token (optional) |
| `duration` | Retry polling interval in ms (default `3000`) |
| `retryCount` | Max retry attempts for batch polling (default `500`) |

These are SDK-side settings, not API parameters — you won't find them in the Management API spec.
`duration` and `retryCount` control the **batch polling** described in [How writes complete](#how-writes-complete) below.

The table above is the JavaScript `Options` class. The .NET client takes an `AgilityManagementOptions` instead:

| Property | Purpose |
| --- | --- |
| `AccessToken` | A Personal Access Token or OAuth access token |
| `RefreshToken` | An OAuth refresh token; the client gets and renews access tokens from it |
| `AccessTokenProvider` | Supplies a token for each request; takes precedence over the two above |
| `BaseUrl` | Send every request to this host instead of the region in the instance GUID (optional) |
| `BatchPolling` | How long to wait for batches: `Interval` (default 3 seconds) and `Timeout` (default 15 minutes) |
| `Retry` | Retries for reads only; writes are never retried |
| `ApplicationName` | Added to the User-Agent header (optional) |

### Regional endpoints

The SDK picks the right API host from your instance GUID's suffix — you normally don't set `baseUrl` yourself:

| GUID suffix | Region | Endpoint |
| --- | --- | --- |
| `-u` | US | `https://mgmt.aglty.io` |
| `-us2` | US 2 | `https://mgmt-usa2.aglty.io` |
| `-c` | Canada | `https://mgmt-ca.aglty.io` |
| `-e` | Europe | `https://mgmt-eu.aglty.io` |
| `-a` | Australia | `https://mgmt-aus.aglty.io` |
| `-d` | Dev | `https://mgmt-dev.aglty.io` |

Each host serves its own Swagger UI — append `/swagger` to try endpoints interactively against your own instance.

---

## Personal Access Tokens (PAT)

For automation, CI/CD pipelines, and server-side jobs where an OAuth redirect isn't practical, use a **Personal Access Token**.

### Generating a PAT

PATs are created through the Management API. Authenticate with OAuth first, then call `POST /api/v1/tokens/create` — via your region's Swagger UI (append `/swagger` to the endpoints in the table above), with this body:

```json
{
  "name": "my-automation-token",
  "expiryDate": "2028-01-01T00:00:00Z"
}
```

> **`name` is the only required field.** `expiryDate` is optional in the API spec, and the spec doesn't define what happens when you omit it — so always set an explicit future date rather than relying on unspecified behaviour.

A successful call returns `201` with the token in the response's `token` field. **That value is returned only once** — save it immediately, and note that the `notice` field carries an accompanying message about it. Alongside the usual `400`, `401`, and `403` errors, `429` is a documented response, so automation that creates tokens in bulk should back off and retry.

| Response field | What it tells you |
| --- | --- |
| `tokenID` | Identifier for the token — used by the token management endpoints |
| `name` | The name you supplied |
| `token` | The secret value, returned **only** on creation |
| `notice` | Message accompanying the newly created token |
| `expiryDate` | When the token expires |
| `createdDate` | When the token was created |
| `enabled` | Whether the token is currently active |
| `isExpired` | `true` once the expiry date has passed |
| `daysUntilExpiration` | Days of life left — useful for rotating tokens before they lapse |
| `lastUsedDate` | Last time the token authenticated a request |

Companion endpoints let you audit and rotate tokens: `GET /api/v1/tokens/list`, `GET /api/v1/tokens/{tokenId}`, `PUT /api/v1/tokens/{tokenId}/update`, and `DELETE /api/v1/tokens/{tokenId}/delete`.

### Using a PAT

Initialization is identical to OAuth: pass the PAT as `token` (JavaScript) or `AccessToken` (.NET):

<div class="code-tabs" data-tabs="JavaScript,.NET">

```ts
import * as mgmtApi from "@agility/management-sdk"

const options = new mgmtApi.Options()
options.token = "<<your-personal-access-token>>"

const apiClient = new mgmtApi.ApiClient(options)
```

```csharp
using var client = new AgilityManagementClient(new AgilityManagementOptions
{
    AccessToken = "<<your-personal-access-token>>"
});
```

</div>

**PAT restrictions:** PATs cover content operations but **cannot** touch user management, token management, or admin-level endpoints — those return `403 Forbidden`.

---

## How writes complete

Two things about writing through this API surprise people. Both are worth knowing before your first
save, because each one looks like a bug when you hit it.

### Every write is queued, and returns a batch ID

The Management API does not perform a write during your request. It **queues a batch** and responds
with a **batch ID** — an integer that identifies the queued work, *not* the content ID and not a
result. The actual save happens moments later.

**The SDK hides this for you.** `saveContentItem`, `publishContent` and friends take the batch ID,
poll until the batch completes, and return the real result — which is why `Options` has `duration`
and `retryCount`: they are the polling interval and the attempt ceiling. If a large import times out
waiting, raise `retryCount` rather than assuming the write failed.

If you want the batch ID instead of waiting, pass `returnBatchId: true` in JavaScript, or `waitForBatch: false` in .NET. You are
then responsible for polling it yourself:

```
GET /api/v1/instance/{guid}/batch/{batchID}
```

That URL is **not** locale-scoped — `/{guid}/batch/{id}`, with no `/{locale}` segment. The batch is
finished when `batchState` is `3`. A freshly created batch ID can return `404` for a moment before it
exists, so treat an early `404` as "not yet", not as failure.

> **Calling the REST API directly?** Then this is your problem, not the SDK's. `POST /item` gives you a
> batch ID and nothing else; read the item straight back and you will get the **old** value, which looks
> exactly like a write that silently did nothing. Poll the batch before you trust the result.

### A save lands in Staging, not on your live site

Saving does **not** publish. A save always writes to **Staging**, and if the item was already
Published it drops back to a Staging state — your live site keeps serving the previous version until
you publish explicitly.

So changing one field on a live item is always **two** operations:

```ts
// 1. save — the change now exists, in Staging
const contentID = await apiClient.contentMethods.saveContentItem(item, guid, locale)

// 2. publish — only now is it live
await apiClient.contentMethods.publishContent(contentID, guid, locale)
```

Skip the second step and the change is real, stored, and invisible to your site — the single most
common reason a write "didn't work". The same applies to pages, and to every bulk equivalent: see
[Content Items](/docs/javascript/management-sdk/content-items) and
[Pages](/docs/javascript/management-sdk/pages).

---

## SDK operations

The client exposes a group of methods for each area of the CMS: `*Methods` properties on the JavaScript `ApiClient`, and properties on the .NET `AgilityManagementClient`.

| JavaScript group | .NET 2.0 property | Covers |
| --- | --- | --- |
| `contentMethods` | `Content` | Content items: get, list, save, delete, workflow, history, comments |
| `containerMethods` | `Containers` | Containers (content lists) |
| `modelMethods` | `Models` | Content and component models |
| `pageMethods` | `Pages` | Pages, sitemap, page models |
| `assetMethods` | `Assets` | Media: upload, folders, galleries |
| `instanceUserMethods` | `InstanceUsers` | Instance users and roles |
| `batchMethods` | `Batches` | Batch status and batch-level workflow actions |
| `instanceMethods` | `Locales`, `SyncStatus` | Locales and Fetch API sync status |
| `serverUserMethods` | `ServerUsers` | The authenticated user |
| `webhookMethods` | `Webhooks` | Webhooks and their signing secrets |
| None | `Localization` | Copying and translating content and pages into other locales |
| None | `UrlRedirections` | URL redirections, including import and export |
| None | `PersonalAccessTokens` | Creating, listing, updating and revoking Personal Access Tokens |
| None | `OAuth` | The sign-in URL, code exchange and token refresh |

---

## Feature differences between the SDKs

Version 2.0 of the .NET SDK covers every method group the JavaScript SDK has. The methods that earlier versions of this page listed as JavaScript-only all have a .NET equivalent:

| JavaScript | .NET 2.0 |
| --- | --- |
| `instanceMethods.getLocales()` | `client.Locales.GetLocalesAsync(guid)` |
| `instanceMethods.getFetchApiStatus()` | `client.SyncStatus.GetFetchApiStatusAsync(guid, mode)` |
| `serverUserMethods.me()` | `client.ServerUsers.GetCurrentUserAsync()` |
| `webhookMethods` (webhook CRUD) | `client.Webhooks`: `GetWebhooksAsync`, `GetWebhookAsync`, `SaveWebhookAsync`, `DeleteWebhookAsync`, `RotateSigningSecretAsync` |
| `contentMethods.batchWorkflowContent()` | `client.Content.BatchWorkflowContentItemsAsync` |
| `contentMethods.getContentList()` (POST filtering) | `client.Content.GetContentListAsync` |
| `contentMethods.getContentHistory()` | `client.Content.GetContentItemHistoryAsync` |
| `contentMethods.getContentComments()` | `client.Content.GetContentItemCommentsAsync` |
| `containerMethods.getContainerListPaged()` | `client.Containers.GetContainerListPagedAsync` |
| `pageMethods.getPageHistory()` | `client.Pages.GetPageHistoryAsync` |
| `pageMethods.getPageComments()` | `client.Pages.GetPageCommentsAsync` |
| `pageMethods.batchWorkflowPages()` | `client.Pages.BatchWorkflowPagesAsync` |
| `batchMethods.publishBatch()` and the other batch workflow actions | `client.Batches.PublishBatchAsync`, `UnpublishBatchAsync`, `ApproveBatchAsync`, `DeclineBatchAsync`, `RequestApprovalBatchAsync` |
| `assetMethods.deleteFolder()`, `assetMethods.renameFolder()` | `client.Assets.DeleteFolderAsync`, `client.Assets.RenameFolderAsync` |

The gap now runs the other way. The .NET SDK also wraps the localization endpoints (initializing and translating content and pages into other locales), URL redirections, Personal Access Token management and the OAuth sign-in flow, plus webhook delivery history (`GetWebhookHistoryAsync`) and cascade publishing (`PublishContentItemCascadeAsync`, `PublishPageCascadeAsync`). The JavaScript SDK doesn't have methods for these yet, so from JavaScript you call those Management API endpoints directly.

> **Keeping this list honest.** These tables are generated from the published packages — `@agility/management-sdk` on npm and `Agility.Management.SDK` on NuGet — rather than written from memory. If you spot a difference, the packages win; please tell us so we can correct the page.

---

## Related pages

- [Batches and the Batch API](https://agilitycms.com/docs/javascript/management-sdk/batches.md)

Index of every docs page: https://agilitycms.com/docs/llms.txt
