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

# Create a limit policy

POST https://api.respan.ai/api/limit-policies/
Content-Type: application/json

Create a usage cap. The policy takes effect immediately: alert rules notify, and block rules reject gateway requests with `429` once the cap is reached.

Reference: https://respan.ai/docs/apis/limit-policies/create-limit-policy

## Authentication

- `Authorization` header (bearer token, required) — Use your Respan API key for Respan API authentication. Enter only the Respan API key value; clients send Authorization: Bearer \<RESPAN\_API\_KEY>. For /api/responses, provider credentials such as Perplexity, OpenAI, or Azure OpenAI go in Settings -> Providers or respan\_params.credential\_override in the request body, not in this authentication field.

## Request

### Body (application/json)

This endpoint expects a LimitPolicyCreateRequest.

- `name` (string, required)
- `scope_value` (string, required) — Identity to meter. For composites (`compose` length >= 2), a JSON list of values in `compose` order.
- `metric` (enum, required, default: cost) — What the cap counts. `cost` is US dollars, `token_count` is total tokens, `request_count` is calls.
  - Allowed values: `cost`, `request_count`, `token_count`
- `rules` (list of LimitPolicyRule, required)
- `scope` (string, optional) — Display category. Not used for matching.
- `compose` (list of string, optional)
- `algorithm` (enum, optional, default: balance_fixed_window)
  - Allowed values: `balance_fixed_window`
- `period` (string, optional, nullable) — Named bucket, integer-seconds string, or `null` for cumulative.
- `anchor` (enum, optional, default: calendar)
  - Allowed values: `calendar`, `first_event`, `explicit_ts`
- `anchor_at` (datetime, optional, nullable)
- `effective_at` (datetime, optional, nullable)
- `expires_at` (datetime, optional, nullable)
- `priority` (integer, optional, default: 0)
- `is_active` (boolean, optional, default: true)

## Response

### 201

The created policy.

- `id` (string, optional)
- `name` (string, optional) — Human label.
- `scope` (string, optional) — Display category (e.g. `API Key`, `Model`). Not used for matching.
- `scope_value` (string, optional) — Identity to meter. For composites, a JSON list of values in `compose` order.
- `compose` (list of string, optional) — Empty for single-dimension policies. Members: `organization_id`, `api_key_id`, `user_id`, `customer_identifier`, `model`, `endpoint`.
- `metric` (enum, optional, default: cost) — What the cap counts. `cost` is US dollars, `token_count` is total tokens, `request_count` is calls.
  - Allowed values: `cost`, `request_count`, `token_count`
- `algorithm` (enum, optional, default: balance_fixed_window) — `balance_fixed_window` is the shipped algorithm. `token_bucket` is reserved and not yet enforced.
  - Allowed values: `balance_fixed_window`
- `period` (string, optional, nullable) — Cadence. A named bucket (`minute`, `hour`, `day`, `week`, `month`), a positive integer of seconds as a string, or `null` for a cumulative (lifetime) cap that never resets.
- `anchor` (enum, optional, default: calendar) — When a recurring window aligns. `calendar` resets on the boundary (e.g. the 1st of the month).
  - Allowed values: `calendar`, `first_event`, `explicit_ts`
- `anchor_at` (datetime, optional, nullable) — Required when `anchor` is not `calendar`.
- `effective_at` (datetime, optional, nullable) — Active-range start. `null` = live since forever.
- `expires_at` (datetime, optional, nullable) — Active-range end. `null` = live until deactivated. Must be after `effective_at`.
- `priority` (integer, optional, default: 0) — Higher is checked first.
- `is_active` (boolean, optional, default: true)
- `rules` (list of LimitPolicyRule, optional) — Any number of soft rules and at most one effective hard rule.
- `threshold_value` (double, optional) — First hard-rule threshold; falls back to the largest soft threshold.
- `meter_definition_id` (string, optional) — Stable hash of the policy identity. Same identity resolves to the same id across recreations.
- `current_state` (LimitPolicyCurrentState, optional) — Live counter for the current window instance.
- `created_at` (datetime, optional)
- `updated_at` (datetime, optional)

## Errors

### 400 Bad Request Error

Validation failed.

- `map from string to any`

### 403 Forbidden Error

The API key is missing, invalid or expired.

- `detail` (string, required)

## Types

### LimitPolicyRule

- `trigger` (map from string to any, required) — Threshold condition. Common shape: `{"counter": {"operator": "gte", "value": 10000}}`.
- `severity` (enum, required) — `soft` fires an alert without blocking; `hard` blocks the request with 429.
  - Allowed values: `soft`, `hard`
