# Evaluate flags for context instance

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

Evaluate flags for a context instance, for example, to determine the expected flag variation. **Do not use this API instead of an SDK.** The LaunchDarkly SDKs are specialized for the tasks of evaluating feature flags in your application at scale and generating analytics events based on those evaluations. This API is not designed for that use case. Any evaluations you perform with this API will not be reflected in features such as flag statuses and flag insights. Context instances evaluated by this API will not appear in the Contexts list. To learn more, read [Comparing LaunchDarkly's SDKs and REST API](https://launchdarkly.com/docs/guides/api/comparing-sdk-rest-api).

### Filtering

LaunchDarkly supports the `filter` query param for filtering, with the following fields:

- `query` filters for a string that matches against the flags' keys and names. It is not case sensitive. For example: `filter=query equals dark-mode`.
- `tags` filters the list to flags that have all of the tags in the list. For example: `filter=tags contains ["beta","q1"]`.

You can also apply multiple filters at once. For example, setting `filter=query equals dark-mode, tags contains ["beta","q1"]` matches flags which match the key or name `dark-mode` and are tagged `beta` and `q1`.


Reference: https://launchdarkly.com/docs/api/contexts/evaluate-context-instance

## OpenAPI Specification

```yaml
openapi: 3.1.0
info:
  title: LaunchDarkly REST API
  version: 1.0.0
paths:
  /api/v2/projects/{projectKey}/environments/{environmentKey}/flags/evaluate:
    post:
      operationId: evaluate-context-instance
      summary: Evaluate flags for context instance
      description: >
        Evaluate flags for a context instance, for example, to determine the
        expected flag variation. **Do not use this API instead of an SDK.** The
        LaunchDarkly SDKs are specialized for the tasks of evaluating feature
        flags in your application at scale and generating analytics events based
        on those evaluations. This API is not designed for that use case. Any
        evaluations you perform with this API will not be reflected in features
        such as flag statuses and flag insights. Context instances evaluated by
        this API will not appear in the Contexts list. To learn more, read
        [Comparing LaunchDarkly's SDKs and REST
        API](https://launchdarkly.com/docs/guides/api/comparing-sdk-rest-api).


        ### Filtering


        LaunchDarkly supports the `filter` query param for filtering, with the
        following fields:


        - `query` filters for a string that matches against the flags' keys and
        names. It is not case sensitive. For example: `filter=query equals
        dark-mode`.

        - `tags` filters the list to flags that have all of the tags in the
        list. For example: `filter=tags contains ["beta","q1"]`.


        You can also apply multiple filters at once. For example, setting
        `filter=query equals dark-mode, tags contains ["beta","q1"]` matches
        flags which match the key or name `dark-mode` and are tagged `beta` and
        `q1`.
      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: >-
            The number of feature flags to return. Defaults to -1, which returns
            all flags
          required: false
          schema:
            type: integer
            format: int64
        - name: offset
          in: query
          description: >-
            Where to start in the list. Use this with pagination. For example,
            an offset of 10 skips the first ten items and then returns the next
            items in the list, up to the query `limit`.
          required: false
          schema:
            type: integer
            format: int64
        - name: sort
          in: query
          description: >-
            A comma-separated list of fields to sort by. Fields prefixed by a
            dash ( - ) sort in descending order
          required: false
          schema:
            type: string
            format: string
        - name: filter
          in: query
          description: >-
            A comma-separated list of filters. Each filter is of the form `field
            operator value`. Supported fields are explained above.
          required: false
          schema:
            type: string
            format: string
        - name: Authorization
          in: header
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Flag evaluation collection response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ContextInstanceEvaluations'
        '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/ContextInstance'
servers:
  - url: https://app.launchdarkly.com
  - url: https://app.launchdarkly.us
components:
  schemas:
    ContextInstance:
      type: object
      additionalProperties:
        description: Any type
      title: ContextInstance
    ContextInstanceEvaluationReason:
      type: object
      properties:
        kind:
          type: string
          description: >-
            Describes the general reason that LaunchDarkly selected this
            variation.
        ruleIndex:
          type: integer
          description: >-
            The positional index of the matching rule if the kind is
            'RULE_MATCH'. The index is 0-based.
        ruleID:
          type: string
          description: >-
            The unique identifier of the matching rule if the kind is
            'RULE_MATCH'.
        prerequisiteKey:
          type: string
          description: >-
            The key of the flag that failed if the kind is
            'PREREQUISITE_FAILED'.
        inExperiment:
          type: boolean
          description: >-
            Indicates whether the context was evaluated as part of an
            experiment.
        errorKind:
          type: string
          description: The specific error type if the kind is 'ERROR'.
      required:
        - kind
      title: ContextInstanceEvaluationReason
    Link:
      type: object
      properties:
        href:
          type: string
          description: The URL of the link
        type:
          type: string
          description: The type of the link
      title: Link
    ContextInstanceEvaluation:
      type: object
      properties:
        name:
          type: string
          description: Name of the flag.
        key:
          type: string
          description: Key of the flag.
        _value:
          description: >-
            The value of the flag variation that the context receives. If there
            is no defined default rule, this is null.
        reason:
          $ref: '#/components/schemas/ContextInstanceEvaluationReason'
          description: Contains information about why that variation was selected.
        _links:
          type: object
          additionalProperties:
            $ref: '#/components/schemas/Link'
          description: The location and content type of related resources
      required:
        - name
        - key
        - _value
        - _links
      title: ContextInstanceEvaluation
    ContextInstanceEvaluations:
      type: object
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/ContextInstanceEvaluation'
          description: Details on the flag evaluations for this context instance
        totalCount:
          type: integer
          description: The number of flags
        _links:
          type: object
          additionalProperties:
            $ref: '#/components/schemas/Link'
          description: The location and content type of related resources
      required:
        - items
        - _links
      title: ContextInstanceEvaluations
    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/projects/projectKey/environments/environmentKey/flags/evaluate"

payload = {
    "key": "user-key-123abc",
    "kind": "user",
    "otherAttribute": "other attribute value"
}
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/flags/evaluate';
const options = {
  method: 'POST',
  headers: {Authorization: '<apiKey>', 'Content-Type': 'application/json'},
  body: '{"key":"user-key-123abc","kind":"user","otherAttribute":"other attribute value"}'
};

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/flags/evaluate"

	payload := strings.NewReader("{\n  \"key\": \"user-key-123abc\",\n  \"kind\": \"user\",\n  \"otherAttribute\": \"other attribute value\"\n}")

	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/flags/evaluate")

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 = "{\n  \"key\": \"user-key-123abc\",\n  \"kind\": \"user\",\n  \"otherAttribute\": \"other attribute value\"\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.post("https://app.launchdarkly.com/api/v2/projects/projectKey/environments/environmentKey/flags/evaluate")
  .header("Authorization", "<apiKey>")
  .header("Content-Type", "application/json")
  .body("{\n  \"key\": \"user-key-123abc\",\n  \"kind\": \"user\",\n  \"otherAttribute\": \"other attribute value\"\n}")
  .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/flags/evaluate', [
  'body' => '{
  "key": "user-key-123abc",
  "kind": "user",
  "otherAttribute": "other attribute value"
}',
  '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/flags/evaluate");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "<apiKey>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"key\": \"user-key-123abc\",\n  \"kind\": \"user\",\n  \"otherAttribute\": \"other attribute value\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Authorization": "<apiKey>",
  "Content-Type": "application/json"
]
let parameters = [
  "key": "user-key-123abc",
  "kind": "user",
  "otherAttribute": "other attribute value"
] 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/flags/evaluate")! 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()
```