# Search for contexts

POST https://app.launchdarkly.com/api/v2/projects/{projectKey}/environments/{environmentKey}/contexts/search
Content-Type: application/json


Search for contexts.

You can use either the query parameters or the request body parameters. If both are provided, there is an error.

To learn more about the filter syntax, read [Filtering contexts and context instances](https://launchdarkly.com/docs/api/contexts#filtering-contexts-and-context-instances). To learn more about contexts, read [Contexts and context kinds](https://launchdarkly.com/docs/home/observability/contexts#contexts-and-context-kinds).


Reference: https://launchdarkly.com/docs/api/contexts/search-contexts

## OpenAPI Specification

```yaml
openapi: 3.1.0
info:
  title: LaunchDarkly REST API
  version: 1.0.0
paths:
  /api/v2/projects/{projectKey}/environments/{environmentKey}/contexts/search:
    post:
      operationId: search-contexts
      summary: Search for contexts
      description: >

        Search for contexts.


        You can use either the query parameters or the request body parameters.
        If both are provided, there is an error.


        To learn more about the filter syntax, read [Filtering contexts and
        context
        instances](https://launchdarkly.com/docs/api/contexts#filtering-contexts-and-context-instances).
        To learn more about contexts, read [Contexts and context
        kinds](https://launchdarkly.com/docs/home/observability/contexts#contexts-and-context-kinds).
      tags:
        - subpackage_contexts
      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: limit
          in: query
          description: >-
            Specifies the maximum number of items in the collection to return
            (max: 50, default: 20)
          required: false
          schema:
            type: integer
            format: int64
        - name: continuationToken
          in: query
          description: >-
            Limits results to contexts with sort values after the value
            specified. You can use this for pagination, however, we recommend
            using the `next` link we provide instead.
          required: false
          schema:
            type: string
            format: string
        - name: sort
          in: query
          description: >-
            Specifies a field by which to sort. LaunchDarkly supports sorting by
            timestamp in ascending order by specifying `ts` for this value, or
            descending order by specifying `-ts`.
          required: false
          schema:
            type: string
            format: string
        - name: filter
          in: query
          description: >-
            A comma-separated list of context filters. To learn more about the
            filter syntax, read [Filtering contexts and context
            instances](https://launchdarkly.com/docs/ld-docs/api/contexts#filtering-contexts-and-context-instances).
          required: false
          schema:
            type: string
            format: string
        - name: includeTotalCount
          in: query
          description: >-
            Specifies whether to include or omit the total count of matching
            contexts. Defaults to true.
          required: false
          schema:
            type: boolean
        - name: Authorization
          in: header
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Contexts collection response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Contexts'
        '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'
        '429':
          description: Rate limited
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RateLimitedErrorRep'
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ContextSearch'
servers:
  - url: https://app.launchdarkly.com
  - url: https://app.launchdarkly.us
components:
  schemas:
    ContextSearch:
      type: object
      properties:
        filter:
          type: string
          description: A collection of context filters
        sort:
          type: string
          description: >-
            Specifies a field by which to sort. LaunchDarkly supports sorting by
            timestamp in ascending order by specifying <code>ts</code> for this
            value, or descending order by specifying <code>-ts</code>.
        limit:
          type: integer
          description: >-
            Specifies the maximum number of items in the collection to return
            (max: 50, default: 20)
        continuationToken:
          type: string
          description: >-
            Limits results to contexts with sort values after the value
            specified. You can use this for pagination, however, we recommend
            using the <code>next</code> link instead, because this value is an
            obfuscated string.
      title: ContextSearch
    Link:
      type: object
      properties:
        href:
          type: string
          description: The URL of the link
        type:
          type: string
          description: The type of the link
      title: Link
    ActionIdentifier:
      type: string
      title: ActionIdentifier
    ActionSpecifier:
      type: string
      title: ActionSpecifier
    AccessDeniedReasonEffect:
      type: string
      enum:
        - allow
        - deny
      description: Whether this statement should allow or deny actions on the resources.
      title: AccessDeniedReasonEffect
    AccessDeniedReason:
      type: object
      properties:
        resources:
          type: array
          items:
            type: string
          description: Resource specifier strings
        notResources:
          type: array
          items:
            type: string
          description: >-
            Targeted resources are the resources NOT in this list. The
            <code>resources</code> and <code>notActions</code> fields must be
            empty to use this field.
        actions:
          type: array
          items:
            $ref: '#/components/schemas/ActionSpecifier'
          description: Actions to perform on a resource
        notActions:
          type: array
          items:
            $ref: '#/components/schemas/ActionSpecifier'
          description: >-
            Targeted actions are the actions NOT in this list. The
            <code>actions</code> and <code>notResources</code> fields must be
            empty to use this field.
        effect:
          $ref: '#/components/schemas/AccessDeniedReasonEffect'
          description: >-
            Whether this statement should allow or deny actions on the
            resources.
        role_name:
          type: string
      required:
        - effect
      title: AccessDeniedReason
    AccessDenied:
      type: object
      properties:
        action:
          $ref: '#/components/schemas/ActionIdentifier'
        reason:
          $ref: '#/components/schemas/AccessDeniedReason'
      required:
        - action
        - reason
      title: AccessDenied
    AccessAllowedReasonEffect:
      type: string
      enum:
        - allow
        - deny
      description: Whether this statement should allow or deny actions on the resources.
      title: AccessAllowedReasonEffect
    AccessAllowedReason:
      type: object
      properties:
        resources:
          type: array
          items:
            type: string
          description: Resource specifier strings
        notResources:
          type: array
          items:
            type: string
          description: >-
            Targeted resources are the resources NOT in this list. The
            <code>resources</code> and <code>notActions</code> fields must be
            empty to use this field.
        actions:
          type: array
          items:
            $ref: '#/components/schemas/ActionSpecifier'
          description: Actions to perform on a resource
        notActions:
          type: array
          items:
            $ref: '#/components/schemas/ActionSpecifier'
          description: >-
            Targeted actions are the actions NOT in this list. The
            <code>actions</code> and <code>notResources</code> fields must be
            empty to use this field.
        effect:
          $ref: '#/components/schemas/AccessAllowedReasonEffect'
          description: >-
            Whether this statement should allow or deny actions on the
            resources.
        role_name:
          type: string
      required:
        - effect
      title: AccessAllowedReason
    AccessAllowedRep:
      type: object
      properties:
        action:
          $ref: '#/components/schemas/ActionIdentifier'
        reason:
          $ref: '#/components/schemas/AccessAllowedReason'
      required:
        - action
        - reason
      title: AccessAllowedRep
    Access:
      type: object
      properties:
        denied:
          type: array
          items:
            $ref: '#/components/schemas/AccessDenied'
        allowed:
          type: array
          items:
            $ref: '#/components/schemas/AccessAllowedRep'
      required:
        - denied
        - allowed
      title: Access
    ContextRecord:
      type: object
      properties:
        lastSeen:
          type: string
          format: date-time
          description: Timestamp of the last time an evaluation occurred for this context
        applicationId:
          type: string
          description: >-
            An identifier representing the application where the LaunchDarkly
            SDK is running
        context:
          description: The context, including its kind and attributes
        _links:
          type: object
          additionalProperties:
            $ref: '#/components/schemas/Link'
          description: The location and content type of related resources
        _access:
          $ref: '#/components/schemas/Access'
          description: Details on the allowed and denied actions for this context instance
        associatedContexts:
          type: integer
          description: >-
            The total number of associated contexts. Associated contexts are
            contexts that have appeared in the same context instance, that is,
            they were part of the same flag evaluation.
      required:
        - context
      title: ContextRecord
    Contexts:
      type: object
      properties:
        _links:
          type: object
          additionalProperties:
            $ref: '#/components/schemas/Link'
          description: The location and content type of related resources
        totalCount:
          type: integer
          description: The number of contexts
        _environmentId:
          type: string
          description: The environment ID where the context was evaluated
        continuationToken:
          type: string
          description: >-
            An obfuscated string that references the last context instance on
            the previous page of results. You can use this for pagination,
            however, we recommend using the <code>next</code> link instead.
        items:
          type: array
          items:
            $ref: '#/components/schemas/ContextRecord'
          description: >-
            A collection of contexts. Can include multiple versions of contexts
            that have the same <code>kind</code> and <code>key</code>, but
            different <code>applicationId</code>s.
      required:
        - _environmentId
        - items
      title: Contexts
    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
    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/search"

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

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

print(response.json())
```

```javascript
const url = 'https://app.launchdarkly.com/api/v2/projects/projectKey/environments/environmentKey/contexts/search';
const options = {
  method: 'POST',
  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/search"

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

	req, _ := http.NewRequest("POST", 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/search")

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

request = Net::HTTP::Post.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.post("https://app.launchdarkly.com/api/v2/projects/projectKey/environments/environmentKey/contexts/search")
  .header("Authorization", "<apiKey>")
  .header("Content-Type", "application/json")
  .body("{}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://app.launchdarkly.com/api/v2/projects/projectKey/environments/environmentKey/contexts/search', [
  '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/search");
var request = new RestRequest(Method.POST);
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/search")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
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()
```