> ## 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.

# Settings API

> Business configuration and site settings for platform behavior

# Kibo Settings API Developer Guide

## Understanding Settings in Kibo

In Kibo, **Settings** are the administrative controls that define the business logic and behavior of your e-commerce site. Unlike data that changes frequently (like orders or inventory), settings are configured once and then modified occasionally to adapt to business needs. They are the "switches and dials" of the platform.

What makes Kibo's approach different is the granularity and scope of its settings. They are not just a flat list of key-value pairs; they are structured, domain-specific JSON objects. For example, `InventorySettings` is a complete object that controls everything from backordering logic to how stock levels are displayed, while `ReturnSettings` governs the entire RMA workflow. Interacting with these settings programmatically allows you to automate site configuration, synchronize environments, and build powerful administrative tools.

## How This Domain Fits Into Kibo

The Settings domain is foundational. It underpins the logic of virtually every other part of the Kibo platform. The settings you configure dictate how the other APIs behave.

* **Inventory:** `InventorySettings` determine if a product can be backordered, which directly affects the **Inventory** and **Order** domains.
* **Fulfillment:** `ShippingSettings` define the origin address and other parameters used by the **Fulfillment** domain to calculate shipping costs.
* **Subscription:** `SubscriptionSettings` control fundamental subscription behaviors, like the next order date offset and how pricing is applied on continuity orders.
* **Returns:** `ReturnSettings` define the rules that the **Returns** API enforces, such as the valid window for a customer to initiate a return.

## 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 organizes its business logic into distinct, structured settings objects (based on official API specs).
* The key "read-then-write" pattern required to safely update settings (verified from apidocs.kibocommerce.com).
* Common workflows like enabling backordering or updating your shipping origin address programmatically.
* How to avoid the most common beginner mistake: accidentally deleting settings with a partial update.
* How to read and navigate the official Settings API documentation effectively.

***

## Kibo Settings Fundamentals

### How Kibo Organizes Settings Data

Kibo groups settings into logical, domain-specific objects. Each object is a complete document containing all the configurable properties for that domain. The primary objects you'll work with are:

* `GeneralSettings`: Site-wide information like name, contact info, and security settings.
* `InventorySettings`: Controls for stock levels, backordering, and out-of-stock behavior.
* `ReturnSettings`: Rules for the customer return process.
* `ShippingSettings`: The master configuration for order shipping, including origin address.
* `CartSettings`: Controls for the shopping cart behavior.
* `CustomerCheckoutSettings`: Rules for the customer-facing checkout process.
* `SubscriptionSettings`: Configuration for subscription products and continuity programs.

### 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 GeneralSettingsApi(configuration)`).

**Request/Response Structure:**
When you get a settings object, Kibo returns the complete JSON document for that domain.

```json theme={null}
// Actual response schema for GET /commerce/settings/general
{
  "isMozuWebstore": true,
  "isMultishipEnabled": false,
  "isTaxEstimationEnabled": true,
  "isUspsValidationEnabled": false,
  "siteName": "My Kibo Store",
  "siteTimezone": "Central Standard Time"
  // ... many other general settings
}
```

**The Required Update Pattern (GET then PUT):**
This is the most important pattern for settings. **The `update` endpoints use the `PUT` HTTP method, which performs a complete replacement of the object.** If you send only a partial object, you will wipe out all the other settings in that group. The only safe way to update a setting is to:

1. **GET** the full settings object.
2. **Modify** the specific property you want to change on that object.
3. **PUT** the entire, modified object back.

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

### Common Settings Workflows

1. **Environment Synchronization:** Reading settings from a production environment and programmatically applying them to a sandbox or staging environment to ensure consistency.
2. **Automated Configuration:** As part of a new site deployment script, automatically enabling or disabling features like guest checkout or backordering.
3. **Building Custom Admin Tools:** Creating a simplified UI for business users to change a specific setting without giving them full access to the Kibo Admin.

Let's explore the core pattern for a few key settings types.

***

## Managing General Settings: The Kibo Way

### When You Need This

This is the most basic settings operation, often used to update your site's name, timezone, or contact email programmatically. It serves as the introduction to the required "GET then PUT" pattern.

### API Documentation Reference

