> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kibocommerce.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Admin User API

> User management, roles, and permissions for Kibo platform administrators

# Kibo Admin User API Developer Guide

<Card title="Administration" icon="book-open" href="/pages/administration" horizontal data-rec="developer-backlink">
  Manage admin users and permissions
</Card>

## Understanding Admin User in Kibo

In Kibo, it's important to distinguish between two types of "users": a **Customer Account** and an **Admin User**. Customer accounts are for shoppers who buy things on your storefront. **Admin Users**, the focus of this guide, are the people who manage your business—your merchandisers, marketers, customer service reps, and developers.

Kibo treats Admin Users as a core security and operational concept. Instead of a flat list of users, Kibo uses a Role-Based Access Control (RBAC) system. Each Admin User is assigned one or more **Roles** (e.g., "Merchandiser," "Content Manager"), and each Role is a collection of specific permissions (called "Behaviors") that dictate exactly what that user can see and do within the Kibo platform.

## How This Domain Fits Into Kibo

Admin User management is the foundation of platform security and team collaboration. While it doesn't directly interact with the live storefront like the Catalog or Cart APIs, it controls who has the power to *change* those things. Every significant action in Kibo, from updating product price to canceling an order, is logged with the `userId` of the administrator who performed it. Proper user management is therefore important for auditing, security, and day-to-day operations.

## Prerequisites

* Kibo API credentials and basic setup
* Node.js 16+ with TypeScript
* Familiarity with REST APIs

## What You'll Learn

After completing this guide, you'll understand:

* How Kibo structures Admin User data, including Roles and Permissions (based on official API specs).
* The key patterns Kibo uses for creating users and managing their roles (verified from apidocs.kibocommerce.com).
* Common workflows like onboarding new team members and auditing user access.
* How to avoid the most common beginner mistakes, like confusing Admin Users with Shopper Customers.
* How to read and navigate the official User Administration API documentation effectively.

***

## Kibo Admin User Fundamentals

### How Kibo Organizes Admin User Data

Kibo's user model is a classic Role-Based Access Control (RBAC) system. Here are the core data structures:

* **User:** The central object representing a person. Key properties include `userId` (a unique integer assigned by Kibo), `emailAddress`, `firstName`, `lastName`, and an `isActive` flag.
* **Role:** A named collection of permissions, like "Administrator" or "Fulfiller." You interact with these via a `roleId`.
* **Behaviors:** These are the granular permissions that make up a Role (e.g., "Read Products," "Update Orders"). You typically don't interact with these directly via the API but assign them to Roles within the Kibo Admin UI.

The relationship is simple: A **User** is assigned one or more **Roles**.

### Key Kibo Patterns You'll See Everywhere

Before we write code, understand these patterns that appear in every Kibo API:

**Authentication Pattern:**
The Kibo SDK manages authentication for you. You create a single `Configuration` object containing your credentials (Client ID, Shared Secret, etc.). This object is then passed to the constructor of specific API clients (e.g., `new AdminUserApi(configuration)`). The clients will automatically handle the OAuth 2.0 token exchange behind the scenes for every API call.

**Request/Response Structure:**
When you request a collection of resources, Kibo's API provides a consistent, paginated response. The actual data is always inside the `items` array.

```json theme={null}
// Actual response schema for GET /commerce/admin/users
{
    "startIndex": 0,
    "pageSize": 20,
    "pageCount": 7,
    "totalCount": 136,
    "items": [
        {
            "emailAddress": "Bob.Kibo@kibocommerce.com",
            "userName": "Bob.Kibo@kibocommerce.com",
            "localeCode": "us_EN",
            "firstName": "Bob",
            "lastName": "Kibo",
            "optInToEmail": false,
            "optInToTextMessage": false,
            "id": "081686eb0e214972a86c7812e6fdb6f4",
            "systemData": {
                "isPasswordChangeRequired": false,
                "lastPasswordChangeOn": "2020-02-26T16:38:41.397Z",
                "isLocked": false,
                "failedLoginAttemptCount": 0,
                "remainingLoginAttempts": 15,
                "lastLoginOn": "2022-02-07T18:52:29.602Z",
                "createdOn": "2020-02-26T16:38:41.386Z",
                "updatedOn": "2020-02-26T16:38:41.397Z"
            },
            "isActive": true
        }
    ]
}
```

