# Update flag settings for context

PUT https://app.launchdarkly.com/api/v2/projects/{projectKey}/environments/{environmentKey}/contexts/{contextKind}/{contextKey}/flags/{featureFlagKey}
Content-Type: application/json


Enable or disable a feature flag for a context based on its context kind and key.

In the request body, the `setting` should be the variation value to set for the context. It must match the flag's variation type. For example, for a boolean flag you can use `"setting": true` or `"setting": false` in the request body. For a string flag, you can use `"setting": "existing_variation_value_to_use"`.

Omitting the `setting` attribute from the request body, or including a `setting` of `null`, erases the current setting for a context.

If you previously patched the flag, and the patch included the context's data, LaunchDarkly continues to use that data. If LaunchDarkly has never encountered the combination of the context's key and kind before, it calculates the flag values based on the context kind and key.


Reference: https://launchdarkly.com/docs/api/context-settings/put-context-flag-setting

## OpenAPI Specification

```yaml
openapi: 3.1.0
info:
  title: LaunchDarkly REST API
  version: 1.0.0
paths:
  /api/v2/projects/{projectKey}/environments/{environmentKey}/contexts/{contextKind}/{contextKey}/flags/{featureFlagKey}:
    put:
      operationId: put-context-flag-setting
      summary: Update flag settings for context
      description: >

        Enable or disable a feature flag for a context based on its context kind
        and key.


        In the request body, the `setting` should be the variation value to set
        for the context. It must match the flag's variation type. For example,
        for a boolean flag you can use `"setting": true` or `"setting": false`
        in the request body. For a string flag, you can use `"setting":
        "existing_variation_value_to_use"`.


        Omitting the `setting` attribute from the request body, or including a
        `setting` of `null`, erases the current setting for a context.


        If you previously patched the flag, and the patch included the context's
        data, LaunchDarkly continues to use that data. If LaunchDarkly has never
        encountered the combination of the context's key and kind before, it
        calculates the flag values based on the context kind and key.
      tags:
        - subpackage_contextSettings
      parameters:
        - name: projectKey
          in: path
          description: The project key
          required: true
          schema:
            type: string
            format: string
        - name: environmentKey
          in: path
          description: The environment key
          required: true
          schema:
            type: string
            format: string
        - name: contextKind
          in: path
          description: The context kind
          required: true
          schema:
            type: string
            format: string
        - name: contextKey
          in: path
          description: The context key
          required: true
          schema:
            type: string
            format: string
        - name: featureFlagKey
          in: path
          description: The feature flag key
          required: true
          schema:
            type: string
            format: string
        - name: Authorization
          in: header
          required: true
          schema:
            type: string
      responses:
        '204':
          description: Action succeeded
          content:
            application/json:
              schema:
                $ref: >-
                  #/components/schemas/Context
                  settings_putContextFlagSetting_Response_204
        '400':
          description: Invalid request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InvalidRequestErrorRep'
        '401':
          description: Invalid access token
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UnauthorizedErrorRep'
        '403':
          description: Forbidden
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ForbiddenErrorRep'
        '404':
          description: Invalid resource identifier
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/NotFoundErrorRep'
        '409':
          description: Status conflict
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/StatusConflictErrorRep'
        '429':
          description: Rate limited
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RateLimitedErrorRep'
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ValuePut'
servers:
  - url: https://app.launchdarkly.com
  - url: https://app.launchdarkly.us
components:
  schemas:
    ValuePut:
      type: object
      properties:
        setting:
          description: >-
            The variation value to set for the context. Must match the flag's
            variation type.
        comment:
          type: string
          description: Optional comment describing the change
      title: ValuePut
    Context settings_putContextFlagSetting_Response_204:
      type: object
      properties: {}
      title: Context settings_putContextFlagSetting_Response_204
    InvalidRequestErrorRep:
      type: object
      properties:
        code:
          type: string
          description: Specific error code encountered
        message:
          type: string
          description: Description of the error
      required:
        - code
        - message
      title: InvalidRequestErrorRep
    UnauthorizedErrorRep:
      type: object
      properties:
        code:
          type: string
          description: Specific error code encountered
        message:
          type: string
          description: Description of the error
      required:
        - code
        - message
      title: UnauthorizedErrorRep
    ForbiddenErrorRep:
      type: object
      properties:
        code:
          type: string
          description: Specific error code encountered
        message:
          type: string
          description: Description of the error
      required:
        - code
        - message
      title: ForbiddenErrorRep
    NotFoundErrorRep:
      type: object
      properties:
        code:
          type: string
          description: Specific error code encountered
        message:
          type: string
          description: Description of the error
      required:
        - code
        - message
      title: NotFoundErrorRep
    StatusConflictErrorRep:
      type: object
      properties:
        code:
          type: string
          description: Specific error code encountered
        message:
          type: string
          description: Description of the error
      required:
        - code
        - message
      title: StatusConflictErrorRep
    RateLimitedErrorRep:
      type: object
      properties:
        code:
          type: string
          description: Specific error code encountered
        message:
          type: string
          description: Description of the error
      required:
        - code
        - message
      title: RateLimitedErrorRep
  securitySchemes:
    ApiKey:
      type: apiKey
      in: header
      name: Authorization

```

## SDK Code Examples

```python
import requests

url = "https://app.launchdarkly.com/api/v2/projects/projectKey/environments/environmentKey/contexts/contextKind/contextKey/flags/featureFlagKey"

payload = {}
headers = {
    "Authorization": "<apiKey>",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript
const url = 'https://app.launchdarkly.com/api/v2/projects/projectKey/environments/environmentKey/contexts/contextKind/contextKey/flags/featureFlagKey';
const options = {
  method: 'PUT',
  headers: {Authorization: '<apiKey>', 'Content-Type': 'application/json'},
  body: '{}'
};

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.launchdarkly.com/api/v2/projects/projectKey/environments/environmentKey/contexts/contextKind/contextKey/flags/featureFlagKey"

	payload := strings.NewReader("{}")

	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.launchdarkly.com/api/v2/projects/projectKey/environments/environmentKey/contexts/contextKind/contextKey/flags/featureFlagKey")

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 = "{}"

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.launchdarkly.com/api/v2/projects/projectKey/environments/environmentKey/contexts/contextKind/contextKey/flags/featureFlagKey")
  .header("Authorization", "<apiKey>")
  .header("Content-Type", "application/json")
  .body("{}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('PUT', 'https://app.launchdarkly.com/api/v2/projects/projectKey/environments/environmentKey/contexts/contextKind/contextKey/flags/featureFlagKey', [
  'body' => '{}',
  'headers' => [
    'Authorization' => '<apiKey>',
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp
using RestSharp;

var client = new RestClient("https://app.launchdarkly.com/api/v2/projects/projectKey/environments/environmentKey/contexts/contextKind/contextKey/flags/featureFlagKey");
var request = new RestRequest(Method.PUT);
request.AddHeader("Authorization", "<apiKey>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Authorization": "<apiKey>",
  "Content-Type": "application/json"
]
let parameters = [] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://app.launchdarkly.com/api/v2/projects/projectKey/environments/environmentKey/contexts/contextKind/contextKey/flags/featureFlagKey")! 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()
```