# AdMedia sync API

HTTP contract the DSP uses when it provisions advertisers and syncs campaigns, creatives, lists, pixels, billing, and reports to AdMedia.

Source of truth in code:

- Client: `src/modules/admedia-api/admedia-api.client.ts`
- Bodies: `src/modules/admedia-api/admedia-api.types.ts`
- Payloads the sync service builds: `src/modules/admedia-entity-sync/`
- Advertiser create and profile patch: `src/modules/admedia-provision/`

The pages under [docs/api](api/README.md) are the broader Advertisers API catalog. This file is the subset the DSP client calls, with the JSON it sends and the JSON it reads.

How those calls are ordered, and what each side stores, is in [AdCenter sync flow](admedia-sync-flow.md) and [AdCenter data flow](admedia-sync-data-flow.md).

The 27–29 Oct payment and budget changes are in [Recent payment and budget changes](admedia-billing-context.md).

## Transport

| Setting      | Value                                                             |
| ------------ | ----------------------------------------------------------------- |
| Base URL     | `ADMEDIA_API_BASE_URL`, default `https://apiad.admedia.com/v1`    |
| Content type | `application/json` when a body is sent                            |
| Accept       | `application/json`                                                |
| Timeout      | 30 seconds. A timeout becomes `AdmediaApiError` with status `504` |

Paths below are relative to the base URL. A trailing slash on the base URL is normalized.

Any HTTP 2xx is success. The client does not require a specific success code such as `201` or `204`.

### Auth

Two modes. Do not mix them on one request.

| Calls                                                  | Header                                                                                                                           |
| ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------- |
| Advertiser admin: create, get, update, budget, billing | `Authorization: Basic` from `ADMEDIA_API_BASIC_USER` and `ADMEDIA_API_BASIC_PASSWORD`. Required when `ADMIN_SYNC_ENABLED` is on. |
| Campaigns, creatives, lists, pixels, channels, reports | `X-API-KEY` of the linked advertiser.                                                                                            |

An `Authorization` header on a report request switches AdMedia into admin impersonation and rejects the advertiser key. Report calls send `X-API-KEY` only.

The advertiser key comes from the local provision row. If it is missing, sync loads it with `GET advertisers/{adv_id}` and stores `api_key`.

### Errors

AdMedia error bodies are `{ "message": "..." }` when a message is present. The client uses that string.

| HTTP status   | Thrown as                                              |
| ------------- | ------------------------------------------------------ |
| 400           | `BadRequestError`                                      |
| 404           | `NotFoundError`                                        |
| 405           | `UnprocessableError` (AdMedia uses 405 for validation) |
| 422           | `UnprocessableError`                                   |
| other non-2xx | `AdmediaApiError` with that status and the raw body    |

Advertiser admin calls also fail when the HTTP status is 2xx but the body has `"status": false`. That becomes `AdmediaApiError` with status `422` and `message` from the body. A known create failure is:

```json
{
  "status": false,
  "message": "Username already exists. Please use a different Username."
}
```

Create calls that must return a resource id (`campaigns`, `creatives`, `lists/*`, `pixels/retargeting`) read `id` as a number or a numeric string. A body without `id` is `AdmediaApiError` with status `502`.

## Advertisers

Basic auth. Sync does not send `X-API-KEY` on these routes.

### POST /advertisers

Creates the AdMedia advertiser during DSP signup.

Request:

```json
{
  "accountid": "acme",
  "passclr": "generated-password",
  "firstname": "Ada",
  "lastname": "Lovelace",
  "company": "acme",
  "address1": "1 Market St",
  "address2": "",
  "city": "San Francisco",
  "state": "CA",
  "country": "US",
  "zipcode": "94105",
  "phone": "4155550100",
  "fax": "",
  "website": "https://acme.example",
  "email": "ada@acme.example",
  "account_type": "IO"
}
```

`accountid` and `company` are the trimmed DSP company name. An empty company name becomes `dsp{dspAdvertiserId}`. If that username already exists, signup retries as `{company}-{dspAdvertiserId}`. Empty address fields are sent as `""`. `account_type` is always `IO`.

`creation`, `admin_type`, and `status` exist on the provision input and are not sent on this request.

Response. `adv_id` and `api_key` are required; a body missing either fails the provision.

```json
{
  "status": true,
  "adv_id": 1001,
  "api_key": "advertiser-api-key"
}
```

| Field   | Type    | Notes                                               |
| ------- | ------- | --------------------------------------------------- |
| status  | boolean | `false` is a failed create                          |
| adv_id  | number  | Stored as `admedia_adv_id`                          |
| api_key | string  | Stored as `admedia_api_key` and used as `X-API-KEY` |
| message | string  | Present on failure                                  |

### GET /advertisers/{adv_id}

Loads the advertiser, including the API key when the local copy is missing.

Response. All fields are optional. An empty body is treated as `{}`.

```json
{
  "status": true,
  "adv_id": 1001,
  "api_key": "advertiser-api-key",
  "accountid": "acme",
  "firstname": "Ada",
  "lastname": "Lovelace",
  "company": "acme",
  "address1": "1 Market St",
  "address2": "",
  "city": "San Francisco",
  "state": "CA",
  "country": "US",
  "zipcode": "94105",
  "phone": "4155550100",
  "fax": "",
  "website": "https://acme.example",
  "email": "ada@acme.example",
  "account_type": "IO",
  "message": "optional"
}
```

### PATCH /advertisers/{adv_id}

Profile address sync. Omitted fields stay unchanged. The success body is ignored unless `status` is `false`.

Request. Only fields the DSP profile change includes are sent. `updated_by` is `dsp` whenever any field is present.

```json
{
  "address1": "1 Market St",
  "city": "San Francisco",
  "state": "CA",
  "country": "US",
  "zipcode": "94105",
  "phone": "4155550100",
  "website": "https://acme.example",
  "updated_by": "dsp"
}
```

Allowed fields: `firstname`, `lastname`, `company`, `address1`, `address2`, `city`, `state`, `country`, `zipcode`, `phone`, `fax`, `website`, `email`, `account_type`, `updated_by`.

### GET /advertisers/{adv_id}/budget

Current delivery balance. The client exposes this; entity sync funds delivery through the adjustment call below.

```json
{
  "status": true,
  "adv_id": 1001,
  "advertiser": "acme",
  "budget": "150.00",
  "last_update": "2026-10-30 12:00:00",
  "message": "optional"
}
```

`adv_id` and `advertiser` may be a number or a string. `budget` may be a two-decimal string or a JSON number.

### POST /advertisers/{adv_id}/billing/credits

Records a billing credit. This does not fund ad delivery. Delivery spends `Advertiser_budget`, which the adjustment call changes.

Request. `amount` is a two-decimal dollar string.

```json
{
  "amount": "50.00",
  "comment": "dsp-payment-42"
}
```

Response:

```json
{
  "status": true,
  "adv_id": 1001,
  "advertiser": "acme",
  "amount": "50.00",
  "comment": "dsp-payment-42",
  "message": "optional"
}
```

`amount` may come back as a number or a string.

Comment values sync sends:

| Event                             | comment                              |
| --------------------------------- | ------------------------------------ |
| Paid wallet payment               | `dsp-payment-{paymentId}`            |
| Search-text line item card charge | `dsp-line-item-funding-{lineItemId}` |

A payment credit and a line-item funding credit are each followed by a budget credit with the same `amount` and `comment`.

### POST /advertisers/{adv_id}/billing/adjustments

Changes the delivery budget.

Request. `amount` is a two-decimal dollar string. `direction` is `credit` or `debit`.

```json
{
  "amount": "12.50",
  "direction": "debit",
  "comment": "dsp-line-item-rollover-88"
}
```

Response:

```json
{
  "status": true,
  "adv_id": 1001,
  "advertiser": "acme",
  "budget": "137.50",
  "applied_amount": "12.50",
  "clamped": false,
  "amount": "12.50",
  "direction": "debit",
  "comment": "dsp-line-item-rollover-88",
  "last_update": "2026-10-30 12:00:00",
  "message": "optional"
}
```

`budget`, `amount`, `applied_amount`, and `clamped` may arrive as booleans, numbers, or strings. Sync treats `clamped === true` as a successful call and logs a warning. A debit that would pass zero is clamped at zero.

Rollover uses this call only. The net is overspend minus unspent budget. A positive net is `credit`; a negative net is `debit`. A net that formats as `0.00` is not posted. Comment: `dsp-line-item-rollover-{lineItemId}`.

## Campaigns

`X-API-KEY`. Create and update use the same body. Delete has no body. Update and delete ignore the success body.

A new campaign is created, then immediately updated with the same body. Create does not persist frequency (`freq_cap`); the follow-up update stores it, including `0` for unlimited.

### POST /campaigns

### PATCH /campaigns/{campaignId}

Request:

```json
{
  "name": "Spring search",
  "type": "text-search",
  "bid": 0.35,
  "budget": 100,
  "status": "A",
  "start_date": "2026-10-01",
  "end_date": "2026-10-31",
  "creatives": [501, 502],
  "targeting": {
    "countries": ["USA"],
    "states": ["CA"],
    "cities": ["San Francisco"],
    "zip": ["94105"],
    "metro": ["807"],
    "exclude": {
      "countries": ["CAN"],
      "states": ["NY"]
    },
    "devices": ["desktop", "phone"],
    "browsers": ["chrome"],
    "os": ["macos"],
    "connection_types": ["wifi"],
    "supplies": ["web"],
    "frequency": 3,
    "frequency_interval": "day",
    "frequency_time_val": 1,
    "pacing": 1,
    "keyword_lists": { "include": [11], "exclude": [12] },
    "domain_lists": { "include": [21], "exclude": [22] },
    "channel": 7,
    "source_lists": [31],
    "retargeting": { "logic": "or", "ids": [41] }
  }
}
```

| Field                | Type     | Sync value                                                                                                   |
| -------------------- | -------- | ------------------------------------------------------------------------------------------------------------ |
| name                 | string   | Line item name                                                                                               |
| type                 | string   | `text-search` or `display`. Also valid on the API: `native`, `text-pop`, `smedia`. Sync does not send those. |
| bid                  | number   | Line item bid                                                                                                |
| budget               | number   | Line item budget                                                                                             |
| status               | string   | `A` active, `S` paused. `C` is capped and is not sent. Paused, archived, and completed line items send `S`.  |
| start_date, end_date | string   | `YYYY-MM-DD`. A missing end date uses the start date.                                                        |
| creatives            | number[] | Remote creative ids already created for this line item                                                       |
| targeting            | object   | Omitted when empty, except `frequency` is always set when targeting is sent                                  |

Create response. Only `id` is read.

```json
{ "id": 9001 }
```

When a linked line item should no longer stay live, sync `PATCH`es the campaign without `creatives` or `targeting` and with `status: "S"`, then pauses each linked creative.

### Targeting values sync sends

Countries are alpha-3 (`USA`). Alpha-2 codes and English country names are converted before send. States are uppercased 2–3 character codes. DMA ids `1`–`999` are zero-padded to three digits (`807`). Excluded geo is nested under `targeting.exclude` with the same keys: `countries`, `states`, `cities`, `zip`, `metro`.

`frequency` is always present on a targeting object. A positive integer is the cap. `0` clears the cap (unlimited). Omitting `frequency` leaves the remote cap unchanged, which is why create is followed by an update. `frequency_interval` and `frequency_time_val` are sent only when the line item has them.

`pacing` is `1` for pace evenly and `0` for spend as soon as possible.

| DSP value                        | AdMedia value                             |
| -------------------------------- | ----------------------------------------- |
| DESKTOP / MOBILE / TABLET / CTV  | `desktop` / `phone` / `tablet` / `others` |
| CHROME / SAFARI / FIREFOX / EDGE | `chrome` / `safari` / `firefox` / `msie`  |
| OTHER (browser)                  | `opera` and `unknown`                     |
| WINDOWS / MACOS / IOS / ANDROID  | `windows` / `macos` / `ios` / `android`   |
| WIFI / CELLULAR                  | `wifi` / `cellular`                       |
| WEB / APP / CTV (environment)    | `web` / `app` / `app`                     |

`keyword_lists.include` is search lists. `keyword_lists.exclude` is negative lists. `domain_lists.include` is allow lists. `domain_lists.exclude` is block lists. `source_lists` is a flat array of remote source-list ids. `channel` is an id from `GET /channels`. `retargeting.logic` defaults to `or`. `retargeting.ids` are remote pixel ids that are already linked; campaign sync does not create pixels.

Other targeting fields the campaign type accepts, and that the client type allows, are not filled by sync today: `categories`, `makers`, `models`, `ron`, `schedule`.

### DELETE /campaigns/{campaignId}

No body. Success body is ignored. The client implements this call. Entity sync does not use it; a line item that should stop serving is paused with `status: "S"`.

## Creatives

`X-API-KEY`. Create returns `{ "id": number }`. Update ignores the success body.

Sync sends `type: "text"` for search-text creatives and `type: "image"` for display creatives. `status` is `A` while the line item is allowed to serve, and `S` when it is paused or no longer maintained. The API also accepts `script` and `native`; sync does not send those.

### POST /creatives

### PATCH /creatives/{creativeId}

Text:

```json
{
  "name": "Headline A",
  "type": "text",
  "destination": "https://acme.example/landing",
  "title": "Headline A",
  "description": "Ad description",
  "display_url": "acme.example",
  "status": "A"
}
```

Image. `size` is `{width}x{height}`. `image_url` is the public asset URL.

```json
{
  "name": "300x250",
  "type": "image",
  "destination": "https://acme.example/landing",
  "image_url": "https://cdn.example/creative.png",
  "size": "300x250",
  "status": "A"
}
```

A pause update may send only `name`, `type`, and `status`.

## Keyword lists

`X-API-KEY`. Name is truncated to 100 characters. Sync always sends `type: "broad"`. `bid` is the line item bid when that bid is at least `0.007`; otherwise `0.007`.

### POST /lists/keywords

### PATCH /lists/keywords/{listId}

```json
{
  "name": "Brand terms",
  "type": "broad",
  "bid": 0.35,
  "keywords": ["running shoes", "trail shoes"]
}
```

Create response: `{ "id": 11 }`.

### DELETE /lists/keywords/{listId}

Sent when the DSP list is archived and a remote id exists. No body.

## Domain lists

`X-API-KEY`. Name is truncated to 100 characters.

### POST /lists/domains

### PATCH /lists/domains/{listId}

```json
{
  "name": "News sites",
  "domains": ["example.com", "news.example"]
}
```

Create response: `{ "id": 21 }`.

### DELETE /lists/domains/{listId}

Sent when the DSP list is archived and a remote id exists. No body.

## Source lists

`X-API-KEY`. Name is truncated to 100 characters.

The dev API expects `source_id`. The published schema uses `source`. The client sends both, with the same source id, on every create and update.

### POST /lists/sources

### PATCH /lists/sources/{listId}

Request on the wire:

```json
{
  "name": "Search sources",
  "sources": [
    { "source": 448, "source_id": 448, "bid": 0.2 },
    { "source": 449, "source_id": 449, "bid": 0 }
  ]
}
```

A source with `bid` `0` is excluded by AdMedia. Create response: `{ "id": 31 }`.

### DELETE /lists/sources/{listId}

Sent when the DSP list is archived and a remote id exists. No body.

## Retargeting pixels

`X-API-KEY`. Pixel create happens when a DSP pixel is created, not during campaign sync. Campaign sync only attaches pixels that already have a remote id.

### POST /pixels/retargeting

```json
{ "name": "Site visitors" }
```

Response: `{ "id": 41 }`.

### GET /pixels/retargeting/{pixelId}

Called immediately after create so the DSP can store the tag.

```json
{
  "id": 41,
  "name": "Site visitors",
  "tag": "<script>...</script>"
}
```

`name` and `tag` are optional on the type. A missing `tag` is stored as an empty string. A missing `name` falls back to the name that was posted.

## Channels

### GET /channels

`X-API-KEY`. Used to resolve `targeting.channel` for text-search campaigns.

```json
[{ "id": 7, "name": "Search" }]
```

## Reports

`X-API-KEY` only. No `Authorization` header. Query values are sent as strings.

Calls the DSP makes:

| Caller                  | Method and path                       | Query                                                  |
| ----------------------- | ------------------------------------- | ------------------------------------------------------ |
| Dashboard pull          | `GET /reports`                        | `from`, `to` (`YYYY-MM-DD`), `format=campaigns,hourly` |
| Dashboard pull fallback | `GET /reports/campaigns`              | `from`, `to`, `format=daily`                           |
| Final spend capture     | `GET /reports/campaigns/{campaignId}` | `from`, `to`                                           |
| Reports proxy           | `GET` the path the caller passes      | `from`, `to`                                           |

The hourly bulk path is `GET /reports?format=campaigns,hourly`. `campaigns/{id}/hourly` rejects `hourly`. A `400`, `404`, or `422` from the hourly call falls back to the daily campaigns report.

No delivery is an empty array:

```json
[]
```

A delivery row may be the response itself, an array of rows, or `{ "data": <row or rows> }`. Field names the parsers accept:

| Meaning        | Accepted keys                                           |
| -------------- | ------------------------------------------------------- |
| Impressions    | `impressions`, `impression`, `imps`, `views`            |
| Clicks         | `clicks`, `click`                                       |
| Spend, dollars | `spent`, `spend`, `cost`                                |
| Conversions    | `conversions`, `conversion`, `leads`, `actions`         |
| Campaign id    | `campaign_id`, `campaignId`, `campaignid`               |
| Day            | `date`, `stat_date`, `day` (`YYYY-MM-DD` or `M/D/YYYY`) |
| Hour           | `hour`, `hr` (Pacific clock hour, 0–23)                 |

Numbers may be JSON numbers or numeric strings. Spend strings may include `$` and commas. Dashboard rows must include impressions, clicks, and spend. Conversions default to `0` when absent. Final spend reads `spent` only, on the object or on `data`, and treats `[]` or `{ "data": [] }` as `0`.

Example hourly row:

```json
[
  {
    "campaign_id": 9001,
    "date": "2026-10-30",
    "hour": 15,
    "impressions": 1200,
    "clicks": 14,
    "spent": "3.50",
    "conversions": 1
  }
]
```

Example single-campaign spend used by final spend capture:

```json
{ "spent": 18.25 }
```
