# Update expiring user targets for segment

PATCH https://app.launchdarkly.com/api/v2/segments/{projectKey}/{segmentKey}/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 targets for segment](https://launchdarkly.com/docs/api/segments/patch-expiring-targets-for-segment) instead of this endpoint. To learn more, read [Contexts](https://launchdarkly.com/docs/home/observability/contexts).

Update expiring user targets for a segment. Updating a user target expiration 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).

If the request is well-formed but any of its instructions failed to process, this operation returns status code `200`. In this case, the response `errors` array will be non-empty.

### 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

Schedules a date and time when LaunchDarkly will remove a user from segment targeting.

##### Parameters

- `targetType`: A segment's target type, must be either `included` or `excluded`.
- `userKey`: The user key.
- `value`: The date when the user should expire from the segment targeting, in Unix milliseconds.

#### updateExpireUserTargetDate

Updates the date and time when LaunchDarkly will remove a user from segment targeting.

##### Parameters

- `targetType`: A segment's target type, must be either `included` or `excluded`.
- `userKey`: The user key.
- `value`: The new date when the user should expire from the segment targeting, in Unix milliseconds.
- `version`: The segment version.

#### removeExpireUserTargetDate

Removes the scheduled expiration for the user in the segment.

##### Parameters

- `targetType`: A segment's target type, must be either `included` or `excluded`.
- `userKey`: The user key.

</details>


Reference: https://launchdarkly.com/docs/api/segments/patch-expiring-user-targets-for-segment

## OpenAPI Specification

```yaml
openapi: 3.1.0
info:
  title: LaunchDarkly REST API
  version: 1.0.0
paths:
  /api/v2/segments/{projectKey}/{segmentKey}/expiring-user-targets/{environmentKey}:
    patch:
      operationId: patch-expiring-user-targets-for-segment
      summary: Update expiring user targets for segment
      description: >

        > ### Contexts are now available

        >

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


        Update expiring user targets for a segment. Updating a user target
        expiration 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).


        If the request is well-formed but any of its instructions failed to
        process, this operation returns status code `200`. In this case, the
        response `errors` array will be non-empty.


        ### 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


        Schedules a date and time when LaunchDarkly will remove a user from
        segment targeting.


        ##### Parameters


        - `targetType`: A segment's target type, must be either `included` or
        `excluded`.

        - `userKey`: The user key.

        - `value`: The date when the user should expire from the segment
        targeting, in Unix milliseconds.


        #### updateExpireUserTargetDate


        Updates the date and time when LaunchDarkly will remove a user from
        segment targeting.


        ##### Parameters


        - `targetType`: A segment's target type, must be either `included` or
        `excluded`.

        - `userKey`: The user key.

        - `value`: The new date when the user should expire from the segment
        targeting, in Unix milliseconds.

        - `version`: The segment version.


        #### removeExpireUserTargetDate


        Removes the scheduled expiration for the user in the segment.


        ##### Parameters


        - `targetType`: A segment's target type, must be either `included` or
        `excluded`.

        - `userKey`: The user key.


        </details>
      tags:
        - subpackage_segments
      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: segmentKey
          in: path
          description: The segment 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'
        '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/patchSegmentRequest'
servers:
  - url: https://app.launchdarkly.com
  - url: https://app.launchdarkly.us
components:
  schemas:
    PatchSegmentInstructionKind:
      type: string
      enum:
        - addExpireUserTargetDate
        - updateExpireUserTargetDate
        - removeExpireUserTargetDate
      description: The type of change to make to the user's removal date from this segment
      title: PatchSegmentInstructionKind
    PatchSegmentInstructionTargetType:
      type: string
      enum:
        - included
        - excluded
      description: The segment's target type
      title: PatchSegmentInstructionTargetType
    patchSegmentInstruction:
      type: object
      properties:
        kind:
          $ref: '#/components/schemas/PatchSegmentInstructionKind'
          description: >-
            The type of change to make to the user's removal date from this
            segment
        userKey:
          type: string
          description: A unique key used to represent the user
        targetType:
          $ref: '#/components/schemas/PatchSegmentInstructionTargetType'
          description: The segment's target type
        value:
          type: integer
          description: >-
            The time, in Unix milliseconds, when the user should be removed from
            this segment. Required if <code>kind</code> is
            <code>addExpireUserTargetDate</code> or
            <code>updateExpireUserTargetDate</code>.
        version:
          type: integer
          description: >-
            The version of the segment to update. Required if <code>kind</code>
            is <code>updateExpireUserTargetDate</code>.
      required:
        - kind
        - userKey
        - targetType
      title: patchSegmentInstruction
    patchSegmentRequest:
      type: object
      properties:
        comment:
          type: string
          description: Optional description of changes
        instructions:
          type: array
          items:
            $ref: '#/components/schemas/patchSegmentInstruction'
          description: Semantic patch instructions for the desired changes to the resource
      required:
        - instructions
      title: patchSegmentRequest
    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
    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/segments/projectKey/segmentKey/expiring-user-targets/environmentKey"

payload = { "instructions": [
        {
            "kind": "updateExpireUserTargetDate",
            "userKey": "user-key-123abc",
            "targetType": "included",
            "value": 1587582000000,
            "version": 0
        }
    ] }
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/segments/projectKey/segmentKey/expiring-user-targets/environmentKey';
const options = {
  method: 'PATCH',
  headers: {Authorization: '<apiKey>', 'Content-Type': 'application/json'},
  body: '{"instructions":[{"kind":"updateExpireUserTargetDate","userKey":"user-key-123abc","targetType":"included","value":1587582000000,"version":0}]}'
};

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/segments/projectKey/segmentKey/expiring-user-targets/environmentKey"

	payload := strings.NewReader("{\n  \"instructions\": [\n    {\n      \"kind\": \"updateExpireUserTargetDate\",\n      \"userKey\": \"user-key-123abc\",\n      \"targetType\": \"included\",\n      \"value\": 1587582000000,\n      \"version\": 0\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/segments/projectKey/segmentKey/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\": \"updateExpireUserTargetDate\",\n      \"userKey\": \"user-key-123abc\",\n      \"targetType\": \"included\",\n      \"value\": 1587582000000,\n      \"version\": 0\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/segments/projectKey/segmentKey/expiring-user-targets/environmentKey")
  .header("Authorization", "<apiKey>")
  .header("Content-Type", "application/json")
  .body("{\n  \"instructions\": [\n    {\n      \"kind\": \"updateExpireUserTargetDate\",\n      \"userKey\": \"user-key-123abc\",\n      \"targetType\": \"included\",\n      \"value\": 1587582000000,\n      \"version\": 0\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/segments/projectKey/segmentKey/expiring-user-targets/environmentKey', [
  'body' => '{
  "instructions": [
    {
      "kind": "updateExpireUserTargetDate",
      "userKey": "user-key-123abc",
      "targetType": "included",
      "value": 1587582000000,
      "version": 0
    }
  ]
}',
  'headers' => [
    'Authorization' => '<apiKey>',
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp
using RestSharp;

var client = new RestClient("https://app.launchdarkly.com/api/v2/segments/projectKey/segmentKey/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\": \"updateExpireUserTargetDate\",\n      \"userKey\": \"user-key-123abc\",\n      \"targetType\": \"included\",\n      \"value\": 1587582000000,\n      \"version\": 0\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": "updateExpireUserTargetDate",
      "userKey": "user-key-123abc",
      "targetType": "included",
      "value": 1587582000000,
      "version": 0
    ]
  ]] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://app.launchdarkly.com/api/v2/segments/projectKey/segmentKey/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()
```