> For the complete documentation index, see [llms.txt](https://docs.thewalletcrew.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.thewalletcrew.io/developers-guides/integration-guides/insights-api.md).

# Insights API

Query tenant-scoped wallet events, logs, requests and page views with the Insights API and Kusto Query Language (KQL) for reporting and analytics.

The **Insights API** gives access to the usage database of The Wallet Crew. Query logs, events, requests, and page views using [Kusto Query Language (KQL)](https://learn.microsoft.com/en-us/kusto/query/).

This API is designed for technical teams extracting data programmatically. Use it for custom date ranges, custom groupings, BI ingestion, and automated reports, when the dashboard is not enough.

{% hint style="info" %}
The **Analytics** dashboards in the admin console are built on the same event data. Everything they show can also be queried here, with more flexibility on groupings, filters and date ranges. For a no-code view, use [Analytics dashboards](https://docs.thewalletcrew.io/guides-monitoring/monitor/analytics-dashboards.md). For record-level CSV exports, see [Export data](https://docs.thewalletcrew.io/guides-monitoring/monitor/report.md).
{% endhint %}

## Common use cases

* Feed installation and uninstall counts into Tableau, Looker, or Power BI.
* Automate a weekly report of program performance by store or region.
* Build a custom activation funnel by correlating `Pass:Created` with `Pass:Installed`.
* Query scan events to build a redemption analytics view.
* Validate campaign delivery by comparing `Pass:NotificationSent` with install spikes.

## Authentication and permissions

* Send the tenant API key in the `X-API-KEY` header.
* Create the key in **Settings → Access control → API keys & secrets** (see [API keys & secrets](https://docs.thewalletcrew.io/configure/advanced-configuration/platform/api-keys-and-secrets.md)). It needs the scope **`tenant.insights:read`**. A missing or invalid key returns `401`. A key without the scope returns `403`.
* Single-tenant scope: a key queries only its own tenant. The platform adds the tenant filter.

## Retention and rate limits

* **Logs**: retained **45 days**
* **Events** and **page views**: retained **indefinitely**

**Rate limit**: 60 calls per minute by default. To request a higher limit, open a support ticket.

The API does not cache results. Cache on your side when you poll.

## Endpoint

All queries use this operation:

## Run an analytics query

> Reference parameters by name, e.g. \`{"query": "Events | where Name == eventName | take 100", "parameters": {"eventName": "Pass:Installed"}}\`.

```json
{"openapi":"3.1.1","info":{"title":"The Wallet Crew internal API","version":"v1"},"tags":[{"name":"Insights"}],"servers":[{"url":"https://api.thewalletcrew.io","description":"Production Server"},{"url":"https://api-qa.thewalletcrew.io","description":"Staging Server"}],"security":[{"admin-bearer":["tenant.insights:read"]},{"apiKey":[]}],"components":{"securitySchemes":{"admin-bearer":{"type":"oauth2","flows":{"implicit":{"authorizationUrl":"https://auth.neostore.cloud/authorize?audience=https://app.neostore.cloud/api/","scopes":{}}}},"apiKey":{"type":"apiKey","name":"X-API-KEY","in":"header"}},"schemas":{"QueryRequest":{"required":["query"],"type":"object","properties":{"query":{"type":"string","description":"KQL text. Only analytics-schema tables and columns are accepted, over the tenant's own data; invalid KQL returns 400 with a diagnostic."},"parameters":{"type":"object","additionalProperties":{"type":"string"},"description":"Query parameter values by name, passed as KQL strings. Names start with a letter or `_`, then letters, digits or `_`. `params_tenantId` is reserved."},"options":{"description":"Execution settings; defaults apply when omitted.","$ref":"#/components/schemas/QueryOptions"}},"additionalProperties":false,"description":"KQL query to run."},"QueryOptions":{"type":"object","properties":{"maxRows":{"type":"integer","description":"Row limit, 1 to 100,000 (default). Out of range, or more matching rows, returns 400: aggregate or narrow the query.","format":"int32"}},"additionalProperties":false,"description":"Execution settings."},"QueryResponse":{"type":"object","properties":{"columns":{"type":"array","items":{"type":"string"},"description":"Column names, in projection order."},"rows":{"type":"array","items":{"type":"array","items":{}},"description":"One array per row, one value per column. Empty cells are `null`, `dynamic` cells are JSON values, dates are UTC."}},"additionalProperties":false,"description":"Query result."},"ProblemDetails":{"type":"object","properties":{"type":{"type":["null","string"]},"title":{"type":["null","string"]},"status":{"type":["null","integer"],"format":"int32"},"detail":{"type":["null","string"]},"instance":{"type":["null","string"]}},"additionalProperties":{}},"HttpValidationProblemDetails":{"type":"object","allOf":[{"$ref":"#/components/schemas/ProblemDetails"}],"properties":{"errors":{"type":"object","additionalProperties":{"type":"array","items":{"type":"string"}}}},"additionalProperties":{}}}},"paths":{"/api/{tenantId}/insights/query":{"post":{"tags":["Insights"],"summary":"Run an analytics query","description":"Reference parameters by name, e.g. `{\"query\": \"Events | where Name == eventName | take 100\", \"parameters\": {\"eventName\": \"Pass:Installed\"}}`.","parameters":[{"name":"tenantId","in":"path","required":true,"schema":{"type":"string"}}],"requestBody":{"description":"Query text, parameters and options.","content":{"application/json":{"schema":{"description":"KQL query to run.","$ref":"#/components/schemas/QueryRequest"}},"text/json":{"schema":{"description":"KQL query to run.","$ref":"#/components/schemas/QueryRequest"}},"application/*+json":{"schema":{"description":"KQL query to run.","$ref":"#/components/schemas/QueryRequest"}}}},"responses":{"200":{"description":"Column names and rows.","content":{"text/plain":{"schema":{"description":"Query result.","$ref":"#/components/schemas/QueryResponse"}},"application/json":{"schema":{"description":"Query result.","$ref":"#/components/schemas/QueryResponse"}},"text/json":{"schema":{"description":"Query result.","$ref":"#/components/schemas/QueryResponse"}}}},"400":{"description":"Empty or invalid query, unknown table or column, invalid or reserved parameter name, `maxRows` out of range, or more rows than `maxRows`.","content":{"text/plain":{"schema":{"oneOf":[{"$ref":"#/components/schemas/ProblemDetails"},{"$ref":"#/components/schemas/HttpValidationProblemDetails"}]}},"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/ProblemDetails"},{"$ref":"#/components/schemas/HttpValidationProblemDetails"}]}},"text/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/ProblemDetails"},{"$ref":"#/components/schemas/HttpValidationProblemDetails"}]}}}},"401":{"description":"The caller is not authenticated.","content":{"application/problem+json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/ProblemDetails"},{"$ref":"#/components/schemas/HttpValidationProblemDetails"}]}}}},"403":{"description":"The caller lacks the `tenant.insights:read` scope, or the endpoint is not enabled for the tenant.","content":{"application/problem+json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/ProblemDetails"},{"$ref":"#/components/schemas/HttpValidationProblemDetails"}]}}}},"404":{"description":"The tenant does not exist.","content":{"application/problem+json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/ProblemDetails"},{"$ref":"#/components/schemas/HttpValidationProblemDetails"}]}}}},"429":{"description":"Over 60 requests per minute to this endpoint for the tenant (default limit); retry after `Retry-After`.","headers":{"Retry-After":{"description":"Seconds to wait before retrying. Sent when the limiter knows it.","schema":{"type":"integer"}}},"content":{"application/problem+json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/ProblemDetails"},{"$ref":"#/components/schemas/HttpValidationProblemDetails"}]}}}},"504":{"description":"Query ran too long; aggregate or narrow it."}}}}}}
```

```http
POST /api/{tenantId}/insights/query
X-API-KEY: <API_KEY>
Content-Type: application/json
```

The base URLs of the production and QA environments are in [Getting started with the API](https://docs.thewalletcrew.io/developers-guides/integration-guides/getting-started-with-the-api.md).

* `{tenantId}` = your tenant identifier
* The request body must contain a `query` string in **KQL**.
* Pass values through `parameters` (named query parameters) instead of concatenating them into the query. Names start with a letter or `_`; `params_tenantId` is reserved.
* `options.maxRows` sets the row limit, from 1 to 100,000 (the default). A query that matches more rows, or a value out of range, returns `400`: aggregate or narrow the query.
* `400` also covers an empty or invalid query and an unknown table or column. `504` means the query ran too long.

A first query, which returns the last 50 errors. The host `api.thewalletcrew.io` is the production base URL:

```bash
curl -X POST "https://api.thewalletcrew.io/api/<TENANT_ID>/insights/query" \
  -H "X-API-KEY: <API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "Logs | where Timestamp > ago(1h) and SeverityLevel >= 3 | project Timestamp, CategoryName, OperationId, Message | order by Timestamp desc | take 50"
  }'
