# Update expiring targets for segment

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


Update expiring context targets for a segment. Updating a context 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 context targets.

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

#### addExpiringTarget

Schedules a date and time when LaunchDarkly will remove a context from segment targeting. The segment must already have the context as an individual target.

##### Parameters

- `targetType`: The type of individual target for this context. Must be either `included` or `excluded`.
- `contextKey`: The context key.
- `contextKind`: The kind of context being targeted.
- `value`: The date when the context should expire from the segment targeting, in Unix milliseconds.

Here's an example:

```json
{
  "instructions": [{
    "kind": "addExpiringTarget",
    "targetType": "included",
    "contextKey": "user-key-123abc",
    "contextKind": "user",
    "value": 1754092860000
  }]
}
```

#### updateExpiringTarget

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

##### Parameters

- `targetType`: The type of individual target for this context. Must be either `included` or `excluded`.
- `contextKey`: The context key.
- `contextKind`: The kind of context being targeted.
- `value`: The new date when the context should expire from the segment targeting, in Unix milliseconds.
- `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",
    "targetType": "included",
    "contextKey": "user-key-123abc",
    "contextKind": "user",
    "value": 1754179260000
  }]
}
```

#### removeExpiringTarget

Removes the scheduled expiration for the context in the segment.

##### Parameters

- `targetType`: The type of individual target for this context. Must be either `included` or `excluded`.
- `contextKey`: The context key.
- `contextKind`: The kind of context being targeted.

Here's an example:

```json
{
  "instructions": [{
    "kind": "removeExpiringTarget",
    "targetType": "included",
    "contextKey": "user-key-123abc",
    "contextKind": "user",
  }]
}
```

</details>


Reference: https://launchdarkly.com/docs/api/segments/patch-expiring-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-targets/{environmentKey}:
    patch:
      operationId: patch-expiring-targets-for-segment
      summary: Update expiring targets for segment
      description: >

        Update expiring context targets for a segment. Updating a context 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 context targets.


        <details>

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


        #### addExpiringTarget


        Schedules a date and time when LaunchDarkly will remove a context from
        segment targeting. The segment must already have the context as an
        individual target.


        ##### Parameters


        - `targetType`: The type of individual target for this context. Must be
        either `included` or `excluded`.

        - `contextKey`: The context key.

        - `contextKind`: The kind of context being targeted.

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


        Here's an example:


        ```json

        {
          "instructions": [{
            "kind": "addExpiringTarget",
            "targetType": "included",
            "contextKey": "user-key-123abc",
            "contextKind": "user",
            "value": 1754092860000
          }]
        }

        ```


        #### updateExpiringTarget


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


        ##### Parameters


        - `targetType`: The type of individual target for this context. Must be
        either `included` or `excluded`.

        - `contextKey`: The context key.

        - `contextKind`: The kind of context being targeted.

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

        - `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",
            "targetType": "included",
            "contextKey": "user-key-123abc",
            "contextKind": "user",
            "value": 1754179260000
          }]
        }

        ```


        #### removeExpiringTarget


        Removes the scheduled expiration for the context in the segment.


        ##### Parameters


        - `targetType`: The type of individual target for this context. Must be
        either `included` or `excluded`.

        - `contextKey`: The context key.

        - `contextKind`: The kind of context being targeted.


        Here's an example:


        ```json

        {
          "instructions": [{
            "kind": "removeExpiringTarget",
            "targetType": "included",
            "contextKey": "user-key-123abc",
            "contextKind": "user",
          }]
        }

        ```


        </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  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'
        '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/patchSegmentExpiringTargetInputRep'
servers:
  - url: https://app.launchdarkly.com
  - url: https://app.launchdarkly.us
components:
  schemas:
    PatchSegmentExpiringTargetInstructionKind:
      type: string
      enum:
        - addExpiringTarget
        - updateExpiringTarget
        - removeExpiringTarget
      description: >-
        The type of change to make to the context's removal date from this
        segment
      title: PatchSegmentExpiringTargetInstructionKind
    PatchSegmentExpiringTargetInstructionTargetType:
      type: string
      enum:
        - included
        - excluded
      description: The segment's target type
      title: PatchSegmentExpiringTargetInstructionTargetType
    patchSegmentExpiringTargetInstruction:
      type: object
      properties:
        kind:
          $ref: '#/components/schemas/PatchSegmentExpiringTargetInstructionKind'
          description: >-
            The type of change to make to the context's removal date from this
            segment
        contextKey:
          type: string
          description: A unique key used to represent the context
        contextKind:
          type: string
          description: The kind of context
        targetType:
          $ref: '#/components/schemas/PatchSegmentExpiringTargetInstructionTargetType'
          description: The segment's target type
        value:
          type: integer
          format: int64
          description: >-
            The time, in Unix milliseconds, when the context should be removed
            from this segment. Required if <code>kind</code> is
            <code>addExpiringTarget</code> or <code>updateExpiringTarget</code>.
        version:
          type: integer
          description: >-
            The version of the expiring target to update. Optional and only used
            if <code>kind</code> is <code>updateExpiringTarget</code>. If
            included, update will fail if version doesn't match current version
            of the expiring target.
      required:
        - kind
        - contextKey
        - contextKind
        - targetType
      title: patchSegmentExpiringTargetInstruction
    patchSegmentExpiringTargetInputRep:
      type: object
      properties:
        comment:
          type: string
          description: Optional description of changes
        instructions:
          type: array
          items:
            $ref: '#/components/schemas/patchSegmentExpiringTargetInstruction'
          description: Semantic patch instructions for the desired changes to the resource
      required:
        - instructions
      title: patchSegmentExpiringTargetInputRep
    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
    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-targets/environmentKey"

payload = { "instructions": [
        {
            "kind": "updateExpiringTarget",
            "contextKey": "user@email.com",
            "contextKind": "user",
            "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-targets/environmentKey';
const options = {
  method: 'PATCH',
  headers: {Authorization: '<apiKey>', 'Content-Type': 'application/json'},
  body: '{"instructions":[{"kind":"updateExpiringTarget","contextKey":"user@email.com","contextKind":"user","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-targets/environmentKey"

	payload := strings.NewReader("{\n  \"instructions\": [\n    {\n      \"kind\": \"updateExpiringTarget\",\n      \"contextKey\": \"user@email.com\",\n      \"contextKind\": \"user\",\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-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\": \"updateExpiringTarget\",\n      \"contextKey\": \"user@email.com\",\n      \"contextKind\": \"user\",\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-targets/environmentKey")
  .header("Authorization", "<apiKey>")
  .header("Content-Type", "application/json")
  .body("{\n  \"instructions\": [\n    {\n      \"kind\": \"updateExpiringTarget\",\n      \"contextKey\": \"user@email.com\",\n      \"contextKind\": \"user\",\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-targets/environmentKey', [
  'body' => '{
  "instructions": [
    {
      "kind": "updateExpiringTarget",
      "contextKey": "user@email.com",
      "contextKind": "user",
      "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-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\": \"updateExpiringTarget\",\n      \"contextKey\": \"user@email.com\",\n      \"contextKind\": \"user\",\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": "updateExpiringTarget",
      "contextKey": "user@email.com",
      "contextKind": "user",
      "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-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()
```