- `description` (string, optional, nullable) — Shown in events and alert payloads.
- `is_active` (boolean, optional, default: true)
- `notification_method_id` (string, optional, nullable) — Optional OrganizationNotificationMethod id to ping when this rule trips.

### LimitPolicyCurrentState

Live counter for the current window instance.

- `meter_id` (string, optional)
- `interval_start` (integer, optional, nullable) — Epoch seconds, inclusive.
- `interval_end` (integer, optional, nullable) — Epoch seconds, exclusive.
- `current_value` (double, optional) — Accumulated value in this window.

## Examples

**Request**

```json
{
  "name": "string",
  "scope_value": "string",
  "metric": "cost",
  "rules": [
    {
      "trigger": {},
      "severity": "soft"
    }
  ]
}
```

**Response**

```json
{
  "id": "string",
  "name": "string",
  "scope": "string",
  "scope_value": "string",
  "compose": [
    "string"
  ],
  "metric": "cost",
  "algorithm": "balance_fixed_window",
  "period": "string",
  "anchor": "calendar",
  "anchor_at": "2024-01-15T09:30:00Z",
  "effective_at": "2024-01-15T09:30:00Z",
  "expires_at": "2024-01-15T09:30:00Z",
  "priority": 0,
  "is_active": true,
  "rules": [
    {
      "trigger": {},
      "severity": "soft",
      "description": "string",
      "is_active": true,
      "notification_method_id": "string"
    }
  ],
  "threshold_value": 1.1,
  "meter_definition_id": "string",
  "current_state": {
    "meter_id": "string",
    "interval_start": 1,
    "interval_end": 1,
    "current_value": 1.1
  },
  "created_at": "2024-01-15T09:30:00Z",
  "updated_at": "2024-01-15T09:30:00Z"
}
```

**SDK Code**

```python
import requests

url = "https://api.respan.ai/api/limit-policies/"

payload = {
    "name": "string",
    "scope_value": "string",
    "metric": "cost",
    "rules": [
        {
            "trigger": {},
            "severity": "soft"
        }
    ]
}
headers = {
    "Authorization": "Bearer <respanApiKey>",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript
const url = 'https://api.respan.ai/api/limit-policies/';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <respanApiKey>', 'Content-Type': 'application/json'},
  body: '{"name":"string","scope_value":"string","metric":"cost","rules":[{"trigger":{},"severity":"soft"}]}'
};

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://api.respan.ai/api/limit-policies/"

	payload := strings.NewReader("{\n  \"name\": \"string\",\n  \"scope_value\": \"string\",\n  \"metric\": \"cost\",\n  \"rules\": [\n    {\n      \"trigger\": {},\n      \"severity\": \"soft\"\n    }\n  ]\n}")

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

	req.Header.Add("Authorization", "Bearer <respanApiKey>")
	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://api.respan.ai/api/limit-policies/")

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

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <respanApiKey>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"name\": \"string\",\n  \"scope_value\": \"string\",\n  \"metric\": \"cost\",\n  \"rules\": [\n    {\n      \"trigger\": {},\n      \"severity\": \"soft\"\n    }\n  ]\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://api.respan.ai/api/limit-policies/")
  .header("Authorization", "Bearer <respanApiKey>")
  .header("Content-Type", "application/json")
  .body("{\n  \"name\": \"string\",\n  \"scope_value\": \"string\",\n  \"metric\": \"cost\",\n  \"rules\": [\n    {\n      \"trigger\": {},\n      \"severity\": \"soft\"\n    }\n  ]\n}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.respan.ai/api/limit-policies/', [
  'body' => '{
  "name": "string",
  "scope_value": "string",
  "metric": "cost",
  "rules": [
    {
      "trigger": {},
      "severity": "soft"
    }
  ]
}',
  'headers' => [
    'Authorization' => 'Bearer <respanApiKey>',
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp
using RestSharp;

var client = new RestClient("https://api.respan.ai/api/limit-policies/");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <respanApiKey>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"name\": \"string\",\n  \"scope_value\": \"string\",\n  \"metric\": \"cost\",\n  \"rules\": [\n    {\n      \"trigger\": {},\n      \"severity\": \"soft\"\n    }\n  ]\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Authorization": "Bearer <respanApiKey>",
  "Content-Type": "application/json"
]
let parameters = [
  "name": "string",
  "scope_value": "string",
  "metric": "cost",
  "rules": [
    [
      "trigger": [],
      "severity": "soft"
    ]
  ]
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://api.respan.ai/api/limit-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()
```