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

# Refresh Statistics

> Fetch live statistics from TikTok/Instagram API for all accounts in your organization

## Endpoint

```
POST https://api.ugc.inc/stats/refresh
```

## Overview

Fetch fresh, real-time statistics directly from TikTok/Instagram API for all accounts in your organization (or a specific org\_group). This endpoint creates new stat records in the database with the latest data for each account and all their posts.

This is useful when you need up-to-date statistics for multiple accounts without waiting for the scheduled refresh cycle.

This endpoint also supports NDJSON streaming progress. Send the `X-Stream-Progress: true` header to receive line-delimited progress events instead of the standard JSON summary response.

<Warning>
  **Rate Limit:** Stats can only be refreshed **once per hour** per organization
  (or per org\_group if specified). If you attempt to refresh before the cooldown
  period has elapsed, you'll receive an error with details about when the next
  refresh is allowed.
</Warning>

## How It Works

1. Fetches all accounts in your organization (optionally filtered by org\_group)
2. For each account with username and type configured:
   * Fetches account profile stats (followers, following) from the platform API
   * Fetches stats for all posts associated with the account
   * Creates an `account_stats` record with aggregated post metrics
   * Creates individual `post_stats` records for each post
3. Returns summary counts of the refresh operation

## Request Body

<ParamField body="org_group" type="string">
  Optional. If provided, only refreshes accounts in this specific org\_group
</ParamField>

<ParamField body="force" type="boolean">
  Optional. If `true`, bypasses the once-per-hour rate limit
</ParamField>

## Optional Request Header

<ParamField header="X-Stream-Progress" type="'true'">
  Optional. When set to `true`, the endpoint streams newline-delimited JSON
  events with `type: "start"`, `type: "progress"`, and `type: "done"`.
</ParamField>

## Response

<ResponseField name="data" type="RefreshStatsResponse">
  Response object containing refresh results summary

  <Expandable title="RefreshStatsResponse properties">
    <ResponseField name="accounts_refreshed" type="number">
      Number of accounts successfully refreshed
    </ResponseField>

    <ResponseField name="accounts_failed" type="number">
      Number of accounts that failed to refresh
    </ResponseField>

    <ResponseField name="total_accounts" type="number">
      Total number of valid accounts processed
    </ResponseField>

    <ResponseField name="post_stats_count" type="number">
      Total number of post stats created across all accounts
    </ResponseField>

    <ResponseField name="errors" type="object[]">
      Optional. Array of error details for accounts that failed (only included if there were errors)
    </ResponseField>
  </Expandable>
</ResponseField>

<RequestExample>
  ```bash cURL theme={null}
  # Refresh all accounts in organization
  curl -X POST https://api.ugc.inc/stats/refresh \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{}'

  # Refresh only accounts in a specific org_group
  curl -X POST https://api.ugc.inc/stats/refresh \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "org_group": "influencers"
    }'
  ```

  ```python Python theme={null}
  import requests

  # Refresh all accounts
  response = requests.post(
      'https://api.ugc.inc/stats/refresh',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={}
  )

  data = response.json()

  if data['ok']:
      print(f"Successfully refreshed {data['data']['accounts_refreshed']} accounts")
      print(f"Failed: {data['data']['accounts_failed']}")
      print(f"Total posts refreshed: {data['data']['post_stats_count']}")
  ```

  ```javascript JavaScript theme={null}
  // Refresh all accounts
  const response = await fetch("https://api.ugc.inc/stats/refresh", {
    method: "POST",
    headers: {
      Authorization: "Bearer YOUR_API_KEY",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({}),
  });

  const data = await response.json();

  if (data.ok) {
    console.log(
      `Successfully refreshed ${data.data.accounts_refreshed} accounts`,
    );
    console.log(`Failed: ${data.data.accounts_failed}`);
    console.log(`Total posts refreshed: ${data.data.post_stats_count}`);
  }
  ```

  ```typescript React theme={null}
  import { UGCClient } from "ugcinc";

  const client = new UGCClient({
    apiKey: "YOUR_API_KEY",
  });

  // Refresh all accounts
  const response = await client.stats.refresh({});

  // Or refresh only specific org_group
  // const response = await client.stats.refresh({ org_group: 'influencers' });

  if (response.ok) {
    console.log(
      `Successfully refreshed ${response.data.accounts_refreshed} accounts`,
    );
    console.log(`Failed: ${response.data.accounts_failed}`);
    console.log(`Total posts refreshed: ${response.data.post_stats_count}`);

    if (response.data.errors) {
      console.log("\nErrors:");
      response.data.errors.forEach((err) => {
        console.log(`  Account ${err.accountId} (${err.username}): ${err.error}`);
      });
    }
  }
  ```

  ```typescript Streaming Progress theme={null}
  import { UGCClient } from "ugcinc";

  const client = new UGCClient({
    apiKey: "YOUR_API_KEY",
  });

  const response = await client.stats.refreshStream({ org_group: "influencers" });
  const reader = response.body?.getReader();
  const decoder = new TextDecoder();

  let buffer = "";

  while (reader) {
    const { done, value } = await reader.read();
    if (done) break;

    buffer += decoder.decode(value, { stream: true });
    const lines = buffer.split("\n");
    buffer = lines.pop() ?? "";

    for (const line of lines) {
      if (!line) continue;
      const event = JSON.parse(line);
      console.log(event.type, event);
    }
  }
  ```
</RequestExample>

<ResponseExample>
  ```json Success Response theme={null}
  {
    "ok": true,
    "code": 200,
    "message": "Stats refresh completed",
    "data": {
      "accounts_refreshed": 3,
      "accounts_failed": 0,
      "total_accounts": 3,
      "post_stats_count": 47
    }
  }
  ```

  ```json Success Response with Errors theme={null}
  {
    "ok": true,
    "code": 200,
    "message": "Stats refresh completed",
    "data": {
      "accounts_refreshed": 2,
      "accounts_failed": 1,
      "total_accounts": 3,
      "post_stats_count": 32,
      "errors": [
        {
          "accountId": "acc_999999",
          "username": "failed_account",
          "error": "Failed to fetch profile stats from social API"
        }
      ]
    }
  }
  ```

  ```json Rate Limit Error theme={null}
  {
    "ok": false,
    "code": 400,
    "message": "Stats can only be refreshed once per hour. Last refresh was 45 minutes ago. You can refresh again in 15 minute(s) at 2024-12-26T16:30:00.000Z"
  }
  ```

  ```json Rate Limit Error (org_group) theme={null}
  {
    "ok": false,
    "code": 400,
    "message": "Stats can only be refreshed once per hour for org_group \"influencers\". Last refresh was 30 minutes ago. You can refresh again in 30 minute(s) at 2024-12-26T16:00:00.000Z"
  }
  ```
</ResponseExample>