**Error Handling Approach:**
If an API call fails, the SDK will throw a structured error object. This helps you programmatically handle failures instead of just getting a generic HTTP status code.

```json theme={null}
// Actual error schema from Kibo
{
    "message": "User with the specified user name already exists.",
    "errorCode": "USER_ALREADY_EXISTS",
    "correlationId": "e0b5b9b0-a5f1-4f1e-9a0c-12345abcdef"
}
```

**Pagination and Filtering:**
To manage large datasets, Kibo uses `pageSize` and `startIndex` parameters. For refining results, the powerful `filter` parameter allows you to query for specific data, like `filter=isActive eq true`.

**API Documentation Reference:**
Throughout this guide, we'll reference specific endpoints. Find complete specs at:
`/api-overviews/openapi_tenant_and_user_overview`

### Common Admin User Workflows

Kibo developers typically work with Admin Users in these scenarios:

1. **Onboarding a New Employee:** Creating a user account and assigning the correct starting role.
2. **Auditing User Access:** Programmatically listing all users and the roles they are assigned to for a security review.
3. **Offboarding an Employee:** Deactivating or deleting a user's account to revoke their access.

Let's explore each pattern step by step.

***

## Getting a List of Admin Users: The Kibo Way

### When You Need This

This is your starting point for almost any user management task. You need it when you want to display a list of users in a custom dashboard, find a specific user to update, or perform a bulk operation.

### API Documentation Reference

**Endpoint:** `GET /commerce/admin/users`
**Method:** `GET`
**API Docs:** [Get Users](/api-reference/adminuser/get-users)

### Understanding the Kibo Approach

Kibo treats fetching users as a potentially large-scale operation. Therefore, it never returns all users at once. It forces you to think about pagination from the start by using `pageSize` and `startIndex`. This is a defensive design that ensures performance and stability.

### Code Structure Walkthrough

Before we implement, let's understand what we're building (based on actual API requirements):

```typescript theme={null}
// We'll build this step by step:
// 1. **Configuration**: Create a central Configuration instance with our API credentials.
// 2. **API Client Instantiation**: Create a dedicated client for the User Administration API.
// 3. **Data Preparation**: Define parameters for pagination and filtering.
// 4. **API Call**: Use the instantiated client to call the `getUsers` method.
```

#### Step-by-Step Implementation

**Step 1: Setting Up the Foundation**

```ts theme={null}
// Essential imports for Admin User operations.
// The SDK is organized by API groups; we import the Configuration class and the AdminUserApi and RoleApi clients.
// These imports are verified from @kibocommerce/rest-sdk documentation.
import { Configuration } from "@kibocommerce/rest-sdk";
import { AdminUserApi, RoleApi } from "@kibocommerce/rest-sdk/clients/AdminUser";
import { User } from "@kibocommerce/rest-sdk/clients/AdminUser/models";

// Configuration setup - this single object is reused for all API clients.
// It holds all necessary credentials for authentication and routing.
// These properties are required per official API documentation.
const configuration = new Configuration({
    tenantId: process.env.KIBO_TENANT_ID,
    siteId: process.env.KIBO_SITE_ID, // Although not always used, it's good practice
    clientId: process.env.KIBO_CLIENT_ID,
    sharedSecret: process.env.KIBO_SHARED_SECRET,
    authHost: process.env.KIBO_AUTH_HOST,
});
```

