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

# Events

> Events are data objects that represent individual user interactions against metrics in Trophy.

## What are events?

Events represent individual user interactions against [Metrics](https://docs.trophy.so/data-sources/metrics.md) in Trophy. One event corresponds to a single interaction made by a single user.

When you [integrate metrics](#tracking-metric-events) into your platform, you're setting up your platform to continuously stream events to your Trophy metrics for each user interaction. These interactions then drive all the in-app features you set up around these metrics, and give [agentic messaging](https://docs.trophy.so/agentic-messaging/overview.md) an up-to-date picture of each user's activity.

## Key attributes

### Event value

The `value` of an event is the numerical amount that will be added to the user's total metric count as a result of the user interaction it relates to.

> [!TIP]
>
> The value of an event can be positive or negative, and can be a whole number or a decimal.

## Custom event attributes

![](https://mintcdn.com/trophy/vvlxkggAvglghNGz/assets/features/events/custom_event_attributes.png?fit=max\&auto=format\&n=vvlxkggAvglghNGz\&q=85\&s=5e00c2a2e940301f30c3276aa4898f95)

You can specify a number of custom event attributes to help you track additional information relevant to your use case against events you send to Trophy.

For example, a language learning app might have a 'Questions Completed' metric and use a custom event attribute to store wether the answer to each question was correct.

Similarly a fitness app might use an 'Exercises Completed' metric and use a custom event attribute to store the weight that was used in each exercise and another custom event attribute to store how long the exercise lasted.

Using custom event attributes in this way allows you to enrich events in Trophy with additional context relevant to your use case and use it to power even more engaging in-app features.

### Creating attributes

To create a new custom event attribute, head to the [Attributes page](https://app.trophy.so/attributes) under *Data sources* in the Trophy dashboard and click the *Add event attribute* button.

Give the attribute a name and a unique key, you'll use the key when referencing the attribute in API calls.

<video autoPlay muted loop playsInline src="https://mintcdn.com/trophy/vvlxkggAvglghNGz/assets/features/events/create_custom_event_attribute.mp4?fit=max&auto=format&n=vvlxkggAvglghNGz&q=85&s=8356b41cffab6e4db75f5c9f4961a9c2" />

### Setting attributes

To set the value of a custom attribute on an event, pass its value in the `attributes` object in your metric tracking code.

> [!WARNING]
>
> Trophy will only set values of attributes that have first been created
> in the dashboard. We do this to help you keep a clean set of attributes and
> prevent accidental overwrites.
>
> If you receive an error similar to the following then you might have miss-spelled the attribute key in the request, or you need to create the attribute first in the Trophy dashboard:
>
> ```json theme={null}
> {
>   "error": "Invalid attribute keys: device. Please ensure all attribute keys match those set up at https://app.trophy.so/metrics."
> }
> ```

Here's an example of an event payload where the values of two attributes, `device` and `duration`, are set:

```json {7-10} theme={null}
{
  "user": {
    "id": "18",
    "tz": "Europe/London"
  },
  "value": 25,
  "attributes": {
    "device": "ios",
    "duration": "120"
  }
}
```

### Using attributes

Custom event attributes can be used to power more advanced triggers for milestones and points and can be used in email templates to customize copy and to control the data shown in charts.

#### Advanced feature triggers

Custom event attributes can be used to set up milestone or points triggers that only track events with specific attribute values. Follow the links to the relevant pages below to learn more.

> [card] [Milestone Triggers](https://docs.trophy.so/features/milestones.md#creating-achievements)
>
> Configure milestones that can only be completed by events with certain
> attribute values.

> [card] [Points Triggers](https://docs.trophy.so/features/points.md#points-triggers)
>
> Set up points triggers to only award points from events with specific
> attribute values.

#### Email customization

If you use any Trophy [Emails](https://docs.trophy.so/features/emails.md), event attributes can be used to customize the data shown in certain email blocks.

Firstly, when using metric-based variables in email copy you can use event attributes to further control what data the variable references.

For example here's a case where we use an email variable to tell users what their total number of workouts they've done on different gym equipment is using a metric 'Workouts' and an attribute 'Equipment':

<video autoPlay muted loop playsInline src="https://mintcdn.com/trophy/vvlxkggAvglghNGz/assets/features/events/using_attributes_in_emails.mp4?fit=max&auto=format&n=vvlxkggAvglghNGz&q=85&s=50726aa104a565984ce6867bf4369b51" />

Secondly, here's an example where we add a chart to an email that shows users how many workouts they've done on a bike over time:

<video autoPlay muted loop playsInline src="https://mintcdn.com/trophy/vvlxkggAvglghNGz/assets/features/events/using_attributes_in_email_charts.mp4?fit=max&auto=format&n=vvlxkggAvglghNGz&q=85&s=9783e48e19988b4a25294f4f856d5dd7" />

There's a huge number of possibilities here, so get creative!

## Tracking metric events

Each metric has a unique `key` which you can use to reference and track events against it in your code. You can find the `key` in the metric settings page.

To start tracking user interactions as events against your Trophy metrics, use the [Metrics API](https://docs.trophy.so/api-reference/endpoints/events/submit-a-metric-event.md) or one of our type-safe [Client SDKs](https://docs.trophy.so/api-reference/client-libraries.md) supported in most major programming languages.

If you're sending events in bulk from your backend (for example queue flushes, migrations, or batch imports), use the Admin API endpoint [Submit a batch of metric events](https://docs.trophy.so/admin-api/endpoints/events/submit-a-batch-of-metric-events.md) to send up to 1,000 metric events in one request.

Here's an example where a fictional study platform is using a metric to track the number of flashcards flipped by each student. Each time an student interacts, the platform sends an event to Trophy telling it how many flashcards they viewed:

```bash cURL theme={null}
curl -X POST https://api.trophy.so/v1/metrics/flashcards-flipped/event \
     -H "X-API-KEY: <apiKey>" \
     -H "Idempotency-Key: flashcard-view-42" \
     -H "Content-Type: application/json" \
     -d '{
  "user": {
    "id": "18",
    "email": "user@example.com",
    "tz": "Europe/London"
  },
  "value": 750
}'
```

```typescript Node theme={null}
import type { EventResponse } from "@trophyso/node/api";

const response: EventResponse = await trophy.metrics.event(
  "flashcards-flipped",
  {
    user: {
      id: "18",
      email: "user@example.com",
      tz: "Europe/London",
    },
    value: 750,
    idempotencyKey: "flashcard-view-42",
  }
);
```

```python Python theme={null}
client.metrics.event(
    key="flashcards-flipped",
    user=EventRequestUser(
        id="18",
        email="user@example.com",
        tz="Europe/London",
    ),
    value=750.0,
)
```

```php PHP theme={null}
$user = new EventRequestUser([
    'id' => '18',
    'email' => 'user@example.com'
]);

$request = new MetricsEventRequest([
    'user' => $user,
    'value' => 750
]);

$trophy->metrics->event("flashcards-flipped", $request);
```

```java Java theme={null}
MetricsEventRequest request = MetricsEventRequest.builder()
      .user(
        EventRequestUser.builder()
          .id("18")
          .email("user@example.com")
          .build()
      )
      .value(750)
      .build();

EventResponse response = client.metrics().event("flashcards-flipped", request);
```

```go Go theme={null}
response, err := client.Metrics.Event(
    "flashcards-flipped",
    &api.MetricsEventRequest{
        User: &api.EventRequestUser{
            Id: "18",
            Email: "user@example.com",
        },
        Value: 750,
    },
)
```

```csharp C# theme={null}
var user = new EventRequestUser {
   Id = "18",
   Email = "user@example.com"
};

var request = new MetricsEventRequest {
   User = user,
   Value = 750
};

await trophy.Metrics.EventAsync("flashcards-flipped", request);
```

```ruby Ruby theme={null}
result = client.metrics.event(
  :key => 'flashcards-flipped',
  :user => {
    :id => '18',
    :email => 'user@example.com'
  },
  :value => 750
)
```

Any [Milestones](https://docs.trophy.so/features/milestones.md), [Streaks](https://docs.trophy.so/features/streaks.md), [Points](https://docs.trophy.so/features/points.md) or [Leaderboards](https://docs.trophy.so/features/leaderboards.md) that have been set up against this metric will be automatically processed, and the response will contain any updates to the user's progress that are a direct result of the event occurring:

```json Response [expandable] theme={null}
{
  "metricId": "d01dcbcb-d51e-4c12-b054-dc811dcdc623",
  "eventId": "0040fe51-6bce-4b44-b0ad-bddc4e123534",
  "total": 750,
  "achievements": [
    {
      "id": "5100fe51-6bce-6j44-b0hs-bddc4e123682",
      "trigger": "metric",
      "metricId": "5100fe51-6bce-6j44-b0hs-bddc4e123682",
      "metricName": "Flashcards Flipped",
      "metricValue": 500,
      "name": "500 Flashcards Flipped",
      "description": "Flip 500 flashcards in the app.",
      "badgeUrl": null,
      "userAttributes": [],
      "achievedAt": "2020-01-01T00:00:00Z"
    }
  ],
  "currentStreak": {
    "length": 1,
    "frequency": "daily",
    "started": "2025-04-02",
    "periodStart": "2025-03-31",
    "periodEnd": "2025-04-05",
    "expires": "2025-04-12",
    "extended": true
  },
  "points": {
    "xp": {
      "id": "0040fe51-6bce-4b44-b0ad-bddc4e123534",
      "key": "xp",
      "name": "XP",
      "description": null,
      "badgeUrl": null,
      "maxPoints": null,
      "total": 10,
      "level": {
        "id": "1140fe51-6bce-4b44-b0ad-bddc4e123534",
        "key": "bronze",
        "name": "Bronze",
        "description": "Starting level",
        "badgeUrl": null,
        "points": 0
      },
      "added": 10,
      "awards": [
        {
          "id": "0040fe51-6bce-4b44-b0ad-bddc4e123534",
          "awarded": 10,
          "date": "2021-01-01T00:00:00Z",
          "total": 10,
          "trigger": {
            "id": "0040fe51-6bce-4b44-b0ad-bddc4e123534",
            "type": "metric",
            "metricName": "Flashcards Flipped",
            "metricThreshold": 100,
            "points": 10,
            "status": "active",
            "userAttributes": [],
            "created": "2021-01-01T00:00:00Z",
            "updated": "2021-01-01T00:00:00Z"
          }
        }
      ]
    }
  },
  "leaderboards": {
    "daily_champions": {
      "id": "0040fe51-6bce-4b44-b0ad-bddc4e123535",
      "key": "daily_champions",
      "name": "Daily Champions",
      "description": null,
      "status": "active",
      "rankBy": "metric",
      "runUnit": "day",
      "runInterval": 1,
      "maxParticipants": 100,
      "breakdownAttributes": [],
      "metricName": "Flashcards Flipped",
      "metricKey": "flashcards-flipped",
      "threshold": 10,
      "start": "2025-01-01",
      "end": null,
      "startTime": null,
      "endTime": null,
      "previousRank": 50,
      "rank": 12
    }
  },
  "idempotencyKey": "flashcard-view-42",
  "idempotentReplayed": false
}
```

In this example the response includes the following:

* The user's newly completed milestones (`achievements` in the response) as a result of the event
* The user's latest streak as result of the event
* The user's latest points for each points system that changed as a result of the event
* The user's latest leaderboard data for each leaderboard that changed as a result of the event

With a little bit of custom code, this response data can be used to drive any in-app experience you wish including:

* Triggering in-app notifications
* Sound effects
* Animations

### Idempotent events

Trophy supports enforcing uniqueness on events so that users cannot increase a metric by taking the same exact action over and over.

For example, a language learning app could specify that users can only increase the `lessons-completed` metric by 1 for each unique lesson completed, so if they complete the same lesson twice only the first counts.

```bash cURL {3} theme={null}
curl -X POST https://app.trophy.so/api/metrics/lessons-completed/event \
     -H "X-API-KEY: <apiKey>" \
     -H "Idempotency-Key: <lesson-123>" \
     -H "Content-Type: application/json" \
     -d '{
  "user": {
    "id": "18",
    "email": "user@example.com",
    "tz": "Europe/London"
  },
  "value": 1
}'
```

```typescript Node {9} theme={null}
trophy.metrics.event("lessons-completed",
  {
    user: {
      id: "18",
      email: "user@example.com",
      tz: "Europe/London",
    },
    value: 1,
    idempotencyKey: "lesson-123",
  }
);
```

```python Python {9} theme={null}
client.metrics.event(
    key="lessons-completed",
    user=EventRequestUser(
        id="18",
        email="user@example.com",
        tz="Europe/London",
    ),
    value=1,
    idempotencyKey="lesson-123"
)
```

```php PHP {9} theme={null}
$user = new EventRequestUser([
    'id' => '18',
    'email' => 'user@example.com'
]);

$request = new MetricsEventRequest([
    'user' => $user,
    'value' => 1,
    'idempotencyKey' => 'lesson-123'
]);

$trophy->metrics->event("lessons-completed", $request);
```

```java Java {9} theme={null}
MetricsEventRequest request = MetricsEventRequest.builder()
      .user(
        EventRequestUser.builder()
          .id("18")
          .email("user@example.com")
          .build()
      )
      .value(1)
      .idempotencyKey("lesson-123")
      .build();

EventResponse response = client.metrics().event("lessons-completed", request);
```

```go Go {10} theme={null}
response, err := client.Metrics.Event(
    "lessons-completed",
    &api.MetricsEventRequest{
        User: &api.EventRequestUser{
            Id: "18",
            Email: "user@example.com",
        },
        Value: 1,
        IdempotencyKey: "lesson-123"
    },
)
```

```csharp C# {9} theme={null}
var user = new EventRequestUser {
   Id = "18",
   Email = "user@example.com"
};

var request = new MetricsEventRequest {
   User = user,
   Value = 1,
   IdempotencyKey = "lesson-123"
};

await trophy.Metrics.EventAsync("lessons-completed", request);
```

```ruby Ruby {8} theme={null}
result = client.metrics.event(
  :key => 'lessons-completed',
  :user => {
    :id => '18',
    :email => 'user@example.com'
  },
  :value => 1,
  :idempotencyKey => 'lesson-123'
)
```

This helps keep your codebase free of logic that checks if users have completed actions before, and can instead trust Trophy to uphold the constraints you need.

To use idempotent events, use the `Idempotency-Key` header in the [metric event API](https://docs.trophy.so/api-reference/endpoints/events/submit-a-metric-event.md).

[Learn more about idempotency](https://docs.trophy.so/api-reference/idempotency.md).

### Parallel events

Trophy does not support parallel events to same metric for the same user. Instead, use the `value` parameter to increment the metric by the total amount of all individual events that you need to track.

```bash cURL {10} theme={null}
curl -X POST https://app.trophy.so/api/metrics/lessons-completed/event \
     -H "X-API-KEY: <apiKey>" \
     -H "Content-Type: application/json" \
     -d '{
  "user": {
    "id": "18",
    "email": "user@example.com",
    "tz": "Europe/London"
  },
  "value": 5
}'
```

```typescript Node {7} theme={null}
trophy.metrics.event("lessons-completed", {
  user: {
    id: "18",
    email: "user@example.com",
    tz: "Europe/London",
  },
  value: 5,
});
```

```python Python {8} theme={null}
client.metrics.event(
    key="lessons-completed",
    user=EventRequestUser(
        id="18",
        email="user@example.com",
        tz="Europe/London",
    ),
    value=5,
)
```

```php PHP {8} theme={null}
$user = new EventRequestUser([
    'id' => '18',
    'email' => 'user@example.com'
]);

$request = new MetricsEventRequest([
    'user' => $user,
    'value' => 5,
]);

$trophy->metrics->event("lessons-completed", $request);
```

```java Java {8} theme={null}
MetricsEventRequest request = MetricsEventRequest.builder()
      .user(
        EventRequestUser.builder()
          .id("18")
          .email("user@example.com")
          .build()
      )
      .value(5)
      .build();

EventResponse response = client.metrics().event("lessons-completed", request);
```

```go Go {8} theme={null}
response, err := client.Metrics.Event(
    "lessons-completed",
    &api.MetricsEventRequest{
        User: &api.EventRequestUser{
            Id: "18",
            Email: "user@example.com",
        },
        Value: 5,
    },
)
```

```csharp C# {8} theme={null}
var user = new EventRequestUser {
   Id = "18",
   Email = "user@example.com"
};

var request = new MetricsEventRequest {
   User = user,
   Value = 5,
};

await trophy.Metrics.EventAsync("lessons-completed", request);
```

```ruby Ruby {7} theme={null}
result = client.metrics.event(
  :key => 'lessons-completed',
  :user => {
    :id => '18',
    :email => 'user@example.com'
  },
  :value => 5
)
```

## Get support

Want to get in touch with the Trophy team? Reach out to us via [email](mailto:support@trophy.so). We're here to help!


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.