SellerLegend API Documentation

Comprehensive API for Amazon seller data management and analytics

Base URL
https://app.sellerlegend.com/api
Version
v1.0.0
Auth
OAuth 2.0 Bearer

Authentication

The SellerLegend API uses OAuth 2.0 Authorization Code flow as the only authentication method for full API access.

Step 1: Register Your Application

Before you can use the API, you need to register your application in SellerLegend:

  1. Log in to your SellerLegend account
  2. Navigate to Admin → Developers
  3. Click on "Create New Client"
  4. Fill in your application details:
    • Name: Your application name
    • Redirect URL: Your OAuth callback URL (e.g., https://yourapp.com/callback)
  5. Click "Create" to generate your credentials
Important: Save your Client ID and Client Secret immediately. The Client Secret will only be shown once for security reasons.
{
  "client_id": "your-generated-client-id",
  "client_secret": "your-generated-client-secret",
  "redirect_uri": "https://yourapp.com/callback"
}

Step 2: Redirect User to SellerLegend for Authorization

Redirect the user to SellerLegend's authorization page where they will log in and approve your application:

Authorization URL Structure:
https://app.sellerlegend.com/oauth/authorize?client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&response_type=code&state={STATE}
Parameters:
  • client_id - Your application's Client ID
  • redirect_uri - Must match the redirect URI registered with your application
  • response_type - Must be "code"
  • state - (Optional) Any value you want to receive back in the callback (e.g., your internal user ID)
Code Examples:
from sellerlegend_api import SellerLegendClient
from flask import Flask, redirect, session

app = Flask(__name__)

@app.route('/login')
def login():
    # Initialize SDK client
    client = SellerLegendClient(
        client_id='your-client-id',
        client_secret='your-client-secret',
        redirect_uri='https://yourapp.com/callback'
    )

    # Get authorization URL
    # State can be any value you want to receive back (e.g., user_id)
    auth_url, state = client.get_authorization_url(
        state="user123"  # Optional: your internal user ID or session ID
    )

    # Save state if you want to verify it later (optional)
    session['oauth_state'] = state

    return redirect(auth_url)
<?php
session_start();

// Build authorization URL
$params = [
    'client_id' => 'your-client-id',
    'redirect_uri' => 'https://yourapp.com/callback',
    'response_type' => 'code',
    'state' => 'user123'  // Optional: your internal user ID or session ID
];

$auth_url = 'https://app.sellerlegend.com/oauth/authorize?' . http_build_query($params);

// Optionally save state for verification
$_SESSION['oauth_state'] = 'user123';

// Redirect user to SellerLegend
header('Location: ' . $auth_url);
exit;
function redirectToAuth() {
    // Build authorization URL
    const params = new URLSearchParams({
        client_id: 'your-client-id',
        redirect_uri: 'https://yourapp.com/callback',
        response_type: 'code',
        state: 'user123'  // Optional: your internal user ID or session ID
    });

    // Optionally store state for later verification
    sessionStorage.setItem('oauth_state', 'user123');

    const authUrl = `https://app.sellerlegend.com/oauth/authorize?${params}`;

    // Redirect user
    window.location.href = authUrl;
}
# Direct the user to this URL in their browser:
https://app.sellerlegend.com/oauth/authorize?client_id=your-client-id&redirect_uri=https://yourapp.com/callback&response_type=code&state=user123

# Note: state parameter is optional, can be any value you want to receive back

Step 3: Handle Callback and Exchange Code for Tokens

After the user approves your application, they will be redirected to your callback URL with an authorization code:

https://yourapp.com/callback?code=AUTHORIZATION_CODE&state=YOUR_STATE_VALUE
Important: The authorization code is single-use and expires quickly (usually within 10 minutes). Exchange it immediately for tokens.
Token Exchange Endpoint:
POST /oauth/token
Complete Code Examples:
from sellerlegend_api import SellerLegendClient
from flask import Flask, request, session
from datetime import datetime, timedelta
import sqlite3

app = Flask(__name__)

@app.route('/callback')
def callback():
    # Get the authorization code
    code = request.args.get('code')
    if not code:
        return "Authorization code not provided", 400

    # Get state if you sent one (optional)
    state = request.args.get('state')  # Will be 'user123' from our example

    # Initialize SDK client
    client = SellerLegendClient(
        client_id='your-client-id',
        client_secret='your-client-secret',
        redirect_uri='https://yourapp.com/callback'
    )

    try:
        # Exchange code for tokens using SDK
        token_info = client.authenticate_with_authorization_code(code, state)

        # Store tokens in database
        store_tokens_in_database(
            user_id=state,  # Using state as user_id in this example
            access_token=token_info['access_token'],
            refresh_token=token_info['refresh_token'],
            expires_in=token_info['expires_in']
        )

        return "Authentication successful! Tokens stored."
    except Exception as e:
        return f"Authentication failed: {e}", 400

def store_tokens_in_database(user_id, access_token, refresh_token, expires_in):
    # Example using SQLite
    conn = sqlite3.connect('tokens.db')
    cursor = conn.cursor()

    expires_at = datetime.utcnow() + timedelta(seconds=expires_in)

    cursor.execute("""
        INSERT INTO user_tokens (user_id, access_token, refresh_token, expires_at)
        VALUES (?, ?, ?, ?)
        ON CONFLICT(user_id) DO UPDATE SET
            access_token = excluded.access_token,
            refresh_token = excluded.refresh_token,
            expires_at = excluded.expires_at,
            updated_at = CURRENT_TIMESTAMP
    """, (user_id, access_token, refresh_token, expires_at))

    conn.commit()
    conn.close()
    print(f"Tokens stored for user {user_id}")
<?php
session_start();

// Callback handler
if ($_SERVER['REQUEST_URI'] == '/callback') {
    // Get the authorization code
    $code = $_GET['code'] ?? null;
    if (!$code) {
        die('Authorization code not provided');
    }

    // Get state if you sent one (optional)
    $state = $_GET['state'] ?? null;  // Will be 'user123' from our example

    // Exchange code for tokens
    $tokenUrl = 'https://app.sellerlegend.com/api/oauth/token';

    $data = [
        'grant_type' => 'authorization_code',
        'client_id' => 'your-client-id',
        'client_secret' => 'your-client-secret',
        'code' => $code,
        'redirect_uri' => 'https://yourapp.com/callback'
    ];

    $ch = curl_init($tokenUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode === 200) {
        $tokens = json_decode($response, true);

        // Store tokens in database
        storeTokensInDatabase(
            $state,  // Using state as user_id in this example
            $tokens['access_token'],
            $tokens['refresh_token'],
            $tokens['expires_in']
        );

        echo "Authentication successful! Tokens stored.";
    } else {
        die("Token exchange failed: " . $response);
    }
}

function storeTokensInDatabase($userId, $accessToken, $refreshToken, $expiresIn) {
    // Example using PDO
    $pdo = new PDO('mysql:host=localhost;dbname=yourdb', 'username', 'password');

    $stmt = $pdo->prepare("
        INSERT INTO user_tokens (user_id, access_token, refresh_token, expires_at)
        VALUES (:user_id, :access_token, :refresh_token, :expires_at)
        ON DUPLICATE KEY UPDATE
            access_token = :access_token,
            refresh_token = :refresh_token,
            expires_at = :expires_at,
            updated_at = NOW()
    ");

    $stmt->execute([
        ':user_id' => $userId,
        ':access_token' => $accessToken,
        ':refresh_token' => $refreshToken,
        ':expires_at' => date('Y-m-d H:i:s', time() + $expiresIn)
    ]);

    echo "Tokens stored for user $userId";
}
// Handle callback and exchange code for tokens
async function handleCallback() {
    const urlParams = new URLSearchParams(window.location.search);

    // Get the authorization code
    const code = urlParams.get('code');
    if (!code) {
        throw new Error('Authorization code not provided');
    }

    // Get state if you sent one (optional)
    const state = urlParams.get('state');  // Will be 'user123' from our example

    // Exchange code for tokens
    const tokenUrl = 'https://app.sellerlegend.com/api/oauth/token';

    const data = new URLSearchParams({
        grant_type: 'authorization_code',
        client_id: 'your-client-id',
        client_secret: 'your-client-secret',
        code: code,
        redirect_uri: 'https://yourapp.com/callback'
    });

    try {
        const response = await fetch(tokenUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: data
        });

        if (response.ok) {
            const tokens = await response.json();

            // Store tokens in your backend
            await storeTokensInBackend({
                user_id: state,  // Using state as user_id in this example
                access_token: tokens.access_token,
                refresh_token: tokens.refresh_token,
                expires_in: tokens.expires_in
            });

            console.log('Authentication successful! Tokens stored.');
            return tokens;
        } else {
            throw new Error(`Token exchange failed: ${await response.text()}`);
        }
    } catch (error) {
        console.error('Token exchange error:', error);
        throw error;
    }
}

async function storeTokensInBackend(tokenData) {
    // Send tokens to your backend for secure storage
    const response = await fetch('/api/store-tokens', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(tokenData)
    });

    if (!response.ok) {
        throw new Error('Failed to store tokens');
    }

    console.log(`Tokens stored for user ${tokenData.user_id}`);
}

// Call this when page loads on callback URL
if (window.location.pathname === '/callback') {
    handleCallback();
}
# Extract the code from the callback URL
# Example callback: https://yourapp.com/callback?code=abc123&state=user123

CODE="abc123"  # Extract this from the URL
STATE="user123"  # Optional: will be whatever value you sent

# Exchange the code for tokens
curl -X POST https://app.sellerlegend.com/api/oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=authorization_code" \
  -d "client_id=your-client-id" \
  -d "client_secret=your-client-secret" \
  -d "code=$CODE" \
  -d "redirect_uri=https://yourapp.com/callback"

# Response:
# {
#   "token_type": "Bearer",
#   "expires_in": 1296000,  # 15 days in seconds
#   "access_token": "eyJ0eXAiOiJKV1...",
#   "refresh_token": "def50200..."
# }

