> ## Documentation Index
> Fetch the complete documentation index at: https://docs.permutive.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Get Contextual Segments

Retrieve contextual cohort codes for a given URL and page properties. Returns cohort codes formatted for Google Ad Manager.

## Request

### Query Parameters

<ParamField query="k" type="string" required>
  Your Permutive API key. This is the same API key used for your main Permutive SDK deployment.
</ParamField>

### Body Parameters

<ParamField body="url" type="string" required>
  The URL to retrieve contextual cohorts for. This is typically the current page URL.
</ParamField>

<ParamField body="page_properties" type="object" required>
  An object containing page properties used for contextual classification. This should match the structure of properties you track in Pageview events, but **must exclude any user-related data**.

  <Expandable title="page_properties structure">
    <ParamField body="page_properties.client" type="object">
      Client information for the request.

      <Expandable title="client properties">
        <ParamField body="page_properties.client.url" type="string">
          The page URL
        </ParamField>

        <ParamField body="page_properties.client.domain" type="string">
          The domain of the page
        </ParamField>

        <ParamField body="page_properties.client.referrer" type="string">
          The referrer URL
        </ParamField>

        <ParamField body="page_properties.client.type" type="string">
          The client type: `web`, `ios`, or `android`
        </ParamField>

        <ParamField body="page_properties.client.user_agent" type="string">
          The user agent string
        </ParamField>

        <ParamField body="page_properties.client.title" type="string">
          The page title
        </ParamField>
      </Expandable>
    </ParamField>

    You can also include any custom page properties that you track as part of your Pageview events (e.g., `category`, `tags`, `author`).
  </Expandable>
</ParamField>

<Warning>
  **Personal Data**: The request must not contain any user-related data points. Omit any user-related properties that you might be recording as part of your Pageview events.
</Warning>

## Response

<ResponseField name="cohorts" type="array of strings">
  All contextual cohort codes for the page. This is the complete list of cohorts that matched.
</ResponseField>

<ResponseField name="activations" type="object">
  An object mapping activation destination names to arrays of cohort code strings. Each key is an activation destination (e.g., `target_dfp`, `appnexus_adserver`) and the value is an array of cohort codes configured for that destination.
</ResponseField>

<ResponseField name="contextual_data" type="object">
  An object containing content classification data, returned when a classification provider is enabled in the account. Includes classifications such as categories, keywords, entities, sentiment, emotion, and concepts.
</ResponseField>

## Example Request

