For clean Markdown of any page, append .md to the page URL. For a complete documentation index, see https://docs.getunleash.io/api/llms.txt. For full documentation content, see https://docs.getunleash.io/api/llms-full.txt.

# [BETA] Change a feature environment safeguard

PUT https://app.unleash-instance.example.com/api/admin/projects/{project}/features/{featureName}/environments/{environment}/safeguards
Content-Type: application/json

**Enterprise feature**

**[BETA]** This API is in beta state, which means it may change or be removed in the future.

Creates or updates a safeguard for a specific feature and environment.

Reference: https://docs.getunleash.io/api/change-feature-env-safeguard

## OpenAPI Specification

```yaml
openapi: 3.1.0
info:
  title: admin-api
  version: 1.0.0
paths:
  /api/admin/projects/{project}/features/{featureName}/environments/{environment}/safeguards:
    put:
      operationId: change-feature-env-safeguard
      summary: '[BETA] Change a feature environment safeguard'
      description: >-
        **Enterprise feature**


        **[BETA]** This API is in beta state, which means it may change or be
        removed in the future.


        Creates or updates a safeguard for a specific feature and environment.
      tags:
        - subpackage_features
      parameters:
        - name: project
          in: path
          required: true
          schema:
            type: string
        - name: featureName
          in: path
          required: true
          schema:
            type: string
        - name: environment
          in: path
          required: true
          schema:
            type: string
        - name: Authorization
          in: header
          description: API key needed to access this API
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Successful response
        '401':
          description: >-
            Authorization information is missing or invalid. Provide a valid API
            token as the `authorization` header, e.g.
            `authorization:*.*.my-admin-token`.
          content:
            application/json:
              schema:
                $ref: >-
                  #/components/schemas/ChangeFeatureEnvSafeguardRequestUnauthorizedError
        '403':
          description: >-
            The provided user credentials are valid, but the user does not have
            the necessary permissions to perform this operation
          content:
            application/json:
              schema:
                $ref: >-
                  #/components/schemas/ChangeFeatureEnvSafeguardRequestForbiddenError
      requestBody:
        description: createSafeguardSchema
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/createSafeguardSchema'
servers:
  - url: https://app.unleash-instance.example.com
components:
  schemas:
    CreateSafeguardSchemaImpactMetricTimeRange:
      type: string
      enum:
        - hour
        - day
        - week
        - month
      description: The time range for the metric data.
      title: CreateSafeguardSchemaImpactMetricTimeRange
    CreateSafeguardSchemaImpactMetricAggregationMode:
      type: string
      enum:
        - rps
        - count
        - avg
        - sum
        - p95
        - p99
        - p50
      description: The aggregation mode for the metric data.
      title: CreateSafeguardSchemaImpactMetricAggregationMode
    CreateSafeguardSchemaImpactMetricSource:
      type: string
      enum:
        - internal
        - external
      description: >-
        The Prometheus data source for this metric. Internal is the
        Unleash-managed Prometheus, external is a customer-provided Prometheus
        instance. Defaults to internal if not specified.
      title: CreateSafeguardSchemaImpactMetricSource
    CreateSafeguardSchemaImpactMetric:
      type: object
      properties:
        metricName:
          type: string
          description: >-
            The Prometheus metric series to query. It includes both unleash
            prefix and metric type and display name
        timeRange:
          $ref: '#/components/schemas/CreateSafeguardSchemaImpactMetricTimeRange'
          description: The time range for the metric data.
        aggregationMode:
          $ref: >-
            #/components/schemas/CreateSafeguardSchemaImpactMetricAggregationMode
          description: The aggregation mode for the metric data.
        labelSelectors:
          type: object
          additionalProperties:
            type: array
            items:
              type: string
          description: The selected labels and their values for filtering the metric data.
        source:
          $ref: '#/components/schemas/CreateSafeguardSchemaImpactMetricSource'
          description: >-
            The Prometheus data source for this metric. Internal is the
            Unleash-managed Prometheus, external is a customer-provided
            Prometheus instance. Defaults to internal if not specified.
      required:
        - metricName
        - timeRange
        - aggregationMode
        - labelSelectors
      description: Metric configuration that should be evaluated for the safeguard.
      title: CreateSafeguardSchemaImpactMetric
    SafeguardTriggerConditionSchemaOperator:
      type: string
      enum:
        - '>'
        - <
      description: The comparison operator for the threshold check.
      title: SafeguardTriggerConditionSchemaOperator
    safeguardTriggerConditionSchema:
      type: object
      properties:
        operator:
          $ref: '#/components/schemas/SafeguardTriggerConditionSchemaOperator'
          description: The comparison operator for the threshold check.
        threshold:
          type: number
          format: double
          description: The threshold value to compare against.
      required:
        - operator
        - threshold
      description: The condition that triggers the safeguard.
      title: safeguardTriggerConditionSchema
    createSafeguardSchema:
      type: object
      properties:
        impactMetric:
          $ref: '#/components/schemas/CreateSafeguardSchemaImpactMetric'
          description: Metric configuration that should be evaluated for the safeguard.
        triggerCondition:
          $ref: '#/components/schemas/safeguardTriggerConditionSchema'
          description: The condition that triggers the safeguard.
      required:
        - impactMetric
        - triggerCondition
      description: Request body to create a safeguard with metric-based alert condition.
      title: createSafeguardSchema
    ChangeFeatureEnvSafeguardRequestUnauthorizedError:
      type: object
      properties:
        id:
          type: string
          description: The ID of the error instance
        name:
          type: string
          description: The name of the error kind
        message:
          type: string
          description: A description of what went wrong.
      title: ChangeFeatureEnvSafeguardRequestUnauthorizedError
    ChangeFeatureEnvSafeguardRequestForbiddenError:
      type: object
      properties:
        id:
          type: string
          description: The ID of the error instance
        name:
          type: string
          description: The name of the error kind
        message:
          type: string
          description: A description of what went wrong.
      title: ChangeFeatureEnvSafeguardRequestForbiddenError
  securitySchemes:
    apiKey:
      type: apiKey
      in: header
      name: Authorization
      description: API key needed to access this API
    bearerToken:
      type: http
      scheme: bearer
      description: API key needed to access this API, in Bearer token format

```

