# Update expiring context targets on feature flag

PATCH https://app.launchdarkly.com/api/v2/flags/{projectKey}/{featureFlagKey}/expiring-targets/{environmentKey}
Content-Type: application/json

Schedule a context for removal from individual targeting on a feature flag. The flag must already individually target the context.

You can add, update, or remove a scheduled removal date. You can only schedule a context for removal on a single variation per flag.

Updating an expiring target uses the semantic patch format. To make a semantic patch request, you must append `domain-model=launchdarkly.semanticpatch` to your `Content-Type` header. To learn more, read [Updates using semantic patch](https://launchdarkly.com/docs/api#updates-using-semantic-patch).

### Instructions

Semantic patch requests support the following `kind` instructions for updating expiring targets.

<details>
<summary>Click to expand instructions for <strong>updating expiring targets</strong></summary>

#### addExpiringTarget

Adds a date and time that LaunchDarkly will remove the context from the flag's individual targeting.

##### Parameters

* `value`: The time, in Unix milliseconds, when LaunchDarkly should remove the context from individual targeting for this flag
* `variationId`: ID of a variation on the flag
* `contextKey`: The context key for the context to remove from individual targeting
* `contextKind`: The kind of context represented by the `contextKey`

Here's an example:

```json
{
  "instructions": [{
    "kind": "addExpiringTarget",
    "value": 1754006460000,
    "variationId": "4254742c-71ae-411f-a992-43b18a51afe0",
    "contextKey": "user-key-123abc",
    "contextKind": "user"
  }]
}
```

#### updateExpiringTarget

Updates the date and time that LaunchDarkly will remove the context from the flag's individual targeting

##### Parameters

* `value`: The time, in Unix milliseconds, when LaunchDarkly should remove the context from individual targeting for this flag
* `variationId`: ID of a variation on the flag
* `contextKey`: The context key for the context to remove from individual targeting
* `contextKind`: The kind of context represented by the `contextKey`
* `version`: (Optional) The version of the expiring target to update. If included, update will fail if version doesn't match current version of the expiring target.

Here's an example:

```json
{
  "instructions": [{
    "kind": "updateExpiringTarget",
    "value": 1754006460000,
    "variationId": "4254742c-71ae-411f-a992-43b18a51afe0",
    "contextKey": "user-key-123abc",
    "contextKind": "user"
  }]
}
```

#### removeExpiringTarget

Removes the scheduled removal of the context from the flag's individual targeting. The context will remain part of the flag's individual targeting until you explicitly remove it, or until you schedule another removal.

##### Parameters

* `variationId`: ID of a variation on the flag
* `contextKey`: The context key for the context to remove from individual targeting
* `contextKind`: The kind of context represented by the `contextKey`

Here's an example:

```json
{
  "instructions": [{
    "kind": "removeExpiringTarget",
    "variationId": "4254742c-71ae-411f-a992-43b18a51afe0",
    "contextKey": "user-key-123abc",
    "contextKind": "user"
  }]
}
```

</details>


Reference: https://launchdarkly.com/docs/api/feature-flags/patch-expiring-targets

## OpenAPI Specification

```yaml
openapi: 3.1.0
info:
  title: LaunchDarkly REST API
  version: 1.0.0
paths:
  /api/v2/flags/{projectKey}/{featureFlagKey}/expiring-targets/{environmentKey}:
    patch:
      operationId: patch-expiring-targets
      summary: Update expiring context targets on feature flag
      description: >
        Schedule a context for removal from individual targeting on a feature
        flag. The flag must already individually target the context.


        You can add, update, or remove a scheduled removal date. You can only
        schedule a context for removal on a single variation per flag.


        Updating an expiring target uses the semantic patch format. To make a
        semantic patch request, you must append
        `domain-model=launchdarkly.semanticpatch` to your `Content-Type` header.
        To learn more, read [Updates using semantic
        patch](https://launchdarkly.com/docs/api#updates-using-semantic-patch).


        ### Instructions


        Semantic patch requests support the following `kind` instructions for
        updating expiring targets.


        <details>

        <summary>Click to expand instructions for <strong>updating expiring
        targets</strong></summary>


        #### addExpiringTarget


        Adds a date and time that LaunchDarkly will remove the context from the
        flag's individual targeting.


        ##### Parameters


        * `value`: The time, in Unix milliseconds, when LaunchDarkly should
        remove the context from individual targeting for this flag

        * `variationId`: ID of a variation on the flag

        * `contextKey`: The context key for the context to remove from
        individual targeting

        * `contextKind`: The kind of context represented by the `contextKey`


        Here's an example:


        ```json

        {
          "instructions": [{
            "kind": "addExpiringTarget",
            "value": 1754006460000,
            "variationId": "4254742c-71ae-411f-a992-43b18a51afe0",
            "contextKey": "user-key-123abc",
            "contextKind": "user"
          }]
        }

        ```


        #### updateExpiringTarget


        Updates the date and time that LaunchDarkly will remove the context from
        the flag's individual targeting


        ##### Parameters


        * `value`: The time, in Unix milliseconds, when LaunchDarkly should
        remove the context from individual targeting for this flag

        * `variationId`: ID of a variation on the flag

        * `contextKey`: The context key for the context to remove from
        individual targeting

        * `contextKind`: The kind of context represented by the `contextKey`

        * `version`: (Optional) The version of the expiring target to update. If
        included, update will fail if version doesn't match current version of
        the expiring target.


        Here's an example:


        ```json

        {
          "instructions": [{
            "kind": "updateExpiringTarget",
            "value": 1754006460000,
            "variationId": "4254742c-71ae-411f-a992-43b18a51afe0",
            "contextKey": "user-key-123abc",
            "contextKind": "user"
          }]
        }

        ```


        #### removeExpiringTarget


        Removes the scheduled removal of the context from the flag's individual
        targeting. The context will remain part of the flag's individual
        targeting until you explicitly remove it, or until you schedule another
        removal.


        ##### Parameters


        * `variationId`: ID of a variation on the flag

        * `contextKey`: The context key for the context to remove from
        individual targeting

        * `contextKind`: The kind of context represented by the `contextKey`


        Here's an example:


        ```json

        {
          "instructions": [{
            "kind": "removeExpiringTarget",
            "variationId": "4254742c-71ae-411f-a992-43b18a51afe0",
            "contextKey": "user-key-123abc",
            "contextKind": "user"
          }]
        }

        ```


        </details>
      tags:
        - subpackage_featureFlags
      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: 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:
        '200':
          description: Expiring target response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ExpiringTargetPatchResponse'
        '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'
        '429':
          description: Rate limited
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RateLimitedErrorRep'
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/patchFlagsRequest'
servers:
  - url: https://app.launchdarkly.com
  - url: https://app.launchdarkly.us
components:
  schemas:
    Instruction:
      type: object
      additionalProperties:
        description: Any type
      title: Instruction
    patchFlagsRequest:
      type: object
      properties:
        comment:
          type: string
          description: Optional comment describing the change
        instructions:
          type: array
          items:
            $ref: '#/components/schemas/Instruction'
          description: The instructions to perform when updating
      required:
        - instructions
      title: patchFlagsRequest
    UnixMillis:
      type: integer
      format: int64
      title: UnixMillis
    ResourceKind:
      type: string
      title: ResourceKind
    ResourceId:
      type: object
      properties:
        environmentKey:
          type: string
          description: The environment key
        flagKey:
          type: string
          description: Deprecated, use <code>key</code> instead
        key:
          type: string
          description: The key of the flag or segment
        kind:
          $ref: '#/components/schemas/ResourceKind'
          description: The type of resource, <code>flag</code> or <code>segment</code>
        projectKey:
          type: string
          description: The project key
      title: ResourceId
    ExpiringTarget:
      type: object
      properties:
        _id:
          type: string
          description: The ID of this expiring target
        _version:
          type: integer
          description: The version of this expiring target
        expirationDate:
          $ref: '#/components/schemas/UnixMillis'
          description: A timestamp for when the target expires
        contextKind:
          type: string
          description: The context kind of the context to be removed
        contextKey:
          type: string
          description: A unique key used to represent the context to be removed
        targetType:
          type: string
          description: >-
            A segment's target type, <code>included</code> or
            <code>excluded</code>. Included when expiring targets are updated on
            a segment.
        variationId:
          type: string
          description: >-
            A unique ID used to represent the flag variation. Included when
            expiring targets are updated on a feature flag.
        _resourceId:
          $ref: '#/components/schemas/ResourceId'
          description: >-
            Details on the segment or flag this expiring target belongs to, its
            environment, and its project
      required:
        - _id
        - _version
        - expirationDate
        - contextKind
        - contextKey
        - _resourceId
      title: ExpiringTarget
    Link:
      type: object
      properties:
        href:
          type: string
          description: The URL of the link
        type:
          type: string
          description: The type of the link
      title: Link
    ExpiringTargetError:
      type: object
      properties:
        instructionIndex:
          type: integer
          description: The index of the PATCH instruction where the error occurred
        message:
          type: string
          description: The error message related to a failed PATCH instruction
      required:
        - instructionIndex
        - message
      title: ExpiringTargetError
    ExpiringTargetPatchResponse:
      type: object
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/ExpiringTarget'
          description: A list of the results from each instruction
        _links:
          type: object
          additionalProperties:
            $ref: '#/components/schemas/Link'
          description: The location and content type of related resources
        totalInstructions:
          type: integer
        successfulInstructions:
          type: integer
        failedInstructions:
          type: integer
        errors:
          type: array
          items:
            $ref: '#/components/schemas/ExpiringTargetError'
      required:
        - items
      title: ExpiringTargetPatchResponse
    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
    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/flags/projectKey/featureFlagKey/expiring-targets/environmentKey"

payload = { "instructions": [
        {
            "kind": "addExpireUserTargetDate",
            "userKey": "sandy",
            "value": 1686412800000,
            "variationId": "ce12d345-a1b2-4fb5-a123-ab123d4d5f5d"
        }
    ] }
headers = {
    "Authorization": "<apiKey>",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript
const url = 'https://app.launchdarkly.com/api/v2/flags/projectKey/featureFlagKey/expiring-targets/environmentKey';
const options = {
  method: 'PATCH',
  headers: {Authorization: '<apiKey>', 'Content-Type': 'application/json'},
  body: '{"instructions":[{"kind":"addExpireUserTargetDate","userKey":"sandy","value":1686412800000,"variationId":"ce12d345-a1b2-4fb5-a123-ab123d4d5f5d"}]}'
};

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/flags/projectKey/featureFlagKey/expiring-targets/environmentKey"

	payload := strings.NewReader("{\n  \"instructions\": [\n    {\n      \"kind\": \"addExpireUserTargetDate\",\n      \"userKey\": \"sandy\",\n      \"value\": 1686412800000,\n      \"variationId\": \"ce12d345-a1b2-4fb5-a123-ab123d4d5f5d\"\n    }\n  ]\n}")

	req, _ := http.NewRequest("PATCH", 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/flags/projectKey/featureFlagKey/expiring-targets/environmentKey")

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

request = Net::HTTP::Patch.new(url)
request["Authorization"] = '<apiKey>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"instructions\": [\n    {\n      \"kind\": \"addExpireUserTargetDate\",\n      \"userKey\": \"sandy\",\n      \"value\": 1686412800000,\n      \"variationId\": \"ce12d345-a1b2-4fb5-a123-ab123d4d5f5d\"\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.patch("https://app.launchdarkly.com/api/v2/flags/projectKey/featureFlagKey/expiring-targets/environmentKey")
  .header("Authorization", "<apiKey>")
  .header("Content-Type", "application/json")
  .body("{\n  \"instructions\": [\n    {\n      \"kind\": \"addExpireUserTargetDate\",\n      \"userKey\": \"sandy\",\n      \"value\": 1686412800000,\n      \"variationId\": \"ce12d345-a1b2-4fb5-a123-ab123d4d5f5d\"\n    }\n  ]\n}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('PATCH', 'https://app.launchdarkly.com/api/v2/flags/projectKey/featureFlagKey/expiring-targets/environmentKey', [
  'body' => '{
  "instructions": [
    {
      "kind": "addExpireUserTargetDate",
      "userKey": "sandy",
      "value": 1686412800000,
      "variationId": "ce12d345-a1b2-4fb5-a123-ab123d4d5f5d"
    }
  ]
}',
  'headers' => [
    'Authorization' => '<apiKey>',
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp
using RestSharp;

var client = new RestClient("https://app.launchdarkly.com/api/v2/flags/projectKey/featureFlagKey/expiring-targets/environmentKey");
var request = new RestRequest(Method.PATCH);
request.AddHeader("Authorization", "<apiKey>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"instructions\": [\n    {\n      \"kind\": \"addExpireUserTargetDate\",\n      \"userKey\": \"sandy\",\n      \"value\": 1686412800000,\n      \"variationId\": \"ce12d345-a1b2-4fb5-a123-ab123d4d5f5d\"\n    }\n  ]\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Authorization": "<apiKey>",
  "Content-Type": "application/json"
]
let parameters = ["instructions": [
    [
      "kind": "addExpireUserTargetDate",
      "userKey": "sandy",
      "value": 1686412800000,
      "variationId": "ce12d345-a1b2-4fb5-a123-ab123d4d5f5d"
    ]
  ]] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://app.launchdarkly.com/api/v2/flags/projectKey/featureFlagKey/expiring-targets/environmentKey")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "PATCH"
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()
```