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

**k** `string` *required*

Your Permutive API key. This is the same API key used for your main Permutive SDK deployment.

### Body Parameters

**url** `string` *required*

The URL to retrieve contextual cohorts for. This is typically the current page URL.

**page\_properties** `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**.

**page\_properties structure**

**client** `object`

Client information for the request.

**client properties**

**url** `string`

The page URL

**domain** `string`

The domain of the page

**referrer** `string`

The referrer URL

**type** `string`

The client type: `web`, `ios`, or `android`

**user\_agent** `string`

The user agent string

**title** `string`

The page title

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

> [!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.

## Response

**cohorts** `array of strings`

All contextual cohort codes for the page. This is the complete list of cohorts that matched.

**activations** `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.

**contextual\_data** `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.

## Example Request

```bash cURL theme={"dark"}
curl -X POST "https://api.permutive.app/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.app/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.app/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
        }
    })
```

## Example Response

```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"
}
```

## Implementation Notes

> [accordion] 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] 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] 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.

## Related

> [card] [Activating in Google Ad Manager](https://docs.permutive.com/guides/signals/cohorts/contextual/deploying-to-google-ad-manager.md)
>
> Full implementation guide with code samples for Google Ad Manager.

> [card] [API Introduction](https://docs.permutive.com/api/contextual/introduction.md)
>
> Overview of the Contextual API.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.