# Update expiring user targets on feature flag

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

> ### Contexts are now available
>
> After you have upgraded your LaunchDarkly SDK to use contexts instead of users, you should use [Update expiring context targets on feature flag](https://launchdarkly.com/docs/api/feature-flags/patch-expiring-targets) instead of this endpoint. To learn more, read [Contexts](https://launchdarkly.com/docs/home/observability/contexts).

Schedule a target for removal from individual targeting on a feature flag. The flag must already serve a variation to specific targets based on their key.

You can add, update, or remove a scheduled removal date. You can only schedule a target 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 user targets.

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

#### addExpireUserTargetDate

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

##### Parameters

* `value`: The time, in Unix milliseconds, when LaunchDarkly should remove the user from individual targeting for this flag
* `variationId`: ID of a variation on the flag
* `userKey`: The user key for the user to remove from individual targeting

#### updateExpireUserTargetDate

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

##### Parameters

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

#### removeExpireUserTargetDate

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

##### Parameters

* `variationId`: ID of a variation on the flag
* `userKey`: The user key for the user to remove from individual targeting

</details>


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

## OpenAPI Specification

```yaml
openapi: 3.1.0
info:
  title: LaunchDarkly REST API
  version: 1.0.0
paths:
  /api/v2/flags/{projectKey}/{featureFlagKey}/expiring-user-targets/{environmentKey}:
    patch:
      operationId: patch-expiring-user-targets
      summary: Update expiring user targets on feature flag
      description: >
        > ### Contexts are now available

        >

        > After you have upgraded your LaunchDarkly SDK to use contexts instead
        of users, you should use [Update expiring context targets on feature
        flag](https://launchdarkly.com/docs/api/feature-flags/patch-expiring-targets)
        instead of this endpoint. To learn more, read
        [Contexts](https://launchdarkly.com/docs/home/observability/contexts).


        Schedule a target for removal from individual targeting on a feature
        flag. The flag must already serve a variation to specific targets based
        on their key.


        You can add, update, or remove a scheduled removal date. You can only
        schedule a target 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 user targets.


        <details>

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


        #### addExpireUserTargetDate


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


        ##### Parameters


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

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

        * `userKey`: The user key for the user to remove from individual
        targeting


        #### updateExpireUserTargetDate


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


        ##### Parameters


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

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

        * `userKey`: The user key for the user to remove from individual
        targeting

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


        #### removeExpireUserTargetDate


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


        ##### Parameters


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

        * `userKey`: The user key for the user to remove from individual
        targeting


        </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 user target response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ExpiringUserTargetPatchResponse'
        '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
    ResourceIDResponse:
      type: object
      properties:
        kind:
          type: string
        projectKey:
          type: string
        environmentKey:
          type: string
        flagKey:
          type: string
        key:
          type: string
      title: ResourceIDResponse
    ExpiringUserTargetItem:
      type: object
      properties:
        _id:
          type: string
          description: The ID of this expiring user target
        _version:
          type: integer
          description: The version of this expiring user target
        expirationDate:
          $ref: '#/components/schemas/UnixMillis'
          description: A timestamp for when the user target expires
        userKey:
          type: string
          description: A unique key used to represent the user
        targetType:
          type: string
          description: >-
            A segment's target type. Included when expiring user targets are
            updated on a segment.
        variationId:
          type: string
          description: >-
            A unique key used to represent the flag variation. Included when
            expiring user targets are updated on a feature flag.
        _resourceId:
          $ref: '#/components/schemas/ResourceIDResponse'
          description: Details on the resource from which the user is expiring
      required:
        - _id
        - _version
        - expirationDate
        - userKey
        - _resourceId
      title: ExpiringUserTargetItem
    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
    ExpiringUserTargetPatchResponse:
      type: object
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/ExpiringUserTargetItem'
          description: An array of expiring user targets
        _links:
          type: object
          additionalProperties:
            $ref: '#/components/schemas/Link'
          description: The location and content type of related resources
        totalInstructions:
          type: integer
          description: The total count of instructions sent in the PATCH request
        successfulInstructions:
          type: integer
          description: The total count of successful instructions sent in the PATCH request
        failedInstructions:
          type: integer
          description: The total count of the failed instructions sent in the PATCH request
        errors:
          type: array
          items:
            $ref: '#/components/schemas/ExpiringTargetError'
          description: An array of error messages for the failed instructions
      required:
        - items
      title: ExpiringUserTargetPatchResponse
    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-user-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-user-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-user-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-user-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-user-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-user-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-user-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-user-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()
```