**Step 2: Understanding the Data Flow**
When we call `getUsers`, our request (including pagination parameters) goes to the Kibo API. The API queries its user database, constructs a response object containing a page of results (`items`) and metadata (`totalCount`, etc.), and sends it back.

**Step 3: The Core Implementation**

```ts theme={null}
// Complete working example that ACTUALLY WORKS with the Kibo API
// Each line verified against official API documentation
// Focus on explaining WHY each step is necessary in Kibo's system

async function getAllActiveUsers(): Promise<User[]> {
    console.log("Fetching all active users...");

    // 1. Instantiate a dedicated client for the User Administration API.
    //    The SDK separates APIs into logical clients for better organization and type safety.
    const adminUserClient = new AdminUserApi(configuration);

    try {
        // 2. Call the method on the client. We are using a filter to get only active users.
        //    The method name `getUsers` directly corresponds to the API operation.
        //    The parameters like `filter` are defined in the API documentation.
        const response = await adminUserClient.getUsers({
            filter: "isActive eq true",
            pageSize: 200 // Fetch up to 200 per page, the max allowed
        });

        console.log(`Successfully fetched ${response.items?.length} of ${response.totalCount} total active users.`);
        return response.items || [];
    } catch (error) {
        // The SDK throws a structured error object on failure.
        console.error("API Error fetching users:", JSON.stringify(error, null, 2));
        throw error;
    }
}

// Example usage:
// getAllActiveUsers().then(users => {
//     console.log("Users:", users);
// });
```

### What Just Happened? (Code Explanation)

* The **setup phase** created a single `Configuration` object. This is the source of truth for all API credentials and is passed to every client.
* The **API call** was made using an instance of `AdminUserApi`. This client has type-safe methods (like `getUsers`) that match the available operations in the User Administration API group.
* We passed a **`filter` parameter** (`isActive eq true`) to instruct Kibo's servers to do the filtering for us, which is much more efficient than fetching all users and filtering them in our own code.
* The **response handling** safely accesses the `items` array from the response and includes error handling for API failures.

### Common Beginner Mistakes

**Mistake 1:** Forgetting about pagination and assuming the first call returns all users.

```ts theme={null}
// Wrong - This only gets the first page of users (default is 20).
const response = await adminUserClient.getUsers();
const allUsers = response.items; // This is NOT all users if you have more than 20.

// Correct - Check `totalCount` and make subsequent calls with an incremented `startIndex` if needed.
// (An advanced pattern would be to loop until all pages are fetched).
```

**Mistake 2:** Confusing Admin Users (`AdminUserApi`) with Shopper Accounts (`CustomerAccountApi`).

```ts theme={null}
// Wrong - This API is for storefront customer accounts, not backend users.
import { CustomerAccountApi } from "@kibocommerce/rest-sdk/clients/Customer";
const customerClient = new CustomerAccountApi(configuration);
// await customerClient.getAccounts(); // This will not return your admin users.

// Correct - Always use the `AdminUserApi` for managing merchandisers, admins, etc.
const adminUserClient = new AdminUserApi(configuration);
```

**Mistake 3:** Using the user's email address as the `userId` in subsequent API calls. The API requires the integer `userId`.

### How This Connects to Other Kibo Operations

Fetching users is the first step in almost any other user operation. Before you can **update**, **delete**, or **manage roles**, you first need to get the `userId` of the user you want to modify.

***

## Creating a New User and Assigning a Role

This is a two-step process in Kibo, and understanding that is key. You first create the user, then you make a second API call to assign a role.

### When You Need This

This workflow is essential for automating the onboarding of new employees. For example, a script could be triggered from your HR system to create a Kibo account for a new merchandiser.

### API Documentation Reference

1. **Create User:**
   * **Endpoint:** `POST /commerce/admin/users`
   * **Method:** `POST`
   * **API Docs:** [Create User](/api-reference/adminuser/create-user)
