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

# Getting Started

> Learn how to authenticate with the Commerce Engine API and make your first request.

## Before You Begin

Before you can start using the Commerce Engine API, you'll need a Commerce Engine account with at least one store configured. If you haven't already signed up, create an account and set up your first store through the Commerce Engine dashboard.

## Understanding Channels

Commerce Engine uses **Channels** to organize how customers interact with your store across different platforms. When you create a new store, Commerce Engine automatically creates a default **Web** channel for you.

### Channel Types

Commerce Engine supports four channel types:

* **Web** - For browser-based storefronts
* **App** - For mobile applications (iOS/Android)
* **POS** - For point-of-sale systems
* **Marketplace** - For third-party integrations (advanced use cases)

<Info>
  **Important:** API keys are scoped to both a store and a specific channel. A key generated for your Web channel should not be used for App or POS channel requests. Each channel requires its own API key.
</Info>

## Step 1: Generate Your API Key

To interact with the Commerce Engine Storefront API, you need to generate an API key for your channel.

<Steps>
  <Step title="Navigate to Settings">
    Log in to your Commerce Engine dashboard and navigate to **Settings** > **Channels** from the left sidebar.
  </Step>

  <Step title="Select Your Channel">
    Click on the channel you want to generate an API key for (typically your **Web** channel to get started).
  </Step>

  <Step title="Generate API Key">
    In the channel settings, find the **API Keys** section and click **Generate New API Key**.

    The dashboard will display your new API key. **Copy this key immediately** and store it somewhere secure.
  </Step>
</Steps>

<Warning>
  **API Key Security**

  While Storefront API keys are designed to be client-safe (they can be exposed in frontend code), you should still:

  * Never commit API keys directly to version control
  * Use environment variables in your projects
  * Rotate keys periodically for security
  * Use separate keys for staging and production environments
</Warning>

## Step 2: Choose Your Environment

Commerce Engine provides two environments for API access:

| Environment    | Base URL                                      | Purpose                 |
| -------------- | --------------------------------------------- | ----------------------- |
| **Staging**    | `https://staging.api.commercengine.io/api/v1` | Testing and development |
| **Production** | `https://prod.api.commercengine.io/api/v1`    | Live production traffic |

<Info>
  **Environment Isolation**

  Data is completely isolated between staging and production environments. However, **the same API key works in both environments**, making it easy to test in staging before deploying to production.

  We recommend using staging for all development and testing activities.
</Info>

## Step 3: Make Your First Request

Let's make your first API request to authenticate an anonymous user. This is the starting point for any Commerce Engine storefront integration.

### Authenticate an Anonymous User

Every visitor to your storefront starts as an anonymous user. This initial authentication step:

* Assigns a unique user ID for tracking
* Returns access and refresh tokens for the session
* Enables server-side analytics from the first interaction

<CodeGroup>
  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl -X POST 'https://staging.api.commercengine.io/api/v1/{store_id}/storefront/auth/anonymous' \
    --header 'X-Api-Key: YOUR_API_KEY' \
    --header 'Content-Type: application/json'
  ```

  ```javascript JavaScript (Fetch) theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const response = await fetch(
    'https://staging.api.commercengine.io/api/v1/{store_id}/storefront/auth/anonymous',
    {
      method: 'POST',
      headers: {
        'X-Api-Key': 'YOUR_API_KEY',
        'Content-Type': 'application/json'
      }
    }
  );

  const data = await response.json();
  console.log(data);
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
  import requests

  url = 'https://staging.api.commercengine.io/api/v1/{store_id}/storefront/auth/anonymous'
  headers = {
      'X-Api-Key': 'YOUR_API_KEY',
      'Content-Type': 'application/json'
  }

  response = requests.post(url, headers=headers)
  data = response.json()
  print(data)
  ```

  ```typescript TypeScript (Commerce Engine SDK) theme={"theme":{"light":"github-light","dark":"github-dark"}}
  import { CommerceEngineClient } from '@commercengine/sdk';

  const client = new CommerceEngineClient({
    storeId: 'YOUR_STORE_ID',
    apiKey: 'YOUR_API_KEY',
    environment: 'staging'
  });

  const { user, access_token, refresh_token } = await client.auth.anonymous();
  ```
</CodeGroup>

Replace `{store_id}` with your actual store ID (found in your dashboard) and `YOUR_API_KEY` with the API key you generated.

### Expected Response

If successful, you'll receive a response like this:

```json Response theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "message": "Anonymous user created successfully.",
  "success": true,
  "content": {
    "user": {
      "id": "01HXXXXXXANONYMOUSUSERID",
      "first_name": null,
      "last_name": null,
      "email": null,
      "phone": null,
      "is_anonymous": true,
      "is_logged_in": false,
      "created_at": "2024-10-28T10:30:00.000Z"
    },
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "refresh_token": "a1b2c3d4e5f6g7h8i9j0..."
  }
}
```

<Tip>
  **Store These Tokens Securely**

  The `access_token` and `refresh_token` are critical for all subsequent API requests:

  * **Access Token** - Include this in the `Authorization: Bearer` header for API calls
  * **Refresh Token** - Use this to obtain a new access token when the current one expires

  Store these securely on the client side (HttpOnly cookies for web, secure storage for mobile).
</Tip>

## Step 4: Make an Authenticated Request

Now that you have an access token, you can make authenticated requests to other API endpoints. Let's fetch the product catalog:

<CodeGroup>
  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl -X GET 'https://staging.api.commercengine.io/api/v1/{store_id}/storefront/catalog/products' \
    --header 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
    --header 'Content-Type: application/json'
  ```

  ```javascript JavaScript (Fetch) theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const response = await fetch(
    'https://staging.api.commercengine.io/api/v1/{store_id}/storefront/catalog/products',
    {
      method: 'GET',
      headers: {
        'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
        'Content-Type': 'application/json'
      }
    }
  );

  const products = await response.json();
  console.log(products);
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
  import requests

  url = 'https://staging.api.commercengine.io/api/v1/{store_id}/storefront/catalog/products'
  headers = {
      'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
      'Content-Type': 'application/json'
  }

  response = requests.get(url, headers=headers)
  products = response.json()
  print(products)
  ```

  ```typescript TypeScript (Commerce Engine SDK) theme={"theme":{"light":"github-light","dark":"github-dark"}}
  // Access token is automatically managed by the SDK
  const products = await client.catalog.listProducts();
  ```
</CodeGroup>

You should receive a list of products from your catalog. Congratulations - you've made your first authenticated API request!

## Understanding the API Structure

All Commerce Engine Storefront API endpoints follow this URL structure:

```
https://{environment}.api.commercengine.io/api/v1/{store_id}/storefront/{resource}
```

* `{environment}` - Either `staging` or `api` (for production)
* `{store_id}` - Your unique store identifier
* `{resource}` - The API resource you're accessing (e.g., `auth`, `catalog`, `carts`, `orders`)

## What You Can Do With the API

The Commerce Engine Storefront API enables you to build complete e-commerce experiences:

* **Authentication** - Anonymous users, passwordless login via OTP, social auth
* **Catalog** - Browse products, search, filter, and recommendations
* **Cart Management** - Add items, apply coupons, calculate shipping
* **Checkout** - Place orders, process payments, manage fulfillment
* **Customer Accounts** - Profile management, order history, addresses
* **Subscriptions** - Recurring orders and subscription management
* **Loyalty & Rewards** - Points, credits, and promotional campaigns

## Next Steps

Now that you're authenticated, explore these guides to build out your storefront:

<CardGroup cols={2}>
  <Card title="Authentication Guide" icon="lock" href="/storefront/authentication">
    Learn about user login, registration, and token management
  </Card>

  <Card title="Catalog & Products" icon="store" href="/storefront/catalog">
    Display products, handle search, and show recommendations
  </Card>

  <Card title="Cart & Checkout" icon="cart-shopping" href="/storefront/cart">
    Build shopping cart and checkout experiences
  </Card>

  <Card title="SDK Documentation" icon="node-js" href="/sdk/installation">
    Use our type-safe SDK for faster development
  </Card>
</CardGroup>

## Rate Limits & Best Practices

<Info>
  **API Rate Limits**

  Commerce Engine enforces rate limits to ensure API stability:

  * **Staging:** 100 requests per minute per API key
  * **Production:** 1000 requests per minute per API key

  Rate limit headers are included in all responses to help you monitor usage.
</Info>

### Best Practices

1. **Token Management** - Implement automatic token refresh to maintain uninterrupted sessions
2. **Error Handling** - Always check response status codes and handle errors gracefully
3. **Caching** - Cache catalog data and configuration to reduce API calls
4. **Webhooks** - Use webhooks for real-time order and payment updates instead of polling

## Getting Help

Need assistance? We're here to help:

* **Documentation** - Explore our comprehensive [API Reference](/api-reference) and [Guides](/storefront/quickstart)
* **Support** - Email us at [support@commercengine.io](mailto:support@commercengine.io)
* **Community** - Join discussions on our [GitHub](https://github.com/tark-ai)

Ready to build? Dive into the [Authentication Guide](/storefront/authentication) to learn how to handle user login and registration.
