> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.pivolio.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.pivolio.com/_mcp/server.

# Record a consent decision

POST /consent
Content-Type: application/json

Records a visitor's consent decision without an event, and returns the
consent now in force for them.

Applied immediately rather than queued: a withdrawal has to bind the next
delivery. It is not billed as an event, and it is never forwarded to a
destination — it decides what may be.

Resolving identity inline means a call whose identifiers span two persons merges
them, taking the workspace-scoped merge lock on the request path. Measured at
~6ms against ~2ms without, so roughly 4ms of lock hold, and only on the call that
first links two identities — the enricher takes the same lock on every merge at
far higher volume, so this is a rounding error on that contention rather than a
new bottleneck. Recording on each matched person instead would avoid the lock,
at the cost of a second resolution mode in ``IdentityResolver``; not worth it
until the lock actually shows up in production.

Reference: https://docs.pivolio.com/api-reference/pivolio/event-ingestion/record-consent

## Authentication

- `X-Write-Key` header (required) — API Key authentication via header

## Request

### Body (application/json)

This endpoint expects a ConsentRequest.

- `identity` (EventIdentity, required) — Who the decision belongs to
- `consent` (Consent, required) — The categories being answered
- `traits` (Traits, optional, nullable) — Identifying traits (email, phone)
- `timestamp` (double, optional, nullable) — When the decision was made (Unix seconds). Defaults to now; a time in the future is clamped to now.

## Response

### 200

Successful Response

- `consent` (Consent, required) — Google Consent Mode v2. A category is ``granted``, ``denied``, or absent — and absent is a real third state that ``ConsentWhenAbsent`` decides, not a synonym for either answer. Semantics live in ``pivolio.consent``.
- `ok` (boolean, optional, default: true)

## Errors

### 422 Unprocessable Entity Error

Validation Error

- `detail` (string, required)
- `code` (string, required)
- `errors` (list of FieldError, optional, nullable)

## Types

### EventIdentity

Who the event belongs to, as the caller knows them. All three are opaque identifiers, not PII — the PII the caller sends lives in ``traits``. ``user_id`` and ``external_id`` are near-twins that differ by direction: ``user_id`` is *inbound*, stitching a person across sessions and devices (it is the only field that marks one identified), while ``external_id`` is *outbound*, shipped to the ad platforms as their match key. They are usually the same value, and a caller who does not want its internal user id sent to Meta supplies a pseudonymous ``external_id`` instead.

- `anonymous_id` (string, required) — Anonymous visitor ID
- `user_id` (string, optional, nullable) — Known user ID after identify
- `external_id` (string, optional, nullable) — Stable user key sent to ad platforms as their match id

### Consent

Google Consent Mode v2. A category is ``granted``, ``denied``, or absent — and absent is a real third state that ``ConsentWhenAbsent`` decides, not a synonym for either answer. Semantics live in ``pivolio.consent``.

- `ad_storage` (enum, optional, nullable) — GDPR/Privacy consent states.
  - Allowed values: `granted`, `denied`
- `analytics_storage` (enum, optional, nullable) — GDPR/Privacy consent states.
  - Allowed values: `granted`, `denied`
- `ad_user_data` (enum, optional, nullable) — GDPR/Privacy consent states.
  - Allowed values: `granted`, `denied`
- `ad_personalization` (enum, optional, nullable) — GDPR/Privacy consent states.
  - Allowed values: `granted`, `denied`

### Traits

User attributes carried on an event (raw PII, hashed server-side before any delivery). Well-known match keys are typed; any extra custom attributes are preserved (`extra="allow"`) and merged onto the person record. PII only — opaque identifiers belong in ``identity``, which is what keeps this bag exactly the set of values that get hashed and excluded from ClickHouse.

- `email` (string, optional, nullable)
- `phone` (string, optional, nullable)
- `first_name` (string, optional, nullable)
- `last_name` (string, optional, nullable)
- `country` (string, optional, nullable)
- `city` (string, optional, nullable)
- `state` (string, optional, nullable)
- `zip` (string, optional, nullable)
- `gender` (string, optional, nullable)
- `date_of_birth` (string, optional, nullable)

### FieldError

- `field` (string, required)
- `message` (string, required)

## Examples

**Request**

```json
{
  "identity": {
    "anonymous_id": "anon-1234567890abcdef"
  }
}
```

**Response**

```json
{
  "consent": {
    "ad_storage": "granted",
    "analytics_storage": "granted",
    "ad_user_data": "granted",
    "ad_personalization": "granted"
  },
  "ok": true
}
```

**SDK Code**

```python
import requests

url = "https://api.example.com/consent"

payload = { "identity": { "anonymous_id": "anon-1234567890abcdef" } }
headers = {
    "X-Write-Key": "<apiKey>",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript
const url = 'https://api.example.com/consent';
const options = {
  method: 'POST',
  headers: {'X-Write-Key': '<apiKey>', 'Content-Type': 'application/json'},
  body: '{"identity":{"anonymous_id":"anon-1234567890abcdef"}}'
};

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://api.example.com/consent"

	payload := strings.NewReader("{\n  \"identity\": {\n    \"anonymous_id\": \"anon-1234567890abcdef\"\n  }\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("X-Write-Key", "<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://api.example.com/consent")

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

request = Net::HTTP::Post.new(url)
request["X-Write-Key"] = '<apiKey>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"identity\": {\n    \"anonymous_id\": \"anon-1234567890abcdef\"\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.post("https://api.example.com/consent")
  .header("X-Write-Key", "<apiKey>")
  .header("Content-Type", "application/json")
  .body("{\n  \"identity\": {\n    \"anonymous_id\": \"anon-1234567890abcdef\"\n  }\n}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.example.com/consent', [
  'body' => '{
  "identity": {
    "anonymous_id": "anon-1234567890abcdef"
  }
}',
  'headers' => [
    'Content-Type' => 'application/json',
    'X-Write-Key' => '<apiKey>',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://api.example.com/consent");
var request = new RestRequest(Method.POST);
request.AddHeader("X-Write-Key", "<apiKey>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"identity\": {\n    \"anonymous_id\": \"anon-1234567890abcdef\"\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "X-Write-Key": "<apiKey>",
  "Content-Type": "application/json"
]
let parameters = ["identity": ["anonymous_id": "anon-1234567890abcdef"]] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.example.com/consent")! 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()
```