> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.lakera.ai/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.lakera.ai/_mcp/server.

# Create policy

POST https://platform.lakera.ai/api/v1/policies
Content-Type: application/json

Create a new policy configuration

Reference: https://docs.lakera.ai/api-reference/platform-api/policies/create-policy

## Authentication

- `Authorization` header (bearer token, required) — Bearer authentication using API key. Generate an API key from the AI Guardrails Dashboard. Example: Bearer sk_123... Keys carry one of two access scopes, chosen when the key is created: - **Read and write** — may call every endpoint. This is the default, and the scope of every key created before scopes were introduced. - **Read only** — may call read endpoints such as `/v1-beta/logs`, `/v1-beta/analytics` and the `GET` endpoints. Write endpoints return `403`. Issue a read-only key to anything that only needs to retrieve data, such as a log-shipping job or a dashboard, so that it cannot modify your policies or projects.

## Request

### Body (application/json)

This endpoint expects a PolicyRequest.

- `name` (string, required) — A descriptive name for the policy. Leading and trailing whitespace is stripped. Must be unique within your organization.
- `default_threshold` (enum, required) — The confidence level at or above which the policy's detectors flag content. `l1_confident` is the most lenient and `l4_less_likely` the strictest. Thresholds are inclusive — `l2_very_likely` flags on both `l2_very_likely` and `l1_confident` detections.
  - Allowed values: `l1_confident`, `l2_very_likely`, `l3_likely`, `l4_less_likely`
- `detectors` (list of DetectorConfig, optional) — The detectors to run. Each entry pairs a detector `type` with the `location` in the conversation it screens.
- `custom_guardrail_ids` (list of string, optional) — IDs of the custom guardrails to attach to this policy.

## Response

### 200

Policy created successfully

- `status` (enum, optional) — Response status
  - Allowed values: `ok`
- `message` (string, optional) — Human-readable response message
- `id` (string, optional) — Policy ID

## Errors

### 400 Bad Request Error

The request could not be processed. Returned when a policy with the same name already exists in your organization.

- `status` (enum, optional) — Response status
  - Allowed values: `error`
- `error` (string, optional) — Short machine-readable error identifier
- `message` (string, optional) — Human-readable error message
- `code` (integer, optional) — HTTP status code
- `request_id` (string, optional) — Unique identifier for the request

### 403 Forbidden Error

Your API key is read-only and this endpoint writes, Policies V2 is not enabled for your organization, or your organization has reached its maximum number of policies.

- `status` (enum, optional) — Response status
  - Allowed values: `error`
- `error` (string, optional) — Short machine-readable error identifier
- `message` (string, optional) — Human-readable error message
- `code` (integer, optional) — HTTP status code
- `request_id` (string, optional) — Unique identifier for the request

### 422 Unprocessable Entity Error

The policy failed validation

- `status` (enum, optional) — Response status
  - Allowed values: `error`
- `error` (string, optional) — Short machine-readable error identifier
- `message` (string, optional) — Human-readable error message
- `code` (integer, optional) — HTTP status code
- `request_id` (string, optional) — Unique identifier for the request

## Types

### DetectorConfig

A single detector, screening one location. To run the same detector on more than one location, add one entry per location.

- `type` (enum, required) — The detector type
  - Allowed values: `prompt_attack`, `moderated_content/hate`, `moderated_content/sexual`, `moderated_content/profanity`, `moderated_content/violence`, `moderated_content/weapons`, `moderated_content/crime`, `moderated_content/self_harm`, `pii/address`, `pii/credit_card`, `pii/email`, `pii/ip_address`, `pii/name`, `pii/phone_number`, `pii/us_social_security_number`, `pii/iban_code`, `unknown_links`, `override_allow`, `override_deny`, `tool_risk/payload`, `tool_risk/create`, `tool_risk/read`, `tool_risk/update`, `tool_risk/delete`, `tool_risk/untrusted_destination`, `tool_risk/untrusted_source`, `dangerous_deviation`, `tool_access_control`
- `location` (enum, required) — Where in the conversation a detector screens. - `user::content` — content of user messages (model input). - `assistant::content` — content of model responses (model output). - `assistant::tool_call` — the arguments an agent passes into a tool. - `tool::content` — the content a tool returns to the agent. - `tool_definition::content` — the tool definitions you expose to the model. Only valid for the `prompt_attack` detector.
  - Allowed values: `user::content`, `assistant::content`, `assistant::tool_call`, `tool::content`, `tool_definition::content`
- `allowed_domains` (list of string, optional, nullable) — A list of trusted domains that should not be flagged by the `unknown_links` detector. Only applicable when `type` is `unknown_links`. Include only the domain name and top-level domain (e.g. "example.com"). Do not include prefixes like "http://" or "www.", or subdomains like "platform.example.com".
- `override_list` (list of string, optional, nullable) — A list of strings to allow or deny, used to override model flagging decisions. Required when `type` is `override_allow` or `override_deny`, and not applicable to other types. `override_allow` prevents matching content from being flagged; `override_deny` forces matching content to be flagged.
- `tool_access_action` (enum, optional, nullable) — Whether `tool_access_list` is an allow list or a deny list. Required when `type` is `tool_access_control`, and not applicable to other types.
  - Allowed values: `allow`, `deny`
- `tool_access_list` (list of string, optional, nullable) — The tool names to allow or deny, per `tool_access_action`. Required when `type` is `tool_access_control`, and not applicable to other types.
- `allowed_tools` (list of DetectorConfigAllowedToolsItems, optional, nullable) — Tool definitions that the `prompt_attack` detector should not flag when screening `tool_definition::content`. Only applicable when `type` is `prompt_attack`. Each entry must be unique on (`tool_name`, `tool_matcher`).

### DetectorConfigAllowedToolsItems

- `tool_name` (string, required) — The name of the tool.
- `tool_matcher` (string, required) — The tool definition this entry allows. An entry matches only when both the name and the definition match.

## Examples

**Request**

```json
{
  "name": "RAG chatbot policy",
  "default_threshold": "l1_confident"
}
```

**Response**

```json
{
  "status": "ok",
  "message": "policy created",
  "id": "policy-123456-random-g74j7"
}
```

**SDK Code**

```python
import requests

url = "https://platform.lakera.ai/api/v1/policies"

payload = {
    "name": "RAG chatbot policy",
    "default_threshold": "l1_confident"
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript
const url = 'https://platform.lakera.ai/api/v1/policies';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"name":"RAG chatbot policy","default_threshold":"l1_confident"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://platform.lakera.ai/api/v1/policies"

	payload := strings.NewReader("{\n  \"name\": \"RAG chatbot policy\",\n  \"default_threshold\": \"l1_confident\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://platform.lakera.ai/api/v1/policies")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"name\": \"RAG chatbot policy\",\n  \"default_threshold\": \"l1_confident\"\n}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://platform.lakera.ai/api/v1/policies")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"name\": \"RAG chatbot policy\",\n  \"default_threshold\": \"l1_confident\"\n}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://platform.lakera.ai/api/v1/policies', [
  'body' => '{
  "name": "RAG chatbot policy",
  "default_threshold": "l1_confident"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://platform.lakera.ai/api/v1/policies");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"name\": \"RAG chatbot policy\",\n  \"default_threshold\": \"l1_confident\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "name": "RAG chatbot policy",
  "default_threshold": "l1_confident"
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://platform.lakera.ai/api/v1/policies")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```