# Store these tokens in your database immediately!
Response Format:
{
  "token_type": "Bearer",
  "expires_in": 1296000,  // 15 days in seconds
  "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI...",
  "refresh_token": "def50200642ba5c72a6c7f4a7a5b..."
}
Next Steps:
  • Store both tokens securely in your database
  • Use the access token for API requests
  • Refresh the token before it expires (see Step 5)

Step 4: Use the Access Token

Include the access token in the Authorization header of all API requests:

Code Examples:
from sellerlegend_api import SellerLegendClient

# Initialize client with access token
client = SellerLegendClient(
    access_token='your-access-token'
)

# Get user information
user_info = client.user.get_current_user()
print(f"User: {user_info['name']}")
print(f"Email: {user_info['email']}")

# Get user accounts
accounts = client.user.get_accounts()
for account in accounts['data']:
    print(f"Account: {account['title']}")

# Get orders with account selection
orders = client.sales.get_orders(
    account_title='My Store US',
    per_page=500,
    start_date='2024-01-01',
    end_date='2024-01-31'
)

for order in orders['data']:
    print(f"Order: {order['amazon_order_id']}")
    print(f"Total: ${order['order_total']}")
<?php
function getUserInfo($accessToken) {
    $ch = curl_init('https://app.sellerlegend.com/api/user/me');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $accessToken,
        'Content-Type: application/json'
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    return json_decode($response, true);
}

// Get orders with account selection
function getOrders($accessToken, $accountTitle) {
    $params = http_build_query([
        'account_title' => $accountTitle,
        'per_page' => 500
    ]);

    $ch = curl_init('https://app.sellerlegend.com/api/sales/orders?' . $params);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $accessToken,
        'Content-Type: application/json'
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    return json_decode($response, true);
}
async function getUserInfo(accessToken) {
    const response = await fetch('https://app.sellerlegend.com/api/user/me', {
        headers: {
            'Authorization': `Bearer ${accessToken}`,
            'Content-Type': 'application/json'
        }
    });

    return await response.json();
}

// Get orders with account selection
async function getOrders(accessToken, accountTitle) {
    const params = new URLSearchParams({
        account_title: accountTitle,
        per_page: 500
    });

    const response = await fetch(`https://app.sellerlegend.com/api/sales/orders?${params}`, {
        headers: {
            'Authorization': `Bearer ${accessToken}`,
            'Content-Type': 'application/json'
        }
    });

    return await response.json();
}
# Get user information
curl -X GET https://app.sellerlegend.com/api/user/me \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

# Get orders with account selection
curl -X GET "https://app.sellerlegend.com/api/sales/orders?account_title=My%20Store%20US&per_page=500" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Step 5: Refresh Tokens When They Expire

CRITICAL: When you refresh a token, you receive a NEW refresh token. The old refresh token becomes invalid immediately. You MUST update your stored refresh token every time you refresh OR request a new access token.

Before the access token expires (15 days), use the refresh token to obtain a new access token:

Code Examples for Token Refresh:
from sellerlegend_api import SellerLegendClient
from datetime import datetime, timedelta
import sqlite3