```

The response is tabular:

```json
{
  "columns": ["Timestamp", "CategoryName", "OperationId", "Message"],
  "rows": [
    ["2026-09-14T19:15:02.117Z", "Runtime.Http...", "4454c9229...", "..."]
  ]
}
```

## Tables and schema

The Insights database exposes these tables. Table and column names are case-sensitive. There is no `Metrics` table.

| Table       | What it contains                                              | Main columns                                                                                   |
| ----------- | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| `Events`    | Business events such as `Pass:Created` or `Customer:Upserted` | `Timestamp`, `Name`, `OperationId`, `UserId`, `EventData` (dynamic)                            |
| `Logs`      | Errors and traces of platform activity, for debugging         | `Timestamp`, `SeverityLevel`, `Message`, `CategoryName`, `OperationId`, `Properties` (dynamic) |
| `Requests`  | API requests                                                  | `Timestamp`, `Name`, `Duration`, `ResultCode`, `Success`, `OperationId`                        |
| `PageViews` | Page views of enrolment and download pages                    | `Timestamp`, `Name`, `Url`, `LayoutName`, `LayoutType`, `UserAgent`                            |

Every table has a `TenantId` column. Event details sit in `EventData`, for example `EventData.passId`.

## Common queries

### Count customer upserts

```kql
Events
| where Timestamp > ago(30d)
| where Name == "Customer:Upserted"
| summarize CustomerUpserts = count()
```

### Count pass installations

```kql
Events
| where Timestamp > ago(30d)
| where Name == "Pass:Installed"
| summarize PassInstallations = count()
```

### Count API requests per day

```kql
Requests
| where Timestamp > ago(30d)
| summarize RequestsPerDay = count() by bin(Timestamp, 1d)
```

### Count redirects per day

```kql
Events
| where Timestamp > ago(30d)
| where Name == "Redirect:Redirected"
| summarize RedirectsPerDay = count() by bin(Timestamp, 1d)
```

### Count page views per layout

```kql
PageViews
| where Timestamp > ago(30d)
| summarize PageViews = count() by LayoutName
```

### Filter on a structured property

```kql
Logs
| where Timestamp > ago(2d)
| where tostring(Properties.requestPath) startswith "/api/"
| summarize Calls = count() by tostring(Properties.requestPath)
| order by Calls desc
| take 25
```

### Error rate as a percentage

```kql
Logs
| where Timestamp > ago(24h)
| summarize Total = count(), Failures = countif(SeverityLevel >= 3)
| extend ErrorRate = round(100.0 * Failures / Total, 2)
```

### Everything that touches one pass, in the logs

```kql
Logs
| where Timestamp > ago(30d)
| where * contains "<PASS_SERIAL>"
| project Timestamp, SeverityLevel, CategoryName, Message
| order by Timestamp desc
```

For the error and trace recipes on `Logs`, see [Retrieve platform logs](https://docs.thewalletcrew.io/guides-monitoring/monitor/retrieve-platform-logs.md).

### History of one pass, with a parameter

```json
{
  "query": "declare query_parameters(passId:string); Events | where Timestamp > ago(90d) | where tostring(EventData.passId) == passId | project Timestamp, Name, EventData | order by Timestamp desc | take 50",
  "parameters": { "passId": "{passId}" },
  "options": { "maxRows": 1000 }
}
```

### Parameter types and paging

Parameters arrive as strings: cast them in the query, with `todatetime()` or `toint()`. Page through large results by numbering and slicing rows:

```json
{
  "query": "Logs\n| where Timestamp between (todatetime(start) .. todatetime(stop))\n| where * contains searchQuery\n| order by Timestamp desc\n| serialize rowNum = row_number()\n| where rowNum > (toint(pageIndex) * toint(pageSize))\n  and rowNum <= ((toint(pageIndex) + 1) * toint(pageSize))\n| project Timestamp, Message, OperationName, OperationId, SeverityLevel, CategoryName, Properties",
  "parameters": {
    "start": "2026-09-01T00:00:00.000Z",
    "stop": "2026-09-14T23:59:59.999Z",
    "searchQuery": "outdated",
    "pageIndex": "0",
    "pageSize": "100"
  }
}
```

A query that returns more rows than `options.maxRows` fails by design instead of returning a trimmed result that looks complete.

## Common event names

The `Name` column of `Events` holds the event name. Webhooks use the same names. Each event is defined in [What The Wallet Crew tracks](https://docs.thewalletcrew.io/guides-monitoring/monitor/what-the-wallet-crew-tracks.md#event-reference). Each event answers a different business question:

| Event                   | What it captures                                                                                                   | Example question                                                   |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------ |
| `Pass:Created`          | A pass record was created.                                                                                         | How many passes were issued this month per store?                  |
| `Pass:Installed`        | A pass was added to Apple Wallet or Google Wallet, with its source in `registrationSource` (medium, tags, origin). | Which email campaign drove the most installs last week?            |
| `Pass:Uninstalled`      | A pass was removed from its last device on one wallet.                                                             | What is the uninstall rate by program?                             |
| `Pass:Updated`          | Pass data changed.                                                                                                 | How many passes were updated after the last campaign?              |
| `Pass:UpdateSent`       | A push update was delivered to a device.                                                                           | Are updates reaching devices reliably?                             |
| `Pass:Scanned`          | A pass barcode was scanned.                                                                                        | How many scans per day happened at each location?                  |
| `Pass:NotificationSent` | A push notification was sent.                                                                                      | How many notifications were sent per program this month?           |
| `Pass:LinkOpened`       | The holder tapped a tracked link of the pass.                                                                      | Which links of the pass do holders open?                           |
| `Customer:Upserted`     | A customer was created or updated.                                                                                 | How many customer profiles were created or updated this week?      |
| `Redirect:Redirected`   | A user opened a minified URL (redirect).                                                                           | How many scans of the in-store QR code reached the enrolment form? |

## Filters

Filter an `Events` query on the date (`Timestamp`), the event (`Name`), and the fields of `EventData`:

* On `Pass:Installed`, the installation source is in `EventData.registrationSource`: `medium`, `tags` (an array, read it with `mv-expand`), `origin` (the page URL; derive the host with `parse_url`) and `userAgent`.
* Every `Pass:*` event carries `EventData.passType` (the pass template), `EventData.metadata.<key>` (the pass metadata, such as `storeId`) and `EventData.passTypeTags`.

To discover the shape of `EventData`, return one raw event:

```kql
Events
| where Timestamp > ago(7d)
| where Name == "Pass:Created"
| project Timestamp, Name, EventData
| order by Timestamp desc
| take 1
```

## Query from an AI assistant (MCP)

An assistant connected over MCP can run the same queries. The MCP connection needs no API key: sign in with admin console credentials (OAuth). See [Model Context Protocol (MCP)](https://docs.thewalletcrew.io/connectors/model-context-protocol-mcp.md) for the endpoints and set-up.

| Tool                      | Use                                                                      |
| ------------------------- | ------------------------------------------------------------------------ |
| `twc_insights_schema_get` | Confirm available tables, columns and event names, with worked examples. |
| `twc_insights_query`      | Run KQL and return results.                                              |

Prompt patterns for investigations:

> Show every error and warning from the last 24 hours, grouped by component. For the three noisiest, explain the component and messages.

> Find log lines for pass `<PASS_ID>` from the last 7 days. Reconstruct what happened and identify failed steps.

> Operation `<OPERATION_ID>` failed. Pull its lines in order and identify where it broke.

> Compare this week's error volume with last week. Flag components whose failures more than doubled.

{% hint style="info" %}
Keep the time range narrow. Each tool call is capped at two minutes, and broad `Logs` queries can reach that limit.
{% endhint %}

## Troubleshooting

* **401 Unauthorized**
  * Ensure the API key is valid.
* **403 Forbidden**
  * The key lacks `tenant.insights:read`, or analytics are not enabled for the tenant.
* **429 Too Many Requests**
  * The rate limit was exceeded. Implement retries with exponential backoff, and batch with `summarize` instead of polling loops.
* **Query takes too long**
  * `504` means the query ran too long. Simplify the query or reduce the time window.
  * Avoid unbounded queries on large tables.
* **No rows when rows were expected**
  * Check the retention window of the table, then the casing of table and column names.
* **`400` on an apparently correct query**
  * A column name is wrong, or a parameter lacks a cast.
* **Unfamiliar numbers**
  * Confirm the environment. QA holds test data, not production data.

## FAQ

<details>

<summary><strong>Can I query multiple tenants?</strong></summary>

No. A key queries only its own tenant: the platform adds the tenant filter to every query.

</details>

<details>

<summary><strong>Can I export results to CSV/JSON?</strong></summary>

Not directly via the API. The response is JSON with `columns` and `rows`: convert it locally. The dashboards in the admin console can export CSV.

</details>

<details>

<summary><strong>Can query results contain personal data?</strong></summary>

The available fields depend on tenant configuration and integrations. Treat query results as operational data and apply the organization’s access and retention policies.

</details>

<details>

<summary><strong>Can I set up alerts (thresholds, triggers)?</strong></summary>

Not at the moment.

</details>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.thewalletcrew.io/developers-guides/integration-guides/insights-api.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
