# get\_\_policy\_{policyId}\_violations

{% hint style="info" %}
This API endpoint is currently available only in the TEST environment. It is not yet available in production.
{% endhint %}

`GET /policy/{policyId}/violations`

*Get Policy Violations by Policy ID*

Retrieve all violations for a specific policy. This endpoint is a convenience method that filters violations by policy ID, making it easier to analyze violations for a particular policy.

**Key Features:**

* Automatically filters violations by the specified policy ID
* Same filtering and pagination options as the general violations endpoint
* Workspace and repository filtering still available
* Date range filtering supported
* Returns detailed violation information

**Query Filtering:**

* `workspaceId` - Filter violations by workspace (optional)
* `repoId` - Filter violations by repository (optional)
* `from` - Start date for date range (ISO 8601 format, optional)
* `to` - End date for date range (ISO 8601 format, optional)
* `skip` - Number of records to skip (for pagination, default: 0)
* `take` - Number of records to return (default: 50, max: 100)

**Important Notes:**

* The `policyId` is provided in the URL path, not as a query parameter
* Only returns violations for the specified policy
* User must have access to the policy to view its violations
* Violations are sorted by timestamp in descending order (newest first)
* Maximum `take` value is 100

**Use Cases:**

* Analyze violations for a specific policy
* Monitor effectiveness of a particular policy
* Generate compliance reports for individual policies
* Track violation trends for a specific policy over time

#### TypeScript Client Library

```typescript
public getPolicyViolationsByPolicyId = async (
  policyId: string,
  query: Omit<GetPolicyViolationsQuery, 'policyId'>
): Promise<GetPolicyViolationsResponse> => {
  const queryParams = new URLSearchParams();
  if (query.workspaceId) {
    queryParams.append('workspaceId', query.workspaceId);
  }
  if (query.repoId) {
    queryParams.append('repoId', query.repoId);
  }
  if (query.from) {
    queryParams.append('from', query.from);
  }
  if (query.to) {
    queryParams.append('to', query.to);
  }
  if (query.take !== undefined) {
    queryParams.append('take', query.take.toString());
  }
  if (query.skip !== undefined) {
    queryParams.append('skip', query.skip.toString());
  }
  return this.makeRequest<GetPolicyViolationsResponse>(
    `policy/${policyId}/violations${queryParams.toString() ? `?${queryParams.toString()}` : ''}`,
    'GET',
    null
  );
};
```

#### Code Samples

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

```shell
# You can also use wget
curl -X GET "https://backend.flashback.tech/policy/{policyId}/violations?from=2024-01-01&to=2024-01-31&take=50" \
  -H 'Accept: application/json' \
  -H 'Authorization: Bearer {access-token}'
```

{% endtab %}

{% tab title="HTTP" %}

```http
GET https://backend.flashback.tech/policy/{policyId}/violations?from=2024-01-01&to=2024-01-31 HTTP/1.1
Host: backend.flashback.tech
Accept: application/json
```

{% endtab %}

{% tab title="JavaScript" %}

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

fetch('https://backend.flashback.tech/policy/{policyId}/violations?from=2024-01-01&to=2024-01-31',
{
  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/policy/{policyId}/violations',
  params: {
  'workspaceId' => 'string',
  'repoId' => 'string',
  'from' => 'string',
  'to' => 'string',
  'take' => 'integer',
  'skip' => 'integer'
}, headers: headers

p JSON.parse(result)
```

{% endtab %}

{% tab title="Python" %}

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

r = requests.get('https://backend.flashback.tech/policy/{policyId}/violations', params={
  'from': '2024-01-01',
  'to': '2024-01-31',
  'take': 50,
  'skip': 0
}, headers = headers)

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();

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

 // ...
```

{% endtab %}

{% tab title="Java" %}

```java
URL obj = new URL("https://backend.flashback.tech/policy/{policyId}/violations?from=2024-01-01&to=2024-01-31");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
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 (
       "bytes"
       "net/http"
)

func main() {

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

    data := bytes.NewBuffer([]byte{jsonReq})
    req, err := http.NewRequest("GET", "https://backend.flashback.tech/policy/{policyId}/violations", data)
    req.Header = headers

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

{% endtab %}
{% endtabs %}

#### Parameters <a href="#get__policy_-policyid-_violations-parameters" id="get__policy_-policyid-_violations-parameters"></a>

| Name        | In    | Type    | Required | Description                                         |
| ----------- | ----- | ------- | -------- | --------------------------------------------------- |
| policyId    | path  | string  | true     | Unique identifier of the policy                     |
| workspaceId | query | string  | false    | Filter violations by workspace ID                   |
| repoId      | query | string  | false    | Filter violations by repository ID                  |
| from        | query | string  | false    | Start date for date range filter (ISO 8601)         |
| to          | query | string  | false    | End date for date range filter (ISO 8601)           |
| take        | query | integer | false    | Number of records to return (default: 50, max: 100) |
| skip        | query | integer | false    | Number of records to skip (default: 0)              |

> Example responses

> 200 Response

```json
{
  "success": true,
  "violations": [
    {
      "id": "violation-123",
      "policyId": "policy-456",
      "policyName": "PII Protection Policy",
      "timestamp": "2024-01-15T10:30:00.000Z",
      "explanation": "Attempted to share credit card number in AI conversation",
      "conversationId": "conv-789",
      "repoId": "repo-101",
      "repoName": "Customer Support Repo",
      "userId": "user-202",
      "userName": "John Doe",
      "repoAiApiKeyId": "apikey-303",
      "repoAiApiKeyName": "Production OpenAI Key"
    },
    {
      "id": "violation-124",
      "policyId": "policy-456",
      "policyName": "PII Protection Policy",
      "timestamp": "2024-01-14T14:20:00.000Z",
      "explanation": "Attempted to share social security number in AI conversation",
      "conversationId": null,
      "repoId": "repo-101",
      "repoName": "Customer Support Repo",
      "userId": "user-203",
      "userName": "Jane Smith",
      "repoAiApiKeyId": "apikey-303",
      "repoAiApiKeyName": "Production OpenAI Key"
    }
  ],
  "total": 2,
  "skip": 0,
  "take": 50
}
```

#### Responses <a href="#get__policy_-policyid-_violations-responses" id="get__policy_-policyid-_violations-responses"></a>

| Status | Meaning                                                                    | Description                       | Schema |
| ------ | -------------------------------------------------------------------------- | --------------------------------- | ------ |
| 200    | [OK](https://tools.ietf.org/html/rfc7231#section-6.3.1)                    | Successfully retrieved violations | Inline |
| 400    | [Bad Request](https://tools.ietf.org/html/rfc7231#section-6.5.1)           | Invalid request parameters        | Inline |
| 404    | [Not Found](https://tools.ietf.org/html/rfc7231#section-6.5.4)             | Policy not found                  | Inline |
| 500    | [Internal Server Error](https://tools.ietf.org/html/rfc7231#section-6.6.1) | Failed to retrieve violations     | Inline |

#### Response Schema <a href="#get__policy_-policyid-_violations-responseschema" id="get__policy_-policyid-_violations-responseschema"></a>

Status Code **200**

| Name                | Type      | Required | Restrictions | Description                                                       |
| ------------------- | --------- | -------- | ------------ | ----------------------------------------------------------------- |
| » success           | boolean   | false    | none         | Operation success status                                          |
| » violations        | \[object] | false    | none         | Array of policy violation objects                                 |
| »» id               | string    | false    | none         | Unique identifier for the violation                               |
| »» policyId         | string    | false    | none         | Policy ID that was violated                                       |
| »» policyName       | string    | false    | none         | Name of the policy that was violated                              |
| »» timestamp        | string    | false    | none         | ISO 8601 timestamp when violation occurred                        |
| »» explanation      | string    | false    | none         | Detailed explanation of the violation                             |
| »» conversationId   | string    | false    | none         | Conversation ID where violation occurred (null if not applicable) |
| »» repoId           | string    | false    | none         | Repository ID where violation occurred                            |
| »» repoName         | string    | false    | none         | Repository name where violation occurred                          |
| »» userId           | string    | false    | none         | User ID who triggered the violation                               |
| »» userName         | string    | false    | none         | Full name of the user who triggered the violation                 |
| »» repoAiApiKeyId   | string    | false    | none         | API key ID used in the operation                                  |
| »» repoAiApiKeyName | string    | false    | none         | API key name used in the operation                                |
| » total             | integer   | false    | none         | Total number of violations matching the query (for pagination)    |
| » skip              | integer   | false    | none         | Number of records skipped                                         |
| » take              | integer   | false    | none         | Number of records returned                                        |

Status Code **400**

| Name         | Type    | Required | Restrictions | Description   |
| ------------ | ------- | -------- | ------------ | ------------- |
| » success    | boolean | false    | none         | none          |
| » violations | array   | false    | none         | none          |
| » total      | integer | false    | none         | none          |
| » skip       | integer | false    | none         | none          |
| » take       | integer | false    | none         | none          |
| » message    | string  | false    | none         | Error message |

Status Code **404**

| Name         | Type    | Required | Restrictions | Description   |
| ------------ | ------- | -------- | ------------ | ------------- |
| » success    | boolean | false    | none         | none          |
| » violations | array   | false    | none         | none          |
| » total      | integer | false    | none         | none          |
| » skip       | integer | false    | none         | none          |
| » take       | integer | false    | none         | none          |
| » message    | string  | false    | none         | Error message |

Status Code **500**

| Name         | Type    | Required | Restrictions | Description   |
| ------------ | ------- | -------- | ------------ | ------------- |
| » success    | boolean | false    | none         | none          |
| » violations | array   | false    | none         | none          |
| » total      | integer | false    | none         | none          |
| » skip       | integer | false    | none         | none          |
| » take       | integer | false    | none         | none          |
| » message    | string  | false    | none         | Error message |

To perform this operation, you must be authenticated by means of one of the following methods: BearerAuth


---

# Agent Instructions: Querying This Documentation

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

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.flashback.tech/support-reference/platform-api-reference/ai-apis/ai-policy/get__policy_-policyid-_violations.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
