# Retrieve usage summary for a subscription

> For the complete machine-readable documentation index, see [llms.txt](https://apidocs.chargebee.com/llms.txt).


[Eventually Consistent](/docs/api/read-consistency)

Retrieves aggregated usage data for a metered feature in a subscription over a specified reporting window.

Unlike [Retrieve Current Usage Charges for a Subscription](/docs/api/usage_charges/retrieve-usage-charges-for-a-subscription) API, which returns the current unbilled usage snapshot including charges, this endpoint returns aggregated usage for a requested timeframe.

Use this endpoint to power experiences such as:

-   plotting daily, weekly, or monthly usage trends
-   analyzing feature adoption over time
-   comparing recent usage against earlier periods
-   showing historical usage summaries to subscribers

### What this endpoint returns[](#what-this-endpoint-returns)

Returns usage summary entries for the requested feature within the specified timeframe.

If `timeframe_start` and `timeframe_end` are not provided, the reporting range **defaults to the start of the subscription's current term for `timeframe_start` and the current time for `timeframe_end`.**

### How aggregation works[](#how-aggregation-works)

-   If `window_size` is omitted, the response returns a single aggregate for the full reporting range.
-   If `window_size` is provided, the response returns one aggregated entry for each window in the reporting range.

Aggregation windows begin at `timeframe_start` and continue consecutively until `timeframe_end`.

The usages in the window will be bucketed into **rolling windows** aligned to `timeframe_start`, **not to calendar boundaries**.

#### Example[](#example)

If:

-   `timeframe_start` is `May 10 10:00:00 UTC`
-   `timeframe_end` is `June 10 10:00:00 UTC`
-   `window_size` is `day`

The response returns windows such as:

-   `May 10 10:00:00 UTC` → `May 11 10:00:00 UTC`
-   `May 11 10:00:00 UTC` → `May 12 10:00:00 UTC`

and continues in the same pattern until the final window:

-   `June 9 10:00:00 UTC` → `June 10 10:00:00 UTC`

If you need calendar-aligned reporting, set `timeframe_start` to the required boundary. For example, use `00:00:00 UTC` for daily reporting aligned to calendar days, or the first day of the month at `00:00:00 UTC` for monthly reporting aligned to calendar months.

Each aggregation window follows inclusive-exclusive semantics:

-   `aggregated_from` is inclusive
-   `aggregated_till` is exclusive

In other words, each window is represented as `aggregated_from` and `aggregated_till`.

This means:

-   an event with a timestamp exactly equal to `aggregated_from` is included in that window
-   an event with a timestamp exactly equal to `aggregated_till` is excluded from that window and counted in the next window, if one exists
-   an event with a timestamp exactly equal to `timeframe_end` is excluded

These inclusive-exclusive boundaries ensure that windows do not overlap and that events on boundaries are never double-counted.

### Distinct-count behavior[](#distinct-count-behavior)

If a feature uses distinct-count aggregation, the distinct count is evaluated separately within each returned window.

This means the same entity can be counted once in multiple windows if it appears in each of them.

#### Example[](#example)

If the same user appears in both:

-   one daily window on **Jan 1**
-   another daily window on **Jan 2**

That user is counted once in the Jan 1 aggregate and once in the Jan 2 aggregate.

## Sample Request

#### cURL

```bash
curl  https://{site}.chargebee.com/api/v2/subscriptions/__test__8asukSOXdv6kOj/usage_summary \
     -G  \
     -u {site_api_key}:\
     --data-urlencode feature_id="storage"
```

#### .NET

```dotnet
using ChargeBee.Api;
using ChargeBee.Models;

ApiConfig.Configure("{site}","{site_api_key}");
ListResult result = UsageSummary.RetrieveUsageSummaryForSubscription("__test__8asukSOXdv6kOj")
		.FeatureId("storage")
		.Request();

foreach (var listItem in result.List){
  UsageSummary usageSummary = listItem.UsageSummary;
}
```

#### Go

```go
package main
import (
    "fmt"
    "github.com/chargebee/chargebee-go/v3"
    usagesummaryAction "github.com/chargebee/chargebee-go/v3/actions/usagesummary"
    "github.com/chargebee/chargebee-go/v3/models/usagesummary"
)
func main() {
    chargebee.Configure("{site_api_key}","{site}");
    res,err := usagesummaryAction.RetrieveUsageSummaryForSubscription("__test__8asukSOXdv6kOj", &usagesummary.RetrieveUsageSummaryForSubscriptionRequestParams{
        FeatureId : "storage",
    }).ListRequest()
    if err != nil {
        fmt.Println(err)
    } else {
        for idx := 0; idx < len(res.List); idx++ {
            UsageSummary := res.List[idx].UsageSummary
        }
    }
}
```

#### Go

```go
package main

import (
  "fmt"
  "github.com/chargebee/chargebee-go/v4"
)

func main() {
  config := &chargebee.ClientConfig{
    SiteName: "{site}",
    ApiKey: "{site_api_key}",
  }    
  client := chargebee.NewClient(config)
  req := &chargebee.UsageSummaryRetrieveUsageSummaryForSubscriptionRequest{
    FeatureId : "storage",
}
  res, err := client.UsageSummary.RetrieveUsageSummaryForSubscription("__test__8asukSOXdv6kOj", req)
      if err != nil {
        fmt.Println(err)
    } else {
        for idx := 0; idx < len(res.List); idx++ {
            UsageSummary := res.List[idx].UsageSummary
        }
    }
}
```

#### Java

```java
import com.chargebee.*;
import com.chargebee.ListResult;
import com.chargebee.models.*;
import com.chargebee.models.enums.*;
import java.io.IOException;
import java.util.List;

public class Sample {

    public static void main(String args[]) throws IOException, Exception {
        Environment.configure("{site}", "{site_api_key}");
        ListResult result = UsageSummary.retrieveUsageSummaryForSubscription("__test__8asukSOXdv6kOj")
            .featureId("storage")
            .request();

        for (ListResult.Entry entry : result) {
            UsageSummary usageSummary = entry.usageSummary();
        }
    }
}
```

#### Java

```java
import com.chargebee.v4.client.ChargebeeClient;
import com.chargebee.v4.models.usageSummary.UsageSummary;
import com.chargebee.v4.models.usageSummary.params.RetrieveUsageSummaryForSubscriptionParams;
import com.chargebee.v4.models.usageSummary.responses.RetrieveUsageSummaryForSubscriptionResponse;
import java.util.List;

public class RetrieveUsageSummaryForSubscription {

    public static void main(String[] args) {
        ChargebeeClient client = ChargebeeClient.builder()
            .apiKey("{site_api_key}")
            .siteName("{site}")
            .build();

        RetrieveUsageSummaryForSubscriptionParams params = RetrieveUsageSummaryForSubscriptionParams.builder()
            .featureId("storage")
            .build();

        RetrieveUsageSummaryForSubscriptionResponse response = client
            .usageSummaries()
            .retrieveUsageSummaryForSubscription("__test__8asukSOXdv6kOj", params);
    }
}
```

#### Node.js

```node
import Chargebee from "chargebee";

const chargebee = new Chargebee({
    site: "{site}",
    apiKey: "{site_api_key}",
});

try {
    const result = await chargebee.usageSummary.retrieveUsageSummaryForSubscription("__test__8asukSOXdv6kOj", {
        feature_id: "storage"
    });
    result.list.forEach((entry) => {
        console.log(entry);
        const usageSummary = entry.usage_summary;
    });
} catch (err) {
    console.log(err);
}
```

#### PHP

```php
<?php

require __DIR__ . '/vendor/autoload.php';

use Chargebee\ChargebeeClient;

$chargebee = new ChargebeeClient(options: [
    "site" => "{site}",
    "apiKey" => "{site_api_key}",
]);
$result = $chargebee->usageSummary()->retrieveUsageSummaryForSubscription("__test__8asukSOXdv6kOj", [
    "feature_id" => "storage"
]);
foreach($result->list as $entry) {
    $usageSummary = $entry->usage_summary;
}
```

#### Python

```python
from chargebee import Chargebee, Filters

cb_client = Chargebee(api_key="{site_api_key}", site="{site}")
entries = cb_client.UsageSummary.retrieve_usage_summary_for_subscription("__test__8asukSOXdv6kOj",
    cb_client.UsageSummary.RetrieveUsageSummaryForSubscriptionParams(
        feature_id="storage"
    )
)
for entry in entries.list:
    usage_summary = entry.usage_summary
```

#### Ruby

```ruby
require 'chargebee'

ChargeBee.configure(:site => "{site}",
  :api_key => "{site_api_key}")

list = ChargeBee::UsageSummary.retrieve_usage_summary_for_subscription("__test__8asukSOXdv6kOj",{
  :feature_id => "storage"
})

list.each do |entry|
  usage_summary = entry.usage_summary
end
```

## Sample Response

```json
{
  "list": [
    {
      "usage_summary": {
        "subscription_id": "sub-001",
        "feature_id": "storage",
        "aggregated_value": 350,
        "aggregated_from": 1762286390,
        "aggregated_to": 1762372708
      }
    },
    {..}
  ]
}
```

## URL Format

**GET** https://[site].chargebee.com/api/v2/subscriptions/{subscription-id}/usage_summary

## Input Parameters

- `limit` (optional, integer, default=10, min=1, max=100)
  The number of resources to be returned.

- `offset` (optional, string, max chars=1000)
  Determines your position in the list for pagination. To ensure that the next page is retrieved correctly, always set `offset` to the value of `next_offset` obtained in the previous iteration of the API call.

- `feature_id` (required, string, max chars=100)
  Unique identifier of the metered [feature](/docs/api/features/feature-object#id) for which usage is aggregated

- `window_size` (optional, enumerated string)
  Specifies the aggregation interval for the reporting window. If omitted, the response includes a single aggregate for the entire reporting window.
  Possible enum values:
    - `month`
    - `week`
    - `day`
    - `hour`
    - `minute`

- `timeframe_start` (optional, timestamp(UTC) in seconds)
  Start of the reporting window, in Unix epoch seconds. If not provided, defaults to the start of the current subscription term.

- `timeframe_end` (optional, timestamp(UTC) in seconds)
  End of the reporting window, in Unix epoch seconds. If not provided, defaults to the current time

## Returns

- `next_offset` (optional, string, max chars=1000)
  This attribute is returned only if more resources are present. To fetch the next set of resources use this value for the input parameter `offset`.

- `usage_summary` (Usage summary object)
  Resource object representing `usage_summary`
