# get\_\_v2\_stats\_policies

`GET /v2/stats/policies`

*Get Policy Stats*

Time-series of policy enforcement + token overhead. Supports resource-level filter: `ruleId`.

#### Parameters <a href="#get__v2_stats_policies-parameters" id="get__v2_stats_policies-parameters"></a>

| Name           | In    | Type   | Required | Description                                    |
| -------------- | ----- | ------ | -------- | ---------------------------------------------- |
| scope          | query | string | true     | Scope level: `org`, `workspace`, or `repo`     |
| id             | query | string | false    | Required when `scope` is `workspace` or `repo` |
| window         | query | string | true     | Time window, e.g. `24h`, `7d`, `30d`           |
| timeBucketSize | query | string | false    | Time grouping size, e.g., `1h`, `1d`           |
| ruleId         | query | string | false    | Filter by Policy Rule ID                       |
| apiKeyId       | query | string | false    | Filter by Repo API Key ID                      |

#### TypeScript Client Library

```typescript
// Using the Flashback TypeScript client
import { FlashbackClient } from '@flashbacktech/flashbackclient';

const client = new FlashbackClient({
  accessToken: 'your-access-token'
});

try {
  const result = await client.getPolicyStats({
    scope: 'org',
    id: 'org-id',
    window: '24h'});
  console.log('Get Policy Stats:', result);
} catch (error) {
  console.error('Failed to retrieve get policy stats:', error);
}
```

#### Code Samples

{% tabs %}
{% tab title="Shell" %}

```shell
# You can also use wget
curl -X GET "https://backend.flashback.tech/v2/stats/policies?scope=org&id=org-id&window=24h" \
  -H 'Accept: application/json' \
  -H 'Authorization: Bearer {access-token}'
```

{% endtab %}

{% tab title="HTTP" %}

```http
GET /v2/stats/policies?scope=org&id=org-id&window=24h HTTP/1.1
Host: backend.flashback.tech
Accept: application/json
Authorization: Bearer {access-token}
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const headers = {
  'Accept':'application/json',
  'Authorization':'Bearer {access-token}'
};

const queryParams = new URLSearchParams({
  scope: 'org',
  id: 'org-id',
  window: '24h'
});

fetch(`https://backend.flashback.tech/v2/stats/policies?${queryParams.toString()}`,
{
  method: 'GET',
  headers: headers
})
.then(function(res) {
    return res.json();
})
.then(function(body) {
    console.log(body);
});
```

{% endtab %}

{% tab title="Ruby" %}

```ruby
require 'rest-client'
require 'json'

headers = {
  'Accept' => 'application/json',
  'Authorization' => 'Bearer {access-token}'
}

result = RestClient.get 'https://backend.flashback.tech/v2/stats/policies',
  params: {
    scope: 'org',
    id: 'org-id',
    window: '24h'
  }, headers: headers

p JSON.parse(result)
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
headers = {
  'Accept': 'application/json',
  'Authorization': 'Bearer {access-token}'
}

params = {
  'scope': 'org',
  'id': 'org-id',
  'window': '24h'
}

r = requests.get('https://backend.flashback.tech/v2/stats/policies', headers=headers, params=params)

print(r.json())
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php

require 'vendor/autoload.php';

$headers = array(
    'Accept' => 'application/json',
    'Authorization' => 'Bearer {access-token}',
);

$client = new \GuzzleHttp\Client();

$queryParams = array(
    'scope' => 'org',
    'id' => 'org-id',
    'window' => '24h'
);

try {
    $response = $client->request('GET','https://backend.flashback.tech/v2/stats/policies', array(
        'headers' => $headers,
        'query' => $queryParams,
       )
    );
    print_r($response->getBody()->getContents());
 }
 catch (\GuzzleHttp\Exception\BadResponseException $e) {
    // handle exception or api errors.
    print_r($e->getMessage());
 }
```

{% endtab %}

{% tab title="Java" %}

```java
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;

String baseUrl = "https://backend.flashback.tech/v2/stats/policies";
String queryString = "scope=org&id=org-id&window=24h";
URL obj = new URL(baseUrl + "?" + queryString);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Authorization", "Bearer {access-token}");
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
    new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();
System.out.println(response.toString());
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
       "net/http"
       "net/url"
)

func main() {

    headers := map[string][]string{
        "Accept": []string{"application/json"},
        "Authorization": []string{"Bearer {access-token}"},
    }

    params := url.Values{}
    params.Add("scope", "org")
    params.Add("id", "org-id")
    params.Add("window", "24h")

    req, err := http.NewRequest("GET", "https://backend.flashback.tech/v2/stats/policies?" + params.Encode(), nil)
    req.Header = headers

    client := &http.Client{}
    resp, err := client.Do(req)
    // ...
}
```

{% endtab %}
{% endtabs %}

> Example responses 200 Response

```json
{
  "success": true,
  "meta": {
    "start": 1704067200,
    "end": 1704153600,
    "scope": "org",
    "window": "24h",
    "timeBucketSize": "1h"
  },
  "summary": {
    "total": 1500,
    "avg": 50,
    "stdDev": 10,
    "min": 0,
    "max": 100,
    "p10": 10,
    "p50": 50,
    "p90": 90
  },
  "series": [
    {
      "ts": 1704067200
      // domain specific metrics
    }
  ]
}
```

#### Responses <a href="#get__v2_stats_policies-responses" id="get__v2_stats_policies-responses"></a>

| Status | Meaning                                                                    | Description                | Schema |
| ------ | -------------------------------------------------------------------------- | -------------------------- | ------ |
| 200    | [OK](https://tools.ietf.org/html/rfc7231#section-6.3.1)                    | Successful request         | Inline |
| 400    | [Bad Request](https://tools.ietf.org/html/rfc7231#section-6.5.1)           | Invalid request parameters | Inline |
| 500    | [Internal Server Error](https://tools.ietf.org/html/rfc7231#section-6.6.1) | Internal server error      | Inline |

#### Response Schema <a href="#get__v2_stats_policies-responseschema" id="get__v2_stats_policies-responseschema"></a>

Status Code **200**

| Name               | Type      | Required | Restrictions | Description                             |
| ------------------ | --------- | -------- | ------------ | --------------------------------------- |
| » success          | boolean   | true     | none         | Indicates if the request was successful |
| » meta             | object    | true     | none         | Metadata for the response               |
| » summary          | object    | true     | none         | Statistical summary                     |
| » series           | \[object] | true     | none         | Array of time-series points             |
| »» ts              | integer   | true     | none         | Unix timestamp                          |
| »» violations      | integer   | true     | none         | Total policy violations                 |
| »» alerts          | integer   | true     | none         | Total alerts triggered                  |
| »» blocks          | integer   | true     | none         | Total blocked requests                  |
| »» severityLow     | integer   | true     | none         | Low severity violations                 |
| »» severityMedium  | integer   | true     | none         | Medium severity violations              |
| »» severityHigh    | integer   | true     | none         | High severity violations                |
| »» policyTokensIn  | integer   | true     | none         | Policy input tokens                     |
| »» policyTokensOut | integer   | true     | none         | Policy output tokens                    |

Status Code **400**

| Name      | Type    | Required | Restrictions | Description                      |
| --------- | ------- | -------- | ------------ | -------------------------------- |
| » success | boolean | true     | none         | Always false for error responses |
| » message | string  | true     | none         | Error message                    |

Status Code **500**

| Name      | Type    | Required | Restrictions | Description                      |
| --------- | ------- | -------- | ------------ | -------------------------------- |
| » success | boolean | true     | none         | Always false for error responses |
| » message | string  | true     | none         | Error message                    |