**Get Endpoint:** `GET /commerce/settings/general`
**Update Endpoint:** `PUT /commerce/settings/general`
**Method:** `GET`, `PUT`
**API Docs:** [/api-overviews/openapi\_settings\_overview#get-general-settings](/api-reference/generalsettings/get-general-settings)

### Understanding the Kibo Approach

Kibo groups all top-level site settings into a single `GeneralSettings` object. To ensure data integrity and prevent accidental misconfigurations, it requires you to submit the *entire* object when making a change. This forces you to acknowledge the current state of all other settings before applying an update.

### Code Structure Walkthrough

```typescript theme={null}
// We'll build this step by step:
// 1. **Configuration**: Create a central Configuration instance.
// 2. **API Client Instantiation**: Create a client for the General Settings API.
// 3. **GET Operation**: Fetch the current GeneralSettings object.
// 4. **Data Modification**: Change a value on the retrieved object.
// 5. **PUT Operation**: Send the entire modified object back to the API.
```

#### Step-by-Step Implementation

**Step 1: Setting Up the Foundation**

```ts theme={null}
// Essential imports for Settings operations.
// The SDK is organized by API groups; we import the clients for each settings area we need.
import { Configuration } from "@kibocommerce/rest-sdk";
import { GeneralSettingsApi, InventorySettingsApi, ReturnSettingsApi, ShippingSettingsApi, CartSettingsApi, CustomerCheckoutSettingsApi, SubscriptionSettingsApi } from "@kibocommerce/rest-sdk/clients/Settings";
import { GeneralSettings } from "@kibocommerce/rest-sdk/clients/Settings/models";

const configuration = new Configuration({
    tenantId: process.env.KIBO_TENANT_ID,
    siteId: process.env.KIBO_SITE_ID,
    clientId: process.env.KIBO_CLIENT_ID,
    sharedSecret: process.env.KIBO_SHARED_SECRET,
    authHost: process.env.KIBO_AUTH_HOST,
});
```

**Step 2: The Core Implementation**

```ts theme={null}
// Complete working example that ACTUALLY WORKS with the Kibo API
// This function updates the site's public email address.

async function updateSiteEmail(newEmail: string) {
    console.log("Updating site email address...");
    const generalSettingsClient = new GeneralSettingsApi(configuration);

    try {
        // 1. GET the current settings first. This is mandatory.
        console.log("Fetching current general settings...");
        const currentSettings = await generalSettingsClient.getGeneralSettings();

        // 2. Modify only the property you want to change on the retrieved object.
        console.log(`Changing email from '${currentSettings.replyToEmailAddress}' to '${newEmail}'`);
        currentSettings.replyToEmailAddress = newEmail;

        // 3. PUT the entire modified object back.
        const updatedSettings = await generalSettingsClient.updateGeneralSettings({
            generalSettings: currentSettings
        });

        console.log("Success! Site email has been updated.");
        return updatedSettings;

    } catch (error) {
        console.error("API Error updating general settings:", JSON.stringify(error, null, 2));
        throw error;
    }
}
```

### What Just Happened? (Code Explanation)

* The **setup phase** created the standard `Configuration` object.
* We instantiated the `GeneralSettingsApi` client to work with general settings.
* The **required step** was calling `getGeneralSettings()` *before* attempting the update. This gave us a complete object representing the current state.
* We then modified a single property on this local object.
* Finally, the `updateGeneralSettings()` call sent the **full object** back, ensuring that only our desired change was made while preserving all other existing settings.

### Common Beginner Mistakes

**Mistake 1:** Performing a partial update and deleting settings. This is the most dangerous mistake when working with settings.

```ts theme={null}
// Wrong - This will delete all other general settings.
await generalSettingsClient.updateGeneralSettings({
    generalSettings: { replyToEmailAddress: "new@example.com" }
});

// Correct - Always get the full object, modify it, then put it back.
const current = await generalSettingsClient.getGeneralSettings();
current.replyToEmailAddres = "new@example.com";
await generalSettingsClient.updateGeneralSettings({ generalSettings: current });
```

***

## Multiple Real-World Examples

The "GET then PUT" pattern applies to all settings. The only difference is the client and the structure of the settings object.

**Example 1: Enable Backordering (Inventory Settings)**

```ts theme={null}
async function enableBackordering() {
    const fulfillmentSettingsClient = new FulfillmentSettingsApi(configuration);
    console.log("Enabling backordering...");
    try {
        // 1. GET
        const currentSettings = await fulfillmentSettingsClient.getFulfillmentSettings();
        // 2. MODIFY
        currentSettings.fulfillmentJobSettings.releaseBackorderJob = {
            "partialReleaseEnabled": false,
            "isEnabled": true,
            "interval": 2
        }; // Verified from API schema
        // 3. PUT
        const updatedSettings = await fulfillmentSettingsClient.updateFulfillmentSettings({ fulfillmentSettings: currentSettings });
        console.log("Backordering is now enabled.");
        return updatedSettings;
    } catch (error) {
        console.error("Failed to enable backordering:", JSON.stringify(error, null, 2));
        throw error;
    }
}
```

**Example 2: Update the Return Restock Setting**

```ts theme={null}
async function setUpdateOnHandOnReturnStock(days: number) {
    const returnSettingsClient = new ReturnSettingsApi(configuration);
    console.log(`Setting return window to ${days} days...`);
    try {
        const currentSettings = await returnSettingsClient.getReturnSettings();
        currentSettings.updateInventoryOnRestock = true;
        const updatedSettings = await returnSettingsClient.updateReturnSettings({ returnSettings: currentSettings });
        console.log("Return window updated.");
        return updatedSettings;
    } catch (error) {
        console.error("Failed to update return window:", JSON.stringify(error, null, 2));
        throw error;
    }
}
```

**Example 3: Update Subscriptions Settings**

```ts theme={null}
async function updateSubscriptionSettings(allow: boolean) {
    const subscriptionSettingClient = new SubscriptionSettingsApi(configuration);
    try {
        const currentSettings = await subscriptionSettingClient.getSubscriptionSettings();
        currentSettings.continuityOrderDateOffset = 15;
        const updatedSettings = await subscriptionSettingClient.updateSubscriptionSettings({ subscriptionSettings: currentSettings });
        console.log(`Subscription continuity order date offset updated to ${currentSettings.continuityOrderDateOffset}.`);
        return updatedSettings;
    } catch (error) {
        console.error("Failed to continuity order date offset setting:", JSON.stringify(error, null, 2));
        throw error;
    }
}
```

***

## Integrating Settings with Other Kibo Domains

### Settings + Storefront Experience

Settings have a direct and immediate impact on the storefront. When you update `CustomerCheckoutSettings` to disallow guest checkout, the very next user who tries to check out without logging in will be blocked. When you update `CartSettings`, the `cross-sell` products a user sees may change. These settings are the primary way a business user configures the customer experience without changing code.

### Settings + Order Management

The entire order management lifecycle is governed by settings. `InventorySettings` control sourcing, `ShippingSettings` control rate calculation, and `ReturnSettings` control post-purchase workflows. Programmatically changing these settings allows you to adapt your fulfillment logic to changing conditions, such as disabling backorders during a supply chain disruption.

***

## Troubleshooting Your Settings Implementation

### Reading Kibo Error Messages

```typescript theme={null}
interface KiboApiError {
  errorCode: string;      // Specific error codes from apidocs.kibocommerce.com
  message: string;          // Error description
  correlationId: string;  // For support tracking
}
```

**Common Error Codes for Settings:**

* `VALIDATION_ERROR`: The request body is malformed or contains an invalid value for a setting (e.g., an incorrect enum value for `backorderBehavior`). The `message` field will often contain details about which property was invalid.
* `ITEM_NOT_FOUND`: Usually means the settings for that domain have not been initialized. This is rare.
* `UNAUTHORIZED`: Your API credentials do not have the permissions required to read or update settings.

### Common Development Issues

**Issue 1:** "I updated a setting, and now my entire site configuration is broken!"

* **Why it happens:** You fell into the most common trap: you performed a partial update using `PUT`. You sent a request body with only the single setting you wanted to change, which caused the Kibo API to delete all the other settings in that group.
* **How to fix it:** Immediately `GET` the settings from a backup environment (like Production) and `PUT` the full, correct object back into the broken environment.
* **How to avoid it:** **NEVER** call an `update` (PUT) endpoint for settings without first calling the corresponding `get` endpoint and modifying the result. Your code must always follow the "GET, Modify, PUT" pattern.
* **API Reference:** This applies to all `PUT` endpoints in the Settings API group.

**Issue 2:** "I'm trying to update a setting, but the API returns a `VALIDATION_ERROR` with a confusing message."

* **Why it happens:** The value you are trying to set is invalid for that specific property. Many settings properties are not free-form strings; they must be one of a specific set of enumerated values (e.g., `backorderBehavior` must be `AllowBackorder`, `AllowBackorderAndNotify`, or `EnterPendingOrder`).
* **How to fix it:** Carefully review the API documentation at `apidocs.kibocommerce.com` for the specific settings object you are working with. The schema definition will show the allowed values for each property. The `GET` response for that setting will also show you the currently valid value.