class SellerLegendTokenManager:
    def __init__(self, client_id, client_secret):
        self.client_id = client_id
        self.client_secret = client_secret
        self.db_path = 'tokens.db'

    def refresh_and_get_client(self, refresh_token):
        """
        Refresh tokens and return authenticated client.

        ⚠️ CRITICAL: When refreshing, you get a NEW refresh token!
        The old refresh token becomes INVALID immediately!
        """
        # Initialize client for token refresh
        client = SellerLegendClient(
            client_id=self.client_id,
            client_secret=self.client_secret,
            refresh_token=refresh_token
        )

        try:
            # Refresh tokens using SDK
            new_tokens = client.refresh_token()

            # CRITICAL: Update BOTH tokens in database
            self.update_tokens_in_database(
                access_token=new_tokens['access_token'],
                refresh_token=new_tokens['refresh_token'],  # NEW refresh token!
                expires_in=new_tokens['expires_in']
            )

            # Return client with new access token
            return SellerLegendClient(
                access_token=new_tokens['access_token']
            )
        except Exception as e:
            raise Exception(f"Token refresh failed: {e}")

    def update_tokens_in_database(self, access_token, refresh_token, expires_in):
        """Update tokens in database - MUST update both!"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()

        expires_at = datetime.utcnow() + timedelta(seconds=expires_in)

        cursor.execute("""
            UPDATE user_tokens SET
                access_token = ?,
                refresh_token = ?,  # CRITICAL: Save new refresh token
                expires_at = ?,
                updated_at = CURRENT_TIMESTAMP
            WHERE user_id = ?
        """, (access_token, refresh_token, expires_at, current_user_id))

        conn.commit()
        conn.close()

    def get_valid_client(self, user_id):
        """Get an authenticated client, refreshing if necessary."""
        conn = sqlite3.connect(self.db_path)
        conn.row_factory = sqlite3.Row
        cursor = conn.cursor()

        cursor.execute("""
            SELECT * FROM user_tokens WHERE user_id = ?
        """, (user_id,))

        tokens = cursor.fetchone()
        conn.close()

        # Check if token is about to expire (refresh if less than 1 day left)
        expires_at = datetime.fromisoformat(tokens['expires_at'])
        if expires_at < datetime.utcnow() + timedelta(days=1):
            print("Token expiring soon, refreshing...")
            return self.refresh_and_get_client(tokens['refresh_token'])

        # Return client with valid token
        return SellerLegendClient(
            access_token=tokens['access_token']
        )
<?php
class TokenManager {
    private $clientId;
    private $clientSecret;
    private $tokenUrl = 'https://app.sellerlegend.com/api/oauth/token';
    private $pdo;

    public function __construct($clientId, $clientSecret, $pdo) {
        $this->clientId = $clientId;
        $this->clientSecret = $clientSecret;
        $this->pdo = $pdo;
    }

    public function refreshToken($refreshToken) {
        // WARNING: This returns a NEW refresh token. The old one becomes invalid!

        $data = [
            'grant_type' => 'refresh_token',
            'refresh_token' => $refreshToken,
            'client_id' => $this->clientId,
            'client_secret' => $this->clientSecret
        ];

        $ch = curl_init($this->tokenUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode === 200) {
            $tokens = json_decode($response, true);

            // CRITICAL: Update BOTH tokens in database
            $this->updateTokensInDatabase(
                $tokens['access_token'],
                $tokens['refresh_token'],  // NEW refresh token!
                $tokens['expires_in']
            );

            return $tokens;
        } else {
            throw new Exception("Token refresh failed: " . $response);
        }
    }

    private function updateTokensInDatabase($accessToken, $refreshToken, $expiresIn) {
        // Update tokens in database - MUST update both!
        $stmt = $this->pdo->prepare("
            UPDATE user_tokens
            SET access_token = :access_token,
                refresh_token = :refresh_token,
                expires_at = :expires_at
            WHERE user_id = :user_id
        ");

        $stmt->execute([
            ':user_id' => $_SESSION['user_id'],
            ':access_token' => $accessToken,
            ':refresh_token' => $refreshToken,  // CRITICAL: Save new refresh token
            ':expires_at' => date('Y-m-d H:i:s', time() + $expiresIn)
        ]);
    }

    public function getValidToken($userId) {
        // Get a valid access token, refreshing if necessary
        $stmt = $this->pdo->prepare("
            SELECT * FROM user_tokens WHERE user_id = :user_id
        ");
        $stmt->execute([':user_id' => $userId]);
        $userToken = $stmt->fetch(PDO::FETCH_ASSOC);

        // Check if token is about to expire (refresh if less than 1 day left)
        $expiresAt = strtotime($userToken['expires_at']);
        if ($expiresAt < time() + 86400) {
            $tokens = $this->refreshToken($userToken['refresh_token']);
            return $tokens['access_token'];
        }

        return $userToken['access_token'];
    }
}
class TokenManager {
    constructor(clientId, clientSecret) {
        this.clientId = clientId;
        this.clientSecret = clientSecret;
        this.tokenUrl = 'https://app.sellerlegend.com/api/oauth/token';
    }

    async refreshToken(refreshToken) {
        // WARNING: This returns a NEW refresh token. The old one becomes invalid!

        const data = new URLSearchParams({
            grant_type: 'refresh_token',
            refresh_token: refreshToken,
            client_id: this.clientId,
            client_secret: this.clientSecret
        });

        try {
            const response = await fetch(this.tokenUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: data
            });

            if (response.ok) {
                const tokens = await response.json();

                // CRITICAL: Update BOTH tokens in backend
                await this.updateTokensInBackend({
                    access_token: tokens.access_token,
                    refresh_token: tokens.refresh_token,  // NEW refresh token!
                    expires_in: tokens.expires_in
                });

                return tokens;
            } else {
                throw new Error(`Token refresh failed: ${await response.text()}`);
            }
        } catch (error) {
            console.error('Token refresh error:', error);
            throw error;
        }
    }

    async updateTokensInBackend(tokens) {
        // Update tokens in backend - MUST update both!
        await fetch('/api/update-tokens', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                access_token: tokens.access_token,
                refresh_token: tokens.refresh_token,  // CRITICAL: Save new refresh token
                expires_in: tokens.expires_in
            })
        });
    }

    async getValidToken() {
        // Get current tokens from backend
        const response = await fetch('/api/get-tokens');
        const userToken = await response.json();

        // Check if token is about to expire (refresh if less than 1 day left)
        const expiresAt = new Date(userToken.expires_at);
        const oneDayFromNow = new Date(Date.now() + 86400000);

        if (expiresAt < oneDayFromNow) {
            const tokens = await this.refreshToken(userToken.refresh_token);
            return tokens.access_token;
        }

        return userToken.access_token;
    }
}
# Refresh the access token
curl -X POST https://app.sellerlegend.com/api/oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=refresh_token" \
  -d "refresh_token=YOUR_REFRESH_TOKEN" \
  -d "client_id=your-client-id" \
  -d "client_secret=your-client-secret"

# Response includes NEW tokens:
# {
#   "token_type": "Bearer",
#   "expires_in": 1296000,
#   "access_token": "eyJ0eXAiOiJKV1...",  # New access token
#   "refresh_token": "def50200..."        # NEW refresh token - save this!
# }

# CRITICAL: Update your stored refresh token with the new one!

Database Schema Example

Here's a recommended database schema for storing OAuth tokens:

CREATE TABLE user_tokens (
    id INT PRIMARY KEY AUTO_INCREMENT,
    user_id INT NOT NULL UNIQUE,
    access_token TEXT NOT NULL,
    refresh_token TEXT NOT NULL,
    expires_at DATETIME NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_user_id (user_id),
    INDEX idx_expires_at (expires_at)
);

Account Selection

Most endpoints require account selection. You can select an account using one of these methods as query parameters:

By Account Title
?account_title=My Store US
Example:
/api/sales/orders?account_title=My Store US&per_page=500
By Seller + Marketplace
?seller_id=A1234567890&marketplace_id=ATVPDKIKX0DER
Example:
/api/sales/orders?seller_id=A1234567890&marketplace_id=ATVPDKIKX0DER&per_page=500
By Group
?group_title=North America
Example:
/api/sales/orders?group_title=North America&per_page=500

API Endpoints

User

GET /user/me Get current user information
Code Examples:
from sellerlegend_api import SellerLegendClient

client = SellerLegendClient(
    access_token="YOUR_ACCESS_TOKEN"
)

# Get current user information
user_info = client.user.get_me()
print(f"User: {user_info['user']['name']}")
print(f"Email: {user_info['user']['email']}")
<?php
use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'https://app.sellerlegend.com/api/',
    'headers' => [
        'Authorization' => 'Bearer YOUR_ACCESS_TOKEN'
    ]
]);

$response = $client->request('GET', 'user/me');
$userData = json_decode($response->getBody(), true);

echo "User: " . $userData['user']['name'] . "\n";
echo "Email: " . $userData['user']['email'] . "\n";
const getUser = async () => {
    const response = await fetch('https://app.sellerlegend.com/api/user/me', {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
            'Content-Type': 'application/json'
        }
    });

    const userData = await response.json();
    console.log('User:', userData.user.name);
    console.log('Email:', userData.user.email);
    return userData;
};

getUser();
curl -X GET "https://app.sellerlegend.com/api/user/me" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
Response Example:
{
  "status": "Success",
  "code": 200,
  "message": "User",
  "user": {
    "id": 123,
    "name": "John Doe",
    "email": "john@example.com",
    "status": "active",
    "active": true
  }
}
GET /user/accounts List user's Amazon accounts
Code Examples:
from sellerlegend_api import SellerLegendClient

client = SellerLegendClient(
    access_token="YOUR_ACCESS_TOKEN"
)

# Get all user accounts
accounts = client.user.get_accounts()

# Process accounts
for account in accounts['accounts']:
    print(f"Account: {account['account_title']}")
    print(f"  - Seller ID: {account['seller_id']}")
    print(f"  - Marketplace: {account['marketplace']}")
    print(f"  - Country: {account['country_code']}")

# Store the first account for future API calls
if accounts['accounts']:
    first_account = accounts['accounts'][0]
    account_title = first_account['account_title']
<?php
use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'https://app.sellerlegend.com/api/',
    'headers' => [
        'Authorization' => 'Bearer YOUR_ACCESS_TOKEN'
    ]
]);

$response = $client->request('GET', 'user/accounts');
$accountsData = json_decode($response->getBody(), true);

// Process all accounts
foreach ($accountsData['accounts'] as $account) {
    echo "Account: " . $account['account_title'] . "\n";
    echo "  - Seller ID: " . $account['seller_id'] . "\n";
    echo "  - Marketplace: " . $account['marketplace'] . "\n";
    echo "  - Country: " . $account['country_code'] . "\n";
}

// Store first account for future use
if (!empty($accountsData['accounts'])) {
    $firstAccount = $accountsData['accounts'][0];
    $accountTitle = $firstAccount['account_title'];
}
const getAccounts = async () => {
    const response = await fetch('https://app.sellerlegend.com/api/user/accounts', {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
            'Content-Type': 'application/json'
        }
    });

    const data = await response.json();

    // Process all accounts
    data.accounts.forEach(account => {
        console.log(`Account: ${account.account_title}`);
        console.log(`  - Seller ID: ${account.seller_id}`);
        console.log(`  - Marketplace: ${account.marketplace}`);
        console.log(`  - Country: ${account.country_code}`);
    });

    // Store first account for future API calls
    if (data.accounts.length > 0) {
        const firstAccount = data.accounts[0];
        localStorage.setItem('account_title', firstAccount.account_title);
    }

    return data;
};

getAccounts();
curl -X GET "https://app.sellerlegend.com/api/user/accounts" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
Response Example:
{
  "accounts": [
    {
      "id": 456,
      "account_title": "My Store US",
      "country_code": "US",
      "currency_code": "USD",
      "timezone": "America/New_York",
      "marketplace": "ATVPDKIKX0DER",
      "seller_id": "A1234567890"
    },
    {
      "id": 457,
      "account_title": "My Store UK",
      "country_code": "GB",
      "currency_code": "GBP",
      "timezone": "Europe/London",
      "marketplace": "A1F83G8C2ARO7P",
      "seller_id": "A0987654321"
    }
  ]
}

Sales

GET /sales/orders Get sales orders
Parameters:
Name Type Required Description
per_page integer Yes Results per page (250, 500, 1000, 2000)
start_date date No Start date (Y-m-d format)
end_date date No End date (max 1 month range)
sales_channel string No amazon or non-amazon
Code Examples:
from sellerlegend_api import SellerLegendClient

client = SellerLegendClient(
    access_token="YOUR_ACCESS_TOKEN"
)

# Get sales orders with account selection
orders = client.sales.get_orders(
    account_title="My Store US",  # Account selection as parameter
    per_page=250,
    start_date="2024-01-01",
    end_date="2024-01-31",
    sales_channel="amazon"  # Optional: filter by channel
)

# Process paginated results
for order in orders['data']:
    print(f"Order ID: {order['amazon_order_id']}")
    print(f"Date: {order['purchase_date']}")
    print(f"Total: {order['order_total']} {order['currency_code']}")
    print(f"Items: {order['quantity_ordered']}")

print(f"Total orders: {orders['total']}")
print(f"Current page: {orders['current_page']} of {orders['last_page']}")
<?php
use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'https://app.sellerlegend.com/api/',
    'headers' => [
        'Authorization' => 'Bearer YOUR_ACCESS_TOKEN'
    ]
]);

$response = $client->request('GET', 'sales/orders', [
    'query' => [
        'account_title' => 'My Store US',  // Account selection as parameter
        'per_page' => 250,
        'start_date' => '2024-01-01',
        'end_date' => '2024-01-31',
        'sales_channel' => 'amazon'  // Optional
    ]
]);

$ordersData = json_decode($response->getBody(), true);

// Process orders
foreach ($ordersData['data'] as $order) {
    echo "Order ID: " . $order['amazon_order_id'] . "\n";
    echo "Date: " . $order['purchase_date'] . "\n";
    echo "Total: " . $order['order_total'] . " " . $order['currency_code'] . "\n";
    echo "Items: " . $order['quantity_ordered'] . "\n\n";
}

echo "Total orders: " . $ordersData['total'] . "\n";
echo "Page " . $ordersData['current_page'] . " of " . $ordersData['last_page'];
const getOrders = async () => {
    const params = new URLSearchParams({
        account_title: 'My Store US',  // Account selection as parameter
        per_page: 250,
        start_date: '2024-01-01',
        end_date: '2024-01-31',
        sales_channel: 'amazon'  // Optional
    });

    const response = await fetch(`https://app.sellerlegend.com/api/sales/orders?${params}`, {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
            'Content-Type': 'application/json'
        }
    });

    const ordersData = await response.json();

    // Process orders
    ordersData.data.forEach(order => {
        console.log(`Order ID: ${order.amazon_order_id}`);
        console.log(`Date: ${order.purchase_date}`);
        console.log(`Total: ${order.order_total} ${order.currency_code}`);
        console.log(`Items: ${order.quantity_ordered}`);
    });

    console.log(`Total orders: ${ordersData.total}`);
    console.log(`Page ${ordersData.current_page} of ${ordersData.last_page}`);

    return ordersData;
};

getOrders();
curl -X GET "https://app.sellerlegend.com/api/sales/orders?account_title=My%20Store%20US&per_page=250&start_date=2024-01-01&end_date=2024-01-31&sales_channel=amazon" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
Response Example:
{
  "current_page": 1,
  "data": [
    {
      "amazon_order_id": "123-4567890-1234567",
      "purchase_date": "2024-01-15 10:30:00",
      "order_status": "Shipped",
      "order_total": 99.99,
      "currency_code": "USD",
      "quantity_ordered": 2,
      "sku": "PROD-SKU-001",
      "asin": "B08ABC1234",
      "product_name": "Example Product"
    }
  ],
  "total": 1250,
  "per_page": 250,
  "last_page": 5
}
GET /sales/statistics-dashboard Get aggregated sales statistics
Parameters:
Name Type Required Description
view_by string Yes product or date
group_by string Yes Grouping criteria
per_page integer Yes 500, 1000, or 2000
currency string No Currency code
Code Examples:
from sellerlegend_api import SellerLegendClient

client = SellerLegendClient(
    access_token="YOUR_ACCESS_TOKEN"
)

# Get sales statistics by product
stats = client.sales.get_statistics_dashboard(
    account_title="My Store US",
    view_by="product",
    group_by="sku",  # Group by SKU, ASIN, or parent ASIN
    per_page=500,
    start_date="2024-01-01",
    end_date="2024-01-31",
    currency="USD"
)

# Process statistics
for item in stats['data']:
    print(f"SKU: {item['sku']}")
    print(f"Product: {item['product_name']}")
    print(f"Units Sold: {item['units_ordered']}")
    print(f"Revenue: ${item['product_sales']}")
    print(f"Profit: ${item['profit']}")
    print(f"ROI: {item['roi']}%")
    print("---")

# View by date example
date_stats = client.sales.get_statistics_dashboard(
    account_title="My Store US",
    view_by="date",
    group_by="day",  # day, week, month, year
    per_page=500
)
<?php
use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'https://app.sellerlegend.com/api/',
    'headers' => [
        'Authorization' => 'Bearer YOUR_ACCESS_TOKEN'
    ]
]);

$response = $client->request('GET', 'sales/statistics-dashboard', [
    'query' => [
        'account_title' => 'My Store US',
        'view_by' => 'product',
        'group_by' => 'sku',  // Group by SKU, ASIN, or parent ASIN
        'per_page' => 500,
        'start_date' => '2024-01-01',
        'end_date' => '2024-01-31',
        'currency' => 'USD'
    ]
]);

$statsData = json_decode($response->getBody(), true);

// Process statistics
foreach ($statsData['data'] as $item) {
    echo "SKU: " . $item['sku'] . "\n";
    echo "Product: " . $item['product_name'] . "\n";
    echo "Units Sold: " . $item['units_ordered'] . "\n";
    echo "Revenue: $" . $item['product_sales'] . "\n";
    echo "Profit: $" . $item['profit'] . "\n";
    echo "ROI: " . $item['roi'] . "%\n";
    echo "---\n";
}
const getSalesStatistics = async () => {
    const params = new URLSearchParams({
        account_title: 'My Store US',
        view_by: 'product',
        group_by: 'sku',  // Group by SKU, ASIN, or parent ASIN
        per_page: 500,
        start_date: '2024-01-01',
        end_date: '2024-01-31',
        currency: 'USD'
    });

    const response = await fetch(`https://app.sellerlegend.com/api/sales/statistics-dashboard?${params}`, {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
            'Content-Type': 'application/json'
        }
    });

    const statsData = await response.json();

    // Process statistics
    statsData.data.forEach(item => {
        console.log(`SKU: ${item.sku}`);
        console.log(`Product: ${item.product_name}`);
        console.log(`Units Sold: ${item.units_ordered}`);
        console.log(`Revenue: $${item.product_sales}`);
        console.log(`Profit: $${item.profit}`);
        console.log(`ROI: ${item.roi}%`);
        console.log('---');
    });

    return statsData;
};

getSalesStatistics();
curl -X GET "https://app.sellerlegend.com/api/sales/statistics-dashboard?account_title=My%20Store%20US&view_by=product&group_by=sku&per_page=500&start_date=2024-01-01&end_date=2024-01-31¤cy=USD" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
Response Example:
{
  "current_page": 1,
  "data": [
    {
      "sku": "PROD-SKU-001",
      "asin": "B08ABC1234",
      "product_name": "Example Product",
      "units_ordered": 150,
      "product_sales": 4499.50,
      "product_cost": 1500.00,
      "amazon_fees": 674.93,
      "profit": 2324.57,
      "roi": 154.97,
      "profit_margin": 51.65
    }
  ],
  "total": 85,
  "per_page": 500,
  "last_page": 1
}
GET /sales/per-day-per-product Get daily product sales data
Parameters:
Name Type Required Description
per_page integer Yes 500, 1000, or 2000
start_date date No Start date (Y-m-d)
end_date date No End date (Y-m-d)
sales_channel string No amazon or non-amazon
currency string No Currency code (e.g., USD)
Code Examples:
from sellerlegend_api import SellerLegendClient

client = SellerLegendClient(
    access_token="YOUR_ACCESS_TOKEN"
)

# Get daily sales data per product
daily_sales = client.sales.get_per_day_per_product(
    account_title="My Store US",
    per_page=500,
    start_date="2024-01-01",
    end_date="2024-01-31",
    sales_channel="amazon",
    currency="USD"
)

# Process daily sales data
for item in daily_sales['data']:
    print(f"Date: {item['date']}")
    print(f"SKU: {item['sku']}")
    print(f"Product: {item['product_name']}")
    print(f"Units Sold: {item['units_ordered']}")
    print(f"Revenue: ${item['product_sales']}")
    print("---")
<?php
use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'https://app.sellerlegend.com/api/',
    'headers' => [
        'Authorization' => 'Bearer YOUR_ACCESS_TOKEN'
    ]
]);

$response = $client->request('GET', 'sales/per-day-per-product', [
    'query' => [
        'account_title' => 'My Store US',
        'per_page' => 500,
        'start_date' => '2024-01-01',
        'end_date' => '2024-01-31',
        'sales_channel' => 'amazon',
        'currency' => 'USD'
    ]
]);

$dailySales = json_decode($response->getBody(), true);

// Process daily sales data
foreach ($dailySales['data'] as $item) {
    echo "Date: {$item['date']}\n";
    echo "SKU: {$item['sku']}\n";
    echo "Product: {$item['product_name']}\n";
    echo "Units Sold: {$item['units_ordered']}\n";
    echo "Revenue: \${$item['product_sales']}\n";
    echo "---\n";
}
const getDailySales = async () => {
    const params = new URLSearchParams({
        account_title: 'My Store US',
        per_page: 500,
        start_date: '2024-01-01',
        end_date: '2024-01-31',
        sales_channel: 'amazon',
        currency: 'USD'
    });

    const response = await fetch(`https://app.sellerlegend.com/api/sales/per-day-per-product?${params}`, {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
            'Content-Type': 'application/json'
        }
    });

    const dailySales = await response.json();

    // Process daily sales data
    dailySales.data.forEach(item => {
        console.log(`Date: ${item.date}`);
        console.log(`SKU: ${item.sku}`);
        console.log(`Product: ${item.product_name}`);
        console.log(`Units Sold: ${item.units_ordered}`);
        console.log(`Revenue: $${item.product_sales}`);
        console.log('---');
    });

    return dailySales;
};

getDailySales();
curl -X GET "https://app.sellerlegend.com/api/sales/per-day-per-product?account_title=My%20Store%20US&per_page=500&start_date=2024-01-01&end_date=2024-01-31&sales_channel=amazon¤cy=USD" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
Response Example:
{
  "current_page": 1,
  "data": [
    {
      "date": "2024-01-15",
      "sku": "PROD-SKU-001",
      "product_name": "Example Product",
      "asin": "B0123456789",
      "units_ordered": 25,
      "product_sales": 499.75,
      "product_sales_tax": 39.98,
      "shipping_credits": 49.95,
      "promotional_rebates": 10.00
    }
  ],
  "total": 450,
  "per_page": 500
}
GET /sales/transactions Get financial transactions
Parameters:
Name Type Required Description
per_page integer Yes 500, 1000, or 2000
start_date date No Start date (Y-m-d)
end_date date No End date (Y-m-d)
Code Examples:
from sellerlegend_api import SellerLegendClient

client = SellerLegendClient(
    access_token="YOUR_ACCESS_TOKEN"
)

# Get financial transactions
transactions = client.sales.get_transactions(
    account_title="My Store US",
    per_page=500,
    start_date="2024-01-01",
    end_date="2024-01-31"
)

# Process transactions
for transaction in transactions['data']:
    print(f"Date: {transaction['posted_date']}")
    print(f"Type: {transaction['transaction_type']}")
    print(f"Order ID: {transaction['amazon_order_id']}")
    print(f"SKU: {transaction['sku']}")
    print(f"Amount: ${transaction['amount']}")
    print(f"Currency: {transaction['currency']}")
    print("---")
<?php
use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'https://app.sellerlegend.com/api/',
    'headers' => [
        'Authorization' => 'Bearer YOUR_ACCESS_TOKEN'
    ]
]);

$response = $client->request('GET', 'sales/transactions', [
    'query' => [
        'account_title' => 'My Store US',
        'per_page' => 500,
        'start_date' => '2024-01-01',
        'end_date' => '2024-01-31'
    ]
]);

$transactions = json_decode($response->getBody(), true);

// Process transactions
foreach ($transactions['data'] as $transaction) {
    echo "Date: {$transaction['posted_date']}\n";
    echo "Type: {$transaction['transaction_type']}\n";
    echo "Order ID: {$transaction['amazon_order_id']}\n";
    echo "SKU: {$transaction['sku']}\n";
    echo "Amount: \${$transaction['amount']}\n";
    echo "Currency: {$transaction['currency']}\n";
    echo "---\n";
}
const getTransactions = async () => {
    const params = new URLSearchParams({
        account_title: 'My Store US',
        per_page: 500,
        start_date: '2024-01-01',
        end_date: '2024-01-31'
    });

    const response = await fetch(`https://app.sellerlegend.com/api/sales/transactions?${params}`, {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
            'Content-Type': 'application/json'
        }
    });

    const transactions = await response.json();

    // Process transactions
    transactions.data.forEach(transaction => {
        console.log(`Date: ${transaction.posted_date}`);
        console.log(`Type: ${transaction.transaction_type}`);
        console.log(`Order ID: ${transaction.amazon_order_id}`);
        console.log(`SKU: ${transaction.sku}`);
        console.log(`Amount: $${transaction.amount}`);
        console.log(`Currency: ${transaction.currency}`);
        console.log('---');
    });

    return transactions;
};

getTransactions();
curl -X GET "https://app.sellerlegend.com/api/sales/transactions?account_title=My%20Store%20US&per_page=500&start_date=2024-01-01&end_date=2024-01-31" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
Response Example:
{
  "current_page": 1,
  "data": [
    {
      "posted_date": "2024-01-15T10:30:00Z",
      "transaction_type": "Order",
      "amazon_order_id": "111-1234567-8901234",
      "sku": "PROD-SKU-001",
      "description": "Product Sale",
      "quantity": 2,
      "amount": 49.98,
      "currency": "USD",
      "marketplace_name": "Amazon.com"
    }
  ],
  "total": 1250,
  "per_page": 500
}

Inventory

GET /inventory/list Get inventory data
Parameters:
Name Type Required Description
per_page integer Yes 20, 50, 100, 250, 500, 1000, 2000
velocity_start_date date No Start date for velocity calculation
velocity_end_date date No End date for velocity calculation
Code Examples:
from sellerlegend_api import SellerLegendClient

client = SellerLegendClient(
    access_token="YOUR_ACCESS_TOKEN"
)

# Get inventory data with velocity calculation
inventory = client.inventory.list(
    account_title="My Store US",
    per_page=500,
    velocity_start_date="2024-01-01",
    velocity_end_date="2024-01-31"
)

# Process inventory data
for item in inventory['data']:
    print(f"SKU: {item['sku']}")
    print(f"Product: {item['product_name']}")
    print(f"ASIN: {item['asin']}")
    print(f"FBA Available: {item['afn_fulfillable_quantity']}")
    print(f"FBA Reserved: {item['afn_reserved_quantity']}")
    print(f"FBA Inbound: {item['afn_inbound_quantity']}")
    print(f"Velocity (30d): {item['velocity_30_days']} units/day")
    print(f"Days of Stock: {item['days_of_stock']}")
    print("---")
<?php
use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'https://app.sellerlegend.com/api/',
    'headers' => [
        'Authorization' => 'Bearer YOUR_ACCESS_TOKEN'
    ]
]);

$response = $client->request('GET', 'inventory/list', [
    'query' => [
        'account_title' => 'My Store US',
        'per_page' => 500,
        'velocity_start_date' => '2024-01-01',
        'velocity_end_date' => '2024-01-31'
    ]
]);

$inventory = json_decode($response->getBody(), true);

// Process inventory data
foreach ($inventory['data'] as $item) {
    echo "SKU: {$item['sku']}\n";
    echo "Product: {$item['product_name']}\n";
    echo "ASIN: {$item['asin']}\n";
    echo "FBA Available: {$item['afn_fulfillable_quantity']}\n";
    echo "FBA Reserved: {$item['afn_reserved_quantity']}\n";
    echo "FBA Inbound: {$item['afn_inbound_quantity']}\n";
    echo "Velocity (30d): {$item['velocity_30_days']} units/day\n";
    echo "Days of Stock: {$item['days_of_stock']}\n";
    echo "---\n";
}
const getInventory = async () => {
    const params = new URLSearchParams({
        account_title: 'My Store US',
        per_page: 500,
        velocity_start_date: '2024-01-01',
        velocity_end_date: '2024-01-31'
    });

    const response = await fetch(`https://app.sellerlegend.com/api/inventory/list?${params}`, {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
            'Content-Type': 'application/json'
        }
    });

    const inventory = await response.json();

    // Process inventory data
    inventory.data.forEach(item => {
        console.log(`SKU: ${item.sku}`);
        console.log(`Product: ${item.product_name}`);
        console.log(`ASIN: ${item.asin}`);
        console.log(`FBA Available: ${item.afn_fulfillable_quantity}`);
        console.log(`FBA Reserved: ${item.afn_reserved_quantity}`);
        console.log(`FBA Inbound: ${item.afn_inbound_quantity}`);
        console.log(`Velocity (30d): ${item.velocity_30_days} units/day`);
        console.log(`Days of Stock: ${item.days_of_stock}`);
        console.log('---');
    });

    return inventory;
};

getInventory();
curl -X GET "https://app.sellerlegend.com/api/inventory/list?account_title=My%20Store%20US&per_page=500&velocity_start_date=2024-01-01&velocity_end_date=2024-01-31" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
Response Example:
{
  "current_page": 1,
  "data": [
    {
      "sku": "PROD-SKU-001",
      "product_name": "Example Product",
      "asin": "B0123456789",
      "fnsku": "X001ABC123",
      "afn_fulfillable_quantity": 150,
      "afn_reserved_quantity": 5,
      "afn_inbound_quantity": 200,
      "afn_total_quantity": 355,
      "velocity_30_days": 3.5,
      "days_of_stock": 42,
      "restock_date": "2024-02-15",
      "restock_quantity_suggested": 100
    }
  ],
  "total": 85,
  "per_page": 500
}

Costs (COGS)

GET /cogs/cost-periods Get product cost periods
Parameters (use one):
  • sku - Product SKU
  • asin - Product ASIN
  • parent_asin - Parent ASIN
Code Examples:
from sellerlegend_api import SellerLegendClient

client = SellerLegendClient(
    access_token="YOUR_ACCESS_TOKEN"
)

# Get cost periods for a SKU
cost_periods = client.cogs.get_cost_periods(
    account_title="My Store US",
    sku="PROD-SKU-001"
)

# Process cost periods
for period in cost_periods['data']:
    print(f"Period: {period['from_date']} to {period['to_date']}")
    for element in period['cost_elements']:
        print(f"  {element['cost_element']}: ${element['amount']} {element['currency']}")
        print(f"  Provider: {element['provider']}")
        print(f"  Notes: {element['notes']}")
<?php
use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'https://app.sellerlegend.com/api/',
    'headers' => [
        'Authorization' => 'Bearer YOUR_ACCESS_TOKEN'
    ]
]);

$response = $client->request('GET', 'cogs/cost-periods', [
    'query' => [
        'account_title' => 'My Store US',
        'sku' => 'PROD-SKU-001'
    ]
]);

$costPeriods = json_decode($response->getBody(), true);

// Process cost periods
foreach ($costPeriods['data'] as $period) {
    echo "Period: {$period['from_date']} to {$period['to_date']}\n";
    foreach ($period['cost_elements'] as $element) {
        echo "  {$element['cost_element']}: \${$element['amount']} {$element['currency']}\n";
        echo "  Provider: {$element['provider']}\n";
        echo "  Notes: {$element['notes']}\n";
    }
}
const getCostPeriods = async () => {
    const params = new URLSearchParams({
        account_title: 'My Store US',
        sku: 'PROD-SKU-001'
    });

    const response = await fetch(`https://app.sellerlegend.com/api/cogs/cost-periods?${params}`, {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
            'Content-Type': 'application/json'
        }
    });

    const costPeriods = await response.json();

    // Process cost periods
    costPeriods.data.forEach(period => {
        console.log(`Period: ${period.from_date} to ${period.to_date}`);
        period.cost_elements.forEach(element => {
            console.log(`  ${element.cost_element}: $${element.amount} ${element.currency}`);
            console.log(`  Provider: ${element.provider}`);
            console.log(`  Notes: ${element.notes}`);
        });
    });

    return costPeriods;
};

getCostPeriods();
curl -X GET "https://app.sellerlegend.com/api/cogs/cost-periods?account_title=My%20Store%20US&sku=PROD-SKU-001" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
POST /cogs/cost-periods Update product costs
Request Body Example:
{
  "sku": "PRODUCT-SKU",
  "data": [
    {
      "dates": {
        "from_date": "2024-01-01",
        "to_date": "2024-12-31"
      },
      "cost_elements": [
        {
          "cost_element": "Product Cost",
          "provider": "Supplier Name",
          "notes": "2024 pricing",
          "total_amount": 25.00,
          "currency": "USD",
          "conversion_rate": "1.00",
          "units": 1,
          "amount": 25.00
        }
      ]
    }
  ]
}
Code Examples:
from sellerlegend_api import SellerLegendClient

client = SellerLegendClient(
    access_token="YOUR_ACCESS_TOKEN"
)

# Update product costs
response = client.cogs.update_cost_periods(
    account_title="My Store US",
    sku="PROD-SKU-001",
    data=[
        {
            "dates": {
                "from_date": "2024-01-01",
                "to_date": "2024-12-31"
            },
            "cost_elements": [
                {
                    "cost_element": "Product Cost",
                    "provider": "Supplier Name",
                    "notes": "2024 pricing",
                    "total_amount": 25.00,
                    "currency": "USD",
                    "conversion_rate": "1.00",
                    "units": 1,
                    "amount": 25.00
                },
                {
                    "cost_element": "Shipping Cost",
                    "provider": "DHL",
                    "notes": "Sea freight",
                    "total_amount": 3.50,
                    "currency": "USD",
                    "conversion_rate": "1.00",
                    "units": 1,
                    "amount": 3.50
                }
            ]
        }
    ]
)

print(f"Cost update status: {response['status']}")
<?php
use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'https://app.sellerlegend.com/api/',
    'headers' => [
        'Authorization' => 'Bearer YOUR_ACCESS_TOKEN',
        'Content-Type' => 'application/json'
    ]
]);

$costData = [
    'sku' => 'PROD-SKU-001',
    'data' => [
        [
            'dates' => [
                'from_date' => '2024-01-01',
                'to_date' => '2024-12-31'
            ],
            'cost_elements' => [
                [
                    'cost_element' => 'Product Cost',
                    'provider' => 'Supplier Name',
                    'notes' => '2024 pricing',
                    'total_amount' => 25.00,
                    'currency' => 'USD',
                    'conversion_rate' => '1.00',
                    'units' => 1,
                    'amount' => 25.00
                ],
                [
                    'cost_element' => 'Shipping Cost',
                    'provider' => 'DHL',
                    'notes' => 'Sea freight',
                    'total_amount' => 3.50,
                    'currency' => 'USD',
                    'conversion_rate' => '1.00',
                    'units' => 1,
                    'amount' => 3.50
                ]
            ]
        ]
    ]
];

$response = $client->request('POST', 'cogs/cost-periods', [
    'query' => ['account_title' => 'My Store US'],
    'json' => $costData
]);

$result = json_decode($response->getBody(), true);
echo "Cost update status: {$result['status']}\n";
const updateCostPeriods = async () => {
    const costData = {
        sku: 'PROD-SKU-001',
        data: [
            {
                dates: {
                    from_date: '2024-01-01',
                    to_date: '2024-12-31'
                },
                cost_elements: [
                    {
                        cost_element: 'Product Cost',
                        provider: 'Supplier Name',
                        notes: '2024 pricing',
                        total_amount: 25.00,
                        currency: 'USD',
                        conversion_rate: '1.00',
                        units: 1,
                        amount: 25.00
                    },
                    {
                        cost_element: 'Shipping Cost',
                        provider: 'DHL',
                        notes: 'Sea freight',
                        total_amount: 3.50,
                        currency: 'USD',
                        conversion_rate: '1.00',
                        units: 1,
                        amount: 3.50
                    }
                ]
            }
        ]
    };

    const params = new URLSearchParams({ account_title: 'My Store US' });

    const response = await fetch(`https://app.sellerlegend.com/api/cogs/cost-periods?${params}`, {
        method: 'POST',
        headers: {
            'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(costData)
    });

    const result = await response.json();
    console.log(`Cost update status: ${result.status}`);

    return result;
};

updateCostPeriods();
curl -X POST "https://app.sellerlegend.com/api/cogs/cost-periods?account_title=My%20Store%20US" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "sku": "PROD-SKU-001",
    "data": [
      {
        "dates": {
          "from_date": "2024-01-01",
          "to_date": "2024-12-31"
        },
        "cost_elements": [
          {
            "cost_element": "Product Cost",
            "provider": "Supplier Name",
            "notes": "2024 pricing",
            "total_amount": 25.00,
            "currency": "USD",
            "conversion_rate": "1.00",
            "units": 1,
            "amount": 25.00
          }
        ]
      }
    ]
  }'
DELETE /cogs/cost-periods Delete product costs

Reports

POST /reports/request Request report generation
Request Body (use one):
  • product_sku - Generate for specific SKU
  • dps_date - Generate for specific date
  • last_updated_date - Generate since last update
Response:
{
  "status": "Success",
  "message": "Request Submitted",
  "report_id": 12345
}
Code Examples:
from sellerlegend_api import SellerLegendClient

client = SellerLegendClient(
    access_token="YOUR_ACCESS_TOKEN"
)

# Request report for specific SKU
report = client.reports.request(
    account_title="My Store US",
    product_sku="PROD-SKU-001"
)

print(f"Report ID: {report['report_id']}")
print(f"Status: {report['status']}")

# Request report for specific date
date_report = client.reports.request(
    account_title="My Store US",
    dps_date="2024-01-15"
)
<?php
use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'https://app.sellerlegend.com/api/',
    'headers' => [
        'Authorization' => 'Bearer YOUR_ACCESS_TOKEN',
        'Content-Type' => 'application/json'
    ]
]);

// Request report for specific SKU
$response = $client->request('POST', 'reports/request', [
    'query' => ['account_title' => 'My Store US'],
    'json' => [
        'product_sku' => 'PROD-SKU-001'
    ]
]);

$report = json_decode($response->getBody(), true);
echo "Report ID: {$report['report_id']}\n";
echo "Status: {$report['status']}\n";
const requestReport = async () => {
    const params = new URLSearchParams({ account_title: 'My Store US' });

    const response = await fetch(`https://app.sellerlegend.com/api/reports/request?${params}`, {
        method: 'POST',
        headers: {
            'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            product_sku: 'PROD-SKU-001'
        })
    });

    const report = await response.json();
    console.log(`Report ID: ${report.report_id}`);
    console.log(`Status: ${report.status}`);

    return report;
};

requestReport();
curl -X POST "https://app.sellerlegend.com/api/reports/request?account_title=My%20Store%20US" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"product_sku": "PROD-SKU-001"}'
GET /reports/status Check report status
Parameters:
  • report_id - The report ID returned from /reports/request
Code Examples:
from sellerlegend_api import SellerLegendClient
import time

client = SellerLegendClient(
    access_token="YOUR_ACCESS_TOKEN"
)

# Check report status
status = client.reports.get_status(
    account_title="My Store US",
    report_id=12345
)

print(f"Report Status: {status['status']}")
print(f"Progress: {status.get('progress', 0)}%")

# Wait for completion
while status['status'] == 'processing':
    time.sleep(5)
    status = client.reports.get_status(
        account_title="My Store US",
        report_id=12345
    )
    print(f"Progress: {status.get('progress', 0)}%")

if status['status'] == 'completed':
    print("Report ready for download!")
<?php
use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'https://app.sellerlegend.com/api/',
    'headers' => [
        'Authorization' => 'Bearer YOUR_ACCESS_TOKEN'
    ]
]);

$response = $client->request('GET', 'reports/status', [
    'query' => [
        'account_title' => 'My Store US',
        'report_id' => 12345
    ]
]);

$status = json_decode($response->getBody(), true);
echo "Report Status: {$status['status']}\n";
echo "Progress: " . ($status['progress'] ?? 0) . "%\n";
const checkReportStatus = async (reportId) => {
    const params = new URLSearchParams({
        account_title: 'My Store US',
        report_id: reportId
    });

    const response = await fetch(`https://app.sellerlegend.com/api/reports/status?${params}`, {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
            'Content-Type': 'application/json'
        }
    });

    const status = await response.json();
    console.log(`Report Status: ${status.status}`);
    console.log(`Progress: ${status.progress || 0}%`);

    return status;
};

checkReportStatus(12345);
curl -X GET "https://app.sellerlegend.com/api/reports/status?account_title=My%20Store%20US&report_id=12345" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
Response Example:
{
  "status": "completed",
  "progress": 100,
  "message": "Report ready for download"
}
GET /reports/download Download completed report
Parameters:
  • report_id - The report ID
  • format - Output format (csv or json)
Code Examples:
from sellerlegend_api import SellerLegendClient

client = SellerLegendClient(
    access_token="YOUR_ACCESS_TOKEN"
)

# Download report as CSV
report_data = client.reports.download(
    account_title="My Store US",
    report_id=12345,
    format="csv"
)

# Save to file
with open('report.csv', 'w') as f:
    f.write(report_data)

# Or download as JSON
json_data = client.reports.download(
    account_title="My Store US",
    report_id=12345,
    format="json"
)

# Process JSON data
for row in json_data['data']:
    print(f"SKU: {row['sku']}, Sales: {row['sales']}")
<?php
use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'https://app.sellerlegend.com/api/',
    'headers' => [
        'Authorization' => 'Bearer YOUR_ACCESS_TOKEN'
    ]
]);

// Download report as CSV
$response = $client->request('GET', 'reports/download', [
    'query' => [
        'account_title' => 'My Store US',
        'report_id' => 12345,
        'format' => 'csv'
    ]
]);

$csvData = $response->getBody()->getContents();
file_put_contents('report.csv', $csvData);
echo "Report saved to report.csv\n";
const downloadReport = async () => {
    const params = new URLSearchParams({
        account_title: 'My Store US',
        report_id: 12345,
        format: 'csv'
    });

    const response = await fetch(`https://app.sellerlegend.com/api/reports/download?${params}`, {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
        }
    });

    // Handle CSV download
    const csvData = await response.text();

    // Create download link
    const blob = new Blob([csvData], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'report.csv';
    a.click();
};

downloadReport();
# Download as CSV
curl -X GET "https://app.sellerlegend.com/api/reports/download?account_title=My%20Store%20US&report_id=12345&format=csv" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -o report.csv

# Download as JSON
curl -X GET "https://app.sellerlegend.com/api/reports/download?account_title=My%20Store%20US&report_id=12345&format=json" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  | jq '.data'

Service Status

GET /service-status Check API service status
Code Examples:
from sellerlegend_api import SellerLegendClient

client = SellerLegendClient(
    access_token="YOUR_ACCESS_TOKEN"
)

# Check service status
status = client.service.get_status()

if status['status'] == 'Success':
    print(f"API Service is {status['message']}")
    print(f"Response code: {status['code']}")
else:
    print("Service may be experiencing issues")
<?php
use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'https://app.sellerlegend.com/api/',
    'headers' => [
        'Authorization' => 'Bearer YOUR_ACCESS_TOKEN'
    ]
]);

$response = $client->request('GET', 'service-status');
$status = json_decode($response->getBody(), true);

if ($status['status'] == 'Success') {
    echo "API Service is {$status['message']}\n";
    echo "Response code: {$status['code']}\n";
} else {
    echo "Service may be experiencing issues\n";
}
const checkServiceStatus = async () => {
    const response = await fetch('https://app.sellerlegend.com/api/service-status', {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
            'Content-Type': 'application/json'
        }
    });

    const status = await response.json();

    if (status.status === 'Success') {
        console.log(`API Service is ${status.message}`);
        console.log(`Response code: ${status.code}`);
    } else {
        console.log('Service may be experiencing issues');
    }

    return status;
};

checkServiceStatus();
curl -X GET "https://app.sellerlegend.com/api/service-status" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
Response Example:
{
  "status": "Success",
  "code": 200,
  "message": "Active"
}

Connections

GET /connections/list List Amazon SP-API and PPC connections

Returns a list of all configured Amazon SP-API and PPC connections for the selected account.

Code Examples:
from sellerlegend_api import SellerLegendClient

client = SellerLegendClient(
    access_token="YOUR_ACCESS_TOKEN"
)

# Get all connections for the account
connections = client.connections.list(
    account_title="My Store US"
)

# Process connections
for connection in connections['data']:
    print(f"Connection Type: {connection['type']}")
    print(f"Marketplace: {connection['marketplace']}")
    print(f"Status: {connection['status']}")
    print(f"Last Sync: {connection['last_sync']}")
    print("---")
<?php
use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'https://app.sellerlegend.com/api/',
    'headers' => [
        'Authorization' => 'Bearer YOUR_ACCESS_TOKEN'
    ]
]);

$response = $client->request('GET', 'connections/list', [
    'query' => [
        'account_title' => 'My Store US'
    ]
]);

$connections = json_decode($response->getBody(), true);

// Process connections
foreach ($connections['data'] as $connection) {
    echo "Connection Type: {$connection['type']}\n";
    echo "Marketplace: {$connection['marketplace']}\n";
    echo "Status: {$connection['status']}\n";
    echo "Last Sync: {$connection['last_sync']}\n";
    echo "---\n";
}
const getConnections = async () => {
    const params = new URLSearchParams({
        account_title: 'My Store US'
    });

    const response = await fetch(`https://app.sellerlegend.com/api/connections/list?${params}`, {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
            'Content-Type': 'application/json'
        }
    });

    const connections = await response.json();

    // Process connections
    connections.data.forEach(connection => {
        console.log(`Connection Type: ${connection.type}`);
        console.log(`Marketplace: ${connection.marketplace}`);
        console.log(`Status: ${connection.status}`);
        console.log(`Last Sync: ${connection.last_sync}`);
        console.log('---');
    });

    return connections;
};

getConnections();
curl -X GET "https://app.sellerlegend.com/api/connections/list?account_title=My%20Store%20US" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
Response Example:
{
  "data": [
    {
      "type": "SP-API",
      "marketplace": "Amazon.com",
      "seller_id": "A1XXXXXXXXXX",
      "status": "active",
      "last_sync": "2024-01-15T10:30:00Z"
    },
    {
      "type": "PPC",
      "marketplace": "Amazon.com",
      "profile_id": "1234567890",
      "status": "active",
      "last_sync": "2024-01-15T09:45:00Z"
    }
  ]
}

Warehouse

GET /warehouse/list List warehouse inventory
Parameters:
Name Type Required Description
per_page integer Yes 20, 50, 100, 250, 500, 1000, or 2000
Code Examples:
from sellerlegend_api import SellerLegendClient

client = SellerLegendClient(
    access_token="YOUR_ACCESS_TOKEN"
)

# Get warehouse inventory
warehouse_inventory = client.warehouse.list(
    account_title="My Store US",
    per_page=500
)

# Process warehouse inventory
for item in warehouse_inventory['data']:
    print(f"SKU: {item['sku']}")
    print(f"Warehouse: {item['warehouse_name']}")
    print(f"Quantity: {item['quantity']}")
    print(f"Location: {item['location']}")
    print(f"Status: {item['status']}")
    print("---")
<?php
use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'https://app.sellerlegend.com/api/',
    'headers' => [
        'Authorization' => 'Bearer YOUR_ACCESS_TOKEN'
    ]
]);

$response = $client->request('GET', 'warehouse/list', [
    'query' => [
        'account_title' => 'My Store US',
        'per_page' => 500
    ]
]);

$warehouseInventory = json_decode($response->getBody(), true);

// Process warehouse inventory
foreach ($warehouseInventory['data'] as $item) {
    echo "SKU: {$item['sku']}\n";
    echo "Warehouse: {$item['warehouse_name']}\n";
    echo "Quantity: {$item['quantity']}\n";
    echo "Location: {$item['location']}\n";
    echo "Status: {$item['status']}\n";
    echo "---\n";
}
const getWarehouseInventory = async () => {
    const params = new URLSearchParams({
        account_title: 'My Store US',
        per_page: 500
    });

    const response = await fetch(`https://app.sellerlegend.com/api/warehouse/list?${params}`, {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
            'Content-Type': 'application/json'
        }
    });

    const warehouseInventory = await response.json();

    // Process warehouse inventory
    warehouseInventory.data.forEach(item => {
        console.log(`SKU: ${item.sku}`);
        console.log(`Warehouse: ${item.warehouse_name}`);
        console.log(`Quantity: ${item.quantity}`);
        console.log(`Location: ${item.location}`);
        console.log(`Status: ${item.status}`);
        console.log('---');
    });

    return warehouseInventory;
};

getWarehouseInventory();
curl -X GET "https://app.sellerlegend.com/api/warehouse/list?account_title=My%20Store%20US&per_page=500" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
Response Example:
{
  "current_page": 1,
  "data": [
    {
      "sku": "PROD-SKU-001",
      "warehouse_name": "FBA US-EAST",
      "quantity": 500,
      "location": "A-12-B",
      "status": "available",
      "last_updated": "2024-01-15T10:30:00Z"
    }
  ],
  "total": 150,
  "per_page": 500
}
GET /warehouse/inbound-shipments Get inbound shipments
Parameters:
Name Type Required Description
per_page integer Yes 20, 50, 100, 250, 500, 1000, or 2000
Code Examples:
from sellerlegend_api import SellerLegendClient

client = SellerLegendClient(
    access_token="YOUR_ACCESS_TOKEN"
)

# Get inbound shipments
shipments = client.warehouse.get_inbound_shipments(
    account_title="My Store US",
    per_page=500
)

# Process inbound shipments
for shipment in shipments['data']:
    print(f"Shipment ID: {shipment['shipment_id']}")
    print(f"Status: {shipment['status']}")
    print(f"Destination: {shipment['destination_fulfillment_center']}")
    print(f"Items: {shipment['total_items']}")
    print(f"ETA: {shipment['estimated_arrival_date']}")
    print("---")
<?php
use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'https://app.sellerlegend.com/api/',
    'headers' => [
        'Authorization' => 'Bearer YOUR_ACCESS_TOKEN'
    ]
]);

$response = $client->request('GET', 'warehouse/inbound-shipments', [
    'query' => [
        'account_title' => 'My Store US',
        'per_page' => 500
    ]
]);

$shipments = json_decode($response->getBody(), true);

// Process inbound shipments
foreach ($shipments['data'] as $shipment) {
    echo "Shipment ID: {$shipment['shipment_id']}\n";
    echo "Status: {$shipment['status']}\n";
    echo "Destination: {$shipment['destination_fulfillment_center']}\n";
    echo "Items: {$shipment['total_items']}\n";
    echo "ETA: {$shipment['estimated_arrival_date']}\n";
    echo "---\n";
}
const getInboundShipments = async () => {
    const params = new URLSearchParams({
        account_title: 'My Store US',
        per_page: 500
    });

    const response = await fetch(`https://app.sellerlegend.com/api/warehouse/inbound-shipments?${params}`, {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
            'Content-Type': 'application/json'
        }
    });

    const shipments = await response.json();

    // Process inbound shipments
    shipments.data.forEach(shipment => {
        console.log(`Shipment ID: ${shipment.shipment_id}`);
        console.log(`Status: ${shipment.status}`);
        console.log(`Destination: ${shipment.destination_fulfillment_center}`);
        console.log(`Items: ${shipment.total_items}`);
        console.log(`ETA: ${shipment.estimated_arrival_date}`);
        console.log('---');
    });

    return shipments;
};

getInboundShipments();
curl -X GET "https://app.sellerlegend.com/api/warehouse/inbound-shipments?account_title=My%20Store%20US&per_page=500" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
Response Example:
{
  "current_page": 1,
  "data": [
    {
      "shipment_id": "FBA15XYZ123",
      "shipment_name": "January Restock",
      "status": "IN_TRANSIT",
      "destination_fulfillment_center": "PHX7",
      "total_items": 1500,
      "total_skus": 25,
      "estimated_arrival_date": "2024-01-20",
      "created_date": "2024-01-10T08:00:00Z"
    }
  ],
  "total": 12,
  "per_page": 500
}

Supply Chain

GET /supply-chain/restock-suggestions Get restock suggestions
Parameters:
Name Type Required Description
per_page integer Yes 500, 1000, or 2000
currency string No Currency code (e.g., USD)
Code Examples:
from sellerlegend_api import SellerLegendClient

client = SellerLegendClient(
    access_token="YOUR_ACCESS_TOKEN"
)

# Get restock suggestions
suggestions = client.supply_chain.get_restock_suggestions(
    account_title="My Store US",
    per_page=500,
    currency="USD"
)

# Process restock suggestions
for item in suggestions['data']:
    print(f"SKU: {item['sku']}")
    print(f"Product: {item['product_name']}")
    print(f"Current Stock: {item['current_stock']} units")
    print(f"Days of Stock: {item['days_of_stock']}")
    print(f"Restock Quantity: {item['suggested_quantity']} units")
    print(f"Restock By: {item['restock_by_date']}")
    print(f"Lead Time: {item['lead_time_days']} days")
    print("---")
<?php
use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'https://app.sellerlegend.com/api/',
    'headers' => [
        'Authorization' => 'Bearer YOUR_ACCESS_TOKEN'
    ]
]);

$response = $client->request('GET', 'supply-chain/restock-suggestions', [
    'query' => [
        'account_title' => 'My Store US',
        'per_page' => 500,
        'currency' => 'USD'
    ]
]);

$suggestions = json_decode($response->getBody(), true);

// Process restock suggestions
foreach ($suggestions['data'] as $item) {
    echo "SKU: {$item['sku']}\n";
    echo "Product: {$item['product_name']}\n";
    echo "Current Stock: {$item['current_stock']} units\n";
    echo "Days of Stock: {$item['days_of_stock']}\n";
    echo "Restock Quantity: {$item['suggested_quantity']} units\n";
    echo "Restock By: {$item['restock_by_date']}\n";
    echo "Lead Time: {$item['lead_time_days']} days\n";
    echo "---\n";
}
const getRestockSuggestions = async () => {
    const params = new URLSearchParams({
        account_title: 'My Store US',
        per_page: 500,
        currency: 'USD'
    });

    const response = await fetch(`https://app.sellerlegend.com/api/supply-chain/restock-suggestions?${params}`, {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
            'Content-Type': 'application/json'
        }
    });

    const suggestions = await response.json();

    // Process restock suggestions
    suggestions.data.forEach(item => {
        console.log(`SKU: ${item.sku}`);
        console.log(`Product: ${item.product_name}`);
        console.log(`Current Stock: ${item.current_stock} units`);
        console.log(`Days of Stock: ${item.days_of_stock}`);
        console.log(`Restock Quantity: ${item.suggested_quantity} units`);
        console.log(`Restock By: ${item.restock_by_date}`);
        console.log(`Lead Time: ${item.lead_time_days} days`);
        console.log('---');
    });

    return suggestions;
};

getRestockSuggestions();
curl -X GET "https://app.sellerlegend.com/api/supply-chain/restock-suggestions?account_title=My%20Store%20US&per_page=500¤cy=USD" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
Response Example:
{
  "current_page": 1,
  "data": [
    {
      "sku": "PROD-SKU-001",
      "product_name": "Example Product",
      "asin": "B0123456789",
      "current_stock": 45,
      "days_of_stock": 12,
      "velocity_30_days": 3.75,
      "suggested_quantity": 200,
      "restock_by_date": "2024-01-25",
      "lead_time_days": 30,
      "supplier": "Supplier ABC"
    }
  ],
  "total": 28,
  "per_page": 500
}

Notifications

GET /notifications/list List system notifications
Parameters:
Name Type Required Description
notification_type string Yes Type of notification to retrieve
Code Examples:
from sellerlegend_api import SellerLegendClient

client = SellerLegendClient(
    access_token="YOUR_ACCESS_TOKEN"
)

# Get notifications
notifications = client.notifications.list(
    account_title="My Store US",
    notification_type="inventory_alerts"  # or "price_alerts", "restock_alerts", etc.
)

# Process notifications
for notification in notifications['data']:
    print(f"Type: {notification['type']}")
    print(f"Title: {notification['title']}")
    print(f"Message: {notification['message']}")
    print(f"Severity: {notification['severity']}")
    print(f"Created: {notification['created_at']}")
    if notification['read']:
        print("Status: Read")
    else:
        print("Status: Unread")
    print("---")
<?php
use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'https://app.sellerlegend.com/api/',
    'headers' => [
        'Authorization' => 'Bearer YOUR_ACCESS_TOKEN'
    ]
]);

$response = $client->request('GET', 'notifications/list', [
    'query' => [
        'account_title' => 'My Store US',
        'notification_type' => 'inventory_alerts'
    ]
]);

$notifications = json_decode($response->getBody(), true);

// Process notifications
foreach ($notifications['data'] as $notification) {
    echo "Type: {$notification['type']}\n";
    echo "Title: {$notification['title']}\n";
    echo "Message: {$notification['message']}\n";
    echo "Severity: {$notification['severity']}\n";
    echo "Created: {$notification['created_at']}\n";
    echo "Status: " . ($notification['read'] ? 'Read' : 'Unread') . "\n";
    echo "---\n";
}
const getNotifications = async () => {
    const params = new URLSearchParams({
        account_title: 'My Store US',
        notification_type: 'inventory_alerts'  // or "price_alerts", "restock_alerts", etc.
    });

    const response = await fetch(`https://app.sellerlegend.com/api/notifications/list?${params}`, {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
            'Content-Type': 'application/json'
        }
    });

    const notifications = await response.json();

    // Process notifications
    notifications.data.forEach(notification => {
        console.log(`Type: ${notification.type}`);
        console.log(`Title: ${notification.title}`);
        console.log(`Message: ${notification.message}`);
        console.log(`Severity: ${notification.severity}`);
        console.log(`Created: ${notification.created_at}`);
        console.log(`Status: ${notification.read ? 'Read' : 'Unread'}`);
        console.log('---');
    });

    return notifications;
};

getNotifications();
curl -X GET "https://app.sellerlegend.com/api/notifications/list?account_title=My%20Store%20US¬ification_type=inventory_alerts" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
Response Example:
{
  "data": [
    {
      "id": 1234,
      "type": "inventory_alerts",
      "title": "Low Stock Alert",
      "message": "SKU PROD-SKU-001 has only 5 units remaining",
      "severity": "warning",
      "sku": "PROD-SKU-001",
      "created_at": "2024-01-15T14:30:00Z",
      "read": false
    },
    {
      "id": 1235,
      "type": "inventory_alerts",
      "title": "Out of Stock",
      "message": "SKU PROD-SKU-002 is now out of stock",
      "severity": "critical",
      "sku": "PROD-SKU-002",
      "created_at": "2024-01-15T15:00:00Z",
      "read": true
    }
  ]
}

Code Examples

# Python Example using SellerLegend SDK
from sellerlegend_api import SellerLegendClient

# Option 1: Use existing access token (recommended)
client = SellerLegendClient(
    access_token="YOUR_ACCESS_TOKEN",
    base_url="https://app.sellerlegend.com"
)

# Option 2: Use Authorization Code flow
client = SellerLegendClient(
    client_id="YOUR_CLIENT_ID",
    client_secret="YOUR_CLIENT_SECRET",
    base_url="https://app.sellerlegend.com"
)
# Get authorization URL
auth_url, state = client.get_authorization_url()
# ... user authorizes ...
# Exchange code for token
client.authenticate_with_code(code, state)

# Get user info
user = client.user.get_me()
print(f"Hello, {user['user']['name']}")

# Get sales orders
orders = client.sales.get_orders(
    start_date="2024-01-01",
    end_date="2024-01-31",
    per_page=500
)

# Process orders
for order in orders['data']:
    print(f"Order: {order['amazon_order_id']}")
    print(f"Total: {order['order_total']}")
// JavaScript Example using Fetch API
const API_BASE = 'https://app.sellerlegend.com/api';

// Use existing access token
const accessToken = 'YOUR_ACCESS_TOKEN';

// Or implement OAuth Authorization Code flow
function getAuthorizationUrl(clientId, redirectUri) {
    const params = new URLSearchParams({
        client_id: clientId,
        redirect_uri: redirectUri,
        response_type: 'code',
        scope: ''
    });
    return `https://app.sellerlegend.com/oauth/authorize?${params}`;
}

// Make API request
async function getOrders(accessToken, accountTitle) {
    const response = await fetch(`${API_BASE}/sales/orders?per_page=500`, {
        headers: {
            'Authorization': `Bearer ${accessToken}`,
            'X-Account-Title': accountTitle,
        },
    });

    return response.json();
}

// Usage with existing token
(async () => {
    const orders = await getOrders(accessToken, 'My Store US');
    console.log(orders);
})();
<?php
// PHP Example using Guzzle

use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'https://app.sellerlegend.com/api/',
]);

// Use existing access token
$token = 'YOUR_ACCESS_TOKEN';

// Or exchange authorization code for token
$response = $client->post('oauth/token', [
    'form_params' => [
        'grant_type' => 'authorization_code',
        'code' => $authorizationCode,
        'redirect_uri' => 'YOUR_REDIRECT_URI',
        'client_id' => 'YOUR_CLIENT_ID',
        'client_secret' => 'YOUR_CLIENT_SECRET',
    ]
]);

// If using authorization code flow:
// $token = json_decode($response->getBody(), true)['access_token'];

// Get orders
$response = $client->get('sales/orders', [
    'headers' => [
        'Authorization' => 'Bearer ' . $token,
        'X-Account-Title' => 'My Store US',
    ],
    'query' => [
        'per_page' => 500,
        'start_date' => '2024-01-01',
        'end_date' => '2024-01-31',
    ]
]);

$orders = json_decode($response->getBody(), true);
foreach ($orders['data'] as $order) {
    echo "Order: {$order['amazon_order_id']}\n";
}
# cURL Examples

# 1. Use existing access token or Authorization Code flow
# Option A: Direct usage with existing token
export ACCESS_TOKEN="YOUR_ACCESS_TOKEN"

# Option B: Exchange authorization code for token
curl -X POST https://app.sellerlegend.com/api/oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=authorization_code" \
  -d "code=AUTHORIZATION_CODE" \
  -d "redirect_uri=YOUR_REDIRECT_URI" \
  -d "client_id=YOUR_CLIENT_ID" \
  -d "client_secret=YOUR_CLIENT_SECRET"

# Save the access_token from response

# 2. Get User Info
curl -X GET https://app.sellerlegend.com/api/user/me \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

# 3. Get Sales Orders
curl -X GET "https://app.sellerlegend.com/api/sales/orders?per_page=500&start_date=2024-01-01&end_date=2024-01-31" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "X-Account-Title: My Store US"

# 4. Update Product Costs
curl -X POST https://app.sellerlegend.com/api/cogs/cost-periods \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "X-Account-Title: My Store US" \
  -H "Content-Type: application/json" \
  -d '{
    "sku": "PRODUCT-SKU",
    "data": [{
      "dates": {
        "from_date": "2024-01-01",
        "to_date": "2024-12-31"
      },
      "cost_elements": [{
        "cost_element": "Product Cost",
        "amount": 25.00,
        "currency": "USD"
      }]
    }]
  }'

Error Handling

Status Code Error Type Description Example Response
401 Unauthorized Invalid or expired token {"status": "Error", "code": 401, "message": "Unauthenticated"}
403 Forbidden User lacks API access {"status": "Error", "code": 403, "message": "Access Denied"}
404 Not Found Resource not found {"status": "Error", "code": 404, "message": "Not Found"}
422 Validation Error Invalid request parameters {"status": "Error", "code": 422, "message": "Validation Error", "errors": {...}}
429 Rate Limited Too many requests {"status": "Error", "code": 429, "message": "Rate limit exceeded"}

Rate Limiting

The API implements rate limiting to ensure fair usage:

  • Default limit: 180 requests per minute
  • Check response headers for current limits:
    • X-RateLimit-Limit - Maximum requests allowed (180)
    • X-RateLimit-Remaining - Requests remaining in current window
    • Retry-After - Seconds to wait before retrying (only present when rate limited with 429 status)
  • When rate limited, you'll receive a 429 Too Many Requests status code
  • Implement exponential backoff when rate limited
Note: The rate limit window resets every minute. When you receive a 429 status, check the Retry-After header to know how long to wait before retrying.

Support & Resources