2. **Add User Role:**
   * **Endpoint:** `POST /commerce/admin/users/{userId}/roles/{roleId}`
   * **Method:** `POST`
   * **API Docs:** [Add User Role](/api-reference/adminuser/add-user-role)

### Understanding the Kibo Approach

Kibo separates user creation from role assignment for clarity and security. This atomic design ensures that you can't accidentally create a user with the wrong permissions in a single, complex request. It forces a deliberate, two-step process: establish the identity, then grant the permissions.

#### Step-by-Step Implementation

```ts theme={null}
// Complete, production-ready example verified against API docs
// This function creates a user and then assigns them a specific role.

async function onboardNewUser(
    userData: {
        firstName: string;
        lastName: string;
        emailAddress: string;
    },
    roleIdToAssign: number
): Promise<User> {
    const adminUserClient = new AdminUserApi(configuration);

    // --- Step 1: Create the User ---
    let newUser: User;
    try {
        console.log(`Creating user for ${userData.emailAddress}...`);

        // The request body must match the schema defined in the API documentation.
        // `userName` is often the same as `emailAddress`.
        const userPayload = {
            ...userData,
            userName: userData.emailAddress,
            isActive: true, // It's best practice to create users as active.
        };

        // The `createUser` method corresponds to the POST /commerce/admin/users endpoint.
        newUser = await adminUserClient.createUser({ user: userPayload });
        console.log(`Successfully created user with ID: ${newUser.id}`);

    } catch (error) {
        console.error("API Error creating user:", JSON.stringify(error, null, 2));
        // If creation fails, we can't proceed to assign roles.
        throw new Error("Failed to create the user.");
    }

    // --- Step 2: Assign the Role ---
    try {
        console.log(`Assigning role ${roleIdToAssign} to user ${newUser.id}...`);

        // The `addUserRole` method requires both the new userId and the roleId.
        // It does not have a request body.
        await adminUserClient.addUserRole({
            userId: `${newUser.id}`, // The SDK expects a number
            roleId: roleIdToAssign,
        });

        console.log("Successfully assigned role.");
        return newUser;

    } catch (error) {
        console.error("API Error assigning role:", JSON.stringify(error, null, 2));
        // This is a serious failure. The user was created but has no permissions.
        // In a production system, you might want to automatically deactivate or delete the user here.
        throw new Error("User was created but role assignment failed.");
    }
}

// Example Usage:
// Let's assume you've already fetched roles and found the ID for "Content Manager" is 5.
// onboardNewUser(
//     {
//         firstName: "Jane",
//         lastName: "Smith",
//         emailAddress: "jane.smith@example.com",
//     },
//     5 // The roleId for "Content Manager"
// ).then(createdUser => {
//     console.log("Onboarding complete:", createdUser);
// });
```

***

## Advanced Admin User Patterns

### When You've Mastered the Basics

Now that you understand Kibo's fundamental approach, let's explore more sophisticated patterns using actual API capabilities.

### Pattern 1: Role Auditing Script

**Business Scenario:** A security manager needs a CSV report of every user and which roles they are assigned to.

**Kibo's Architecture Consideration:** There is no single endpoint to get users *and* their roles simultaneously. This is intentional to keep the API responses lean. The correct pattern is to first get all users, then iterate through each user to fetch their assigned roles.

**API Endpoints Used:**

* `GET /commerce/admin/users`
* `GET /commerce/admin/users/{userId}/roles`
* **Full API Reference:** [Get Users](/api-reference/adminuser/get-users)

**Implementation Strategy:**
This implementation demonstrates how to chain API calls together to build a complete data picture. It also shows how to handle potential failures for a single user without stopping the entire process.

```typescript theme={null}
import { Role } from "@kibocommerce/rest-sdk/clients/AdminUser/models";

// This pattern builds on the patterns from earlier sections
async function generateUserRoleReport() {
    const adminUserClient = new AdminUserApi(configuration);
    const report: { email: string; roles: string[]; error?: string }[] = [];

    // 1. Get all users (in a real app, handle pagination here)
    const usersResponse = await adminUserClient.getUsers({ pageSize: 200 });
    const users = usersResponse.items || [];

    console.log(`Found ${users.length} users. Fetching roles for each...`);

    // 2. Loop through each user to get their roles
    for (const user of users) {
        if (!user.userId || !user.emailAddress) continue;

        try {
            // 3. For each user, call the getUserRoles endpoint
            const rolesResponse: AdminUserUserRoleCollection = await adminUserClient.getUserRoles({ userId: user.userId });
            // Map role names and filter out null/undefined to ensure string[] type.
            const roleNames = (rolesResponse.items || [])
                .map(role => role.roleName)
                .filter((name): name is string => typeof name === 'string');
            report.push({ email: user.emailAddress, roles: roleNames });
        } catch (error: any) {
            // Handle cases where a single user role lookup might fail
            console.warn(`Could not fetch roles for ${user.emailAddress}: ${error.message}`);
            report.push({ email: user.emailAddress, roles: [], error: "Failed to fetch roles" });
        }
    }

    console.log("--- User Role Report ---");
    console.table(report);
    // In a real application, you would convert this `report` array to a CSV file.
    return report;
}
```

***

### Multiple Real-World Examples

Here are 5 complete, runnable examples for common `Admin User` operations.

**Example 1: Find a Specific User by Email**

```ts theme={null}
async function findUserByEmail(email: string): Promise<User | undefined> {
    const adminUserClient = new AdminUserApi(configuration);
    try {
        // Use the 'filter' parameter to query by email address.
        const response = await adminUserClient.getUsers({
            filter: `emailAddress eq '${email}'`,
        });
        if (response.totalCount === 0 || !response.items) {
            console.log(`No user found with email: ${email}`);
            return undefined;
        }
        return response.items[0];
    } catch (error) {
        console.error("API Error finding user by email:", JSON.stringify(error, null, 2));
        throw error;
    }
}
```

**Example 2: Remove a Role from a User**

```ts theme={null}
async function removeRoleFromUser(userId: string, roleId: number): Promise<void> {
    const adminUserClient = new AdminUserApi(configuration);
    try {
        // The removeUserRole method corresponds to the DELETE operation.
        // It returns a 204 No Content on success, so the result is void.
        await adminUserClient.removeUserRole({ userId, roleId });
        console.log(`Successfully removed role ${roleId} from user ${userId}.`);
    } catch (error) {
        console.error("API Error removing user role:", JSON.stringify(error, null, 2));
        throw error;
    }
}
```

**Example 3: Get All Available Roles**

```ts theme={null}
async function getAllRoles(): Promise<Role[]> {
    const roleClient = new RoleApi(configuration);
    try {
        const roles = await roleClient.getRoles();
        console.log(`Found ${roles.length} available roles.`);
        return roles;
    } catch (error) {
        console.error("API Error fetching roles:", JSON.stringify(error, null, 2));
        throw error;
    }
}
```

**Example 4: A Complete Offboarding Function (Remove All Roles)**

```ts theme={null}
async function offboardUser(userId: string): Promise<void> {
    const adminUserClient = new AdminUserApi(configuration);
    console.log(`Starting offboarding for user ${userId}...`);

    // 1. Get all roles currently assigned to the user.
    const assignedRoles = await adminUserClient.getUserRoles({ userId });
    console.log(`User has ${assignedRoles.length} roles to be removed.`);

    // 2. Loop and remove each role.
    for (const role of assignedRoles || []) {
        if (!role.roleId) continue;
        await removeRoleFromUser(userId, role.roleId);
    }

    console.log(`Offboarding for user ${userId} complete.`);
}
```

***

## Integrating Admin User with Other Kibo Domains

Understanding how `Admin User` connects to other parts of Kibo helps you build more effective solutions.

### Admin User + Orders Integration

When an administrator manually edits an order (e.g., adds a discount, changes the shipping address), their `userId` is stored in the order's `auditInfo` block. This creates a clear audit trail. You can use the Admin User API to cross-reference this `userId` to find out who made the change (e.g., `John Doe (j.doe@example.com)`).

### Admin User + Catalog Data Integration

Similarly, every change to a product in your catalog—a price update, a new image, a changed description—is logged against the `userId` of the merchandiser who performed the action. This is useful for tracking down unauthorized or accidental changes.

### Performance Considerations

* **Filter, Don't Fetch:** Always use the `filter` query parameter (`filter=emailAddress eq '...'`) when you need a specific user or subset of users. It is vastly more performant than fetching all users and filtering them in your code.
* **Paginate Wisely:** Never try to fetch thousands of users in a single API call. Use the `pageSize` (max 200) and `startIndex` parameters to loop through pages of results.
* **Cache Roles:** The list of available roles (`getRoles`) changes infrequently. For applications that need to display roles, it's a good practice to cache this API call's response for a few hours to reduce redundant API traffic.

***

## Troubleshooting Your Admin User Implementation

### Reading Kibo Error Messages

Kibo's error responses follow specific patterns. Here's how to decode them (verified from actual API responses):

```typescript theme={null}
// Actual error structure from Kibo API documentation
interface KiboApiError {
  errorCode: string;      // Specific error codes from apidocs.kibocommerce.com
  message: string;          // Error description
  correlationId: string;  // For support tracking
  // The actual error thrown by the SDK will have more properties like status and headers.
}
```

**Common Error Codes for Admin User:** (from official API documentation)

* `USER_ALREADY_EXISTS`: Occurs when using `createUser` with an email/username that is already taken.
* `USER_NOT_FOUND`: Occurs when providing an invalid `userId` to endpoints like `updateUser`, `getUserRoles`, or `deleteUser`.
* `VALIDATION_ERROR`: The request body for creating or updating a user is missing required fields (e.g., `emailAddress`) or contains invalid data.
* `ROLE_NOT_FOUND`: You tried to add or remove a `roleId` that does not exist.

**Reference:** [Status Codes](/pages/status-codes)

### Common Development Issues

**Issue 1:** `401 Unauthorized` Error on Every API Call

* **Why it happens:** Your API credentials in the `Configuration` object are incorrect, or the API key you are using does not have the required permissions (Behaviors) for the User Administration API.
* **How to fix it:**
  1. Carefully verify your `clientId`, `sharedSecret`, `tenantId`, and `authHost`.
  2. In the Kibo Dev Center, check that your Application has been granted permissions like `user.read`, `user.create`, `user.update`, etc.
* **API Reference:** [Introduction to the KCCP UIs](/pages/introduction-to-the-kccp-uis)

**Issue 2:** Creating a user works, but assigning a role immediately after fails.

* **Why it happens:** There can sometimes be a very brief replication delay between when a user is created in Kibo's identity system and when it's available to have a role assigned.
* **How to fix it:** While rare, a simple retry mechanism with a short delay (e.g., wait 500ms and try the `createUserRole` call again) can make your integration more robust.
* **How to avoid it:** Structure your error handling to catch failures on the role assignment step and log them for manual review or automated retry.

### Debugging Checklist

When your Admin User implementation isn't working:

1. Verify endpoint URL matches `apidocs.kibocommerce.com` exactly.
2. Confirm request body for `createUser` or `updateUser` matches the required schema in the API docs.
3. Check authentication credentials in your `Configuration` object.
4. Validate that the `userId` and `roleId` are integers, not strings or objects.
5. Review the `errorCode` in the API error response - it tells you exactly what went wrong.
6. Check your application's permissions in the Kibo Dev Center.
7. Ensure you are using `AdminUserApi` and not another client like `CustomerAccountApi`.