## SDK Code Examples

```python
import requests

url = "https://app.unleash-instance.example.com/api/admin/projects/project/features/featureName/environments/environment/safeguards"

payload = {
    "impactMetric": {
        "metricName": "unleash_counter_feature_toggle_usage_total",
        "timeRange": "day",
        "aggregationMode": "rps",
        "labelSelectors": {
            "environment": ["development"],
            "project": ["default"]
        }
    },
    "triggerCondition": {
        "operator": ">",
        "threshold": 100
    }
}
headers = {
    "Authorization": "<apiKey>",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript
const url = 'https://app.unleash-instance.example.com/api/admin/projects/project/features/featureName/environments/environment/safeguards';
const options = {
  method: 'PUT',
  headers: {Authorization: '<apiKey>', 'Content-Type': 'application/json'},
  body: '{"impactMetric":{"metricName":"unleash_counter_feature_toggle_usage_total","timeRange":"day","aggregationMode":"rps","labelSelectors":{"environment":["development"],"project":["default"]}},"triggerCondition":{"operator":">","threshold":100}}'
};

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://app.unleash-instance.example.com/api/admin/projects/project/features/featureName/environments/environment/safeguards"

	payload := strings.NewReader("{\n  \"impactMetric\": {\n    \"metricName\": \"unleash_counter_feature_toggle_usage_total\",\n    \"timeRange\": \"day\",\n    \"aggregationMode\": \"rps\",\n    \"labelSelectors\": {\n      \"environment\": [\n        \"development\"\n      ],\n      \"project\": [\n        \"default\"\n      ]\n    }\n  },\n  \"triggerCondition\": {\n    \"operator\": \">\",\n    \"threshold\": 100\n  }\n}")

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

	req.Header.Add("Authorization", "<apiKey>")
	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://app.unleash-instance.example.com/api/admin/projects/project/features/featureName/environments/environment/safeguards")

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

request = Net::HTTP::Put.new(url)
request["Authorization"] = '<apiKey>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"impactMetric\": {\n    \"metricName\": \"unleash_counter_feature_toggle_usage_total\",\n    \"timeRange\": \"day\",\n    \"aggregationMode\": \"rps\",\n    \"labelSelectors\": {\n      \"environment\": [\n        \"development\"\n      ],\n      \"project\": [\n        \"default\"\n      ]\n    }\n  },\n  \"triggerCondition\": {\n    \"operator\": \">\",\n    \"threshold\": 100\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.put("https://app.unleash-instance.example.com/api/admin/projects/project/features/featureName/environments/environment/safeguards")
  .header("Authorization", "<apiKey>")
  .header("Content-Type", "application/json")
  .body("{\n  \"impactMetric\": {\n    \"metricName\": \"unleash_counter_feature_toggle_usage_total\",\n    \"timeRange\": \"day\",\n    \"aggregationMode\": \"rps\",\n    \"labelSelectors\": {\n      \"environment\": [\n        \"development\"\n      ],\n      \"project\": [\n        \"default\"\n      ]\n    }\n  },\n  \"triggerCondition\": {\n    \"operator\": \">\",\n    \"threshold\": 100\n  }\n}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('PUT', 'https://app.unleash-instance.example.com/api/admin/projects/project/features/featureName/environments/environment/safeguards', [
  'body' => '{
  "impactMetric": {
    "metricName": "unleash_counter_feature_toggle_usage_total",
    "timeRange": "day",
    "aggregationMode": "rps",
    "labelSelectors": {
      "environment": [
        "development"
      ],
      "project": [
        "default"
      ]
    }
  },
  "triggerCondition": {
    "operator": ">",
    "threshold": 100
  }
}',
  'headers' => [
    'Authorization' => '<apiKey>',
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp
using RestSharp;

var client = new RestClient("https://app.unleash-instance.example.com/api/admin/projects/project/features/featureName/environments/environment/safeguards");
var request = new RestRequest(Method.PUT);
request.AddHeader("Authorization", "<apiKey>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"impactMetric\": {\n    \"metricName\": \"unleash_counter_feature_toggle_usage_total\",\n    \"timeRange\": \"day\",\n    \"aggregationMode\": \"rps\",\n    \"labelSelectors\": {\n      \"environment\": [\n        \"development\"\n      ],\n      \"project\": [\n        \"default\"\n      ]\n    }\n  },\n  \"triggerCondition\": {\n    \"operator\": \">\",\n    \"threshold\": 100\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Authorization": "<apiKey>",
  "Content-Type": "application/json"
]
let parameters = [
  "impactMetric": [
    "metricName": "unleash_counter_feature_toggle_usage_total",
    "timeRange": "day",
    "aggregationMode": "rps",
    "labelSelectors": [
      "environment": ["development"],
      "project": ["default"]
    ]
  ],
  "triggerCondition": [
    "operator": ">",
    "threshold": 100
  ]
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://app.unleash-instance.example.com/api/admin/projects/project/features/featureName/environments/environment/safeguards")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "PUT"
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()
```