<CodeGroup>
  ```bash cURL theme={"dark"}
  curl -X POST "https://api.permutive.com/ctx/v1/segment?k=YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "url": "https://example.com/article/sports-news",
      "page_properties": {
        "client": {
          "url": "https://example.com/article/sports-news",
          "domain": "example.com",
          "referrer": "https://example.com",
          "type": "web",
          "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
          "title": "Latest Sports News"
        },
        "category": "sports",
        "tags": ["football", "premier-league"]
      }
    }'
  ```

  ```javascript JavaScript theme={"dark"}
  const apiKey = 'YOUR_API_KEY';
  const url = `https://api.permutive.com/ctx/v1/segment?k=${apiKey}`;

  const response = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      url: document.URL,
      page_properties: {
        client: {
          url: document.URL,
          domain: window.location.hostname,
          referrer: document.referrer,
          type: 'web',
          user_agent: navigator.userAgent,
          title: document.title
        },
        category: 'sports',
        tags: ['football', 'premier-league']
      }
    })
  });

  const data = await response.json();
  console.log(data);
  ```

  ```swift Swift theme={"dark"}
  let apiKey = "YOUR_API_KEY"
  let requestUrl = URL(string: "https://api.permutive.com/ctx/v1/segment?k=\(apiKey)")!

  let requestBody: [String: Any] = [
      "url": "https://example.com/article/sports-news",
      "page_properties": [
          "client": [
              "url": "https://example.com/article/sports-news",
              "domain": "example.com",
              "type": "ios",
              "title": "Latest Sports News"
          ],
          "category": "sports"
      ]
  ]

  var request = URLRequest(url: requestUrl)
  request.httpMethod = "POST"
  request.httpBody = try? JSONSerialization.data(withJSONObject: requestBody)
  request.setValue("application/json", forHTTPHeaderField: "Content-Type")

  URLSession.shared.dataTask(with: request) { data, response, error in
      // Handle response
  }.resume()
  ```

  ```kotlin Kotlin theme={"dark"}
  val apiKey = "YOUR_API_KEY"
  val requestBody = ContextualBody(
      page_properties = mapOf(
          "client" to mapOf(
              "url" to "https://example.com/article/sports-news",
              "domain" to "example.com",
              "type" to "android",
              "title" to "Latest Sports News"
          ),
          "category" to "sports"
      ),
      url = "https://example.com/article/sports-news"
  )

  contextualApi.getContextualCohorts(apiKey, requestBody)
      .enqueue(object : Callback<ContextualResponse> {
          override fun onResponse(call: Call<ContextualResponse>, response: Response<ContextualResponse>) {
              val cohorts = response.body()
              // Handle response
          }
          override fun onFailure(call: Call<ContextualResponse>, t: Throwable) {
              // Handle error
          }
      })
  ```
</CodeGroup>

## Example Response

<CodeGroup>
  ```json Success (200) theme={"dark"}
  {
    "cohorts": ["abc", "def", "ghi"],
    "activations": {
      "target_dfp": ["abc", "def"],
      "appnexus_adserver": ["ghi"]
    },
    "contextual_data": {
      "classifications": {
        "categories": [
          {
            "value": "155",
            "confidence": 0.5,
            "taxonomy": "iab_3.0",
            "provider": "ibm_watson"
          }
        ],
        "keywords": [
          {
            "value": "museum",
            "confidence": 0.7,
            "provider": "ibm_watson"
          }
        ],
        "entities": [
          {
            "value": "British Museum",
            "confidence": 0.9,
            "provider": "ibm_watson"
          }
        ],
        "sentiment": [
          {
            "value": "positive",
            "confidence": 0.9,
            "provider": "ibm_watson"
          }
        ],
        "emotion": [
          {
            "value": "joy",
            "confidence": 0.4,
            "provider": "ibm_watson"
          }
        ],
        "concepts": [
          {
            "value": "Vincent van Gogh",
            "confidence": 0.6,
            "provider": "ibm_watson"
          }
        ]
      }
    }
  }
  ```

  ```json No matching cohorts (200) theme={"dark"}
  {
    "cohorts": [],
    "activations": {},
    "contextual_data": {}
  }
  ```

  ```json Error (400) theme={"dark"}
  {
    "error": "Invalid request body"
  }
  ```
</CodeGroup>

## Implementation Notes

<AccordionGroup>
  <Accordion title="Always include 'rts' in targeting">
    When passing targeting values to your ad server, always append `rts` to the array of cohort codes. This is required for proper targeting:

    ```javascript theme={"dark"}
    const targetingValues = apiResponse.activations.target_dfp.concat('rts');
    ```
  </Accordion>

  <Accordion title="Call early in page lifecycle">
    Make the API call as early as possible when the page loads to ensure targeting is attached to the first ad call. We recommend placing the API call in the `<head>` of your page.
  </Accordion>

  <Accordion title="Use the same API key">
    Use the same API key that you use for your main Permutive SDK deployment. This ensures cohorts are correctly associated with your workspace.
  </Accordion>
</AccordionGroup>

## Related

<CardGroup cols={2}>
  <Card title="Activating in Google Ad Manager" href="/guides/signals/cohorts/contextual/deploying-to-google-ad-manager" icon="bullseye">
    Full implementation guide with code samples for Google Ad Manager.
  </Card>

  <Card title="API Introduction" href="./introduction" icon="book">
    Overview of the Contextual API.
  </Card>
</CardGroup>
