# Commit a proposal Source: https://api-docs.usegrade.com/agent/commit agent/openapi.json POST /sdk/v1/agent/commit Saves what a person confirmed: send the `proposal_token` of the assistant's `action` event, unchanged. Grade calls the SDK v1 routes the proposal stands for with your key, so each route applies its own scopes, rules and audit. A second commit of the same proposal answers the first receipt. **Beta.** The assistant API and its reads over MCP are in beta. They are open to every organization that pays out through Grade, and parts are not available yet, as each page says. > [!WARNING] > > Sending the same token again never writes twice: a finished commit answers its first receipt. After > `504` `COMMIT_OUTCOME_UNKNOWN` the first route may have written: check the outcome in Grade, and never > ask the assistant for a new proposal to recover it, since a new proposal is a new write. A proposal > can be committed for 24 hours after the assistant made it. # Reads over MCP Source: https://api-docs.usegrade.com/agent/mcp Let your own model, or Claude, read your organization's data through the assistant's reads. **Beta.** The assistant API and its reads over MCP are in beta. They are open to every organization that pays out through Grade, and parts are not available yet, as each page says. The assistant's reads are also an MCP server. A model you run can call them as tools, and a person can connect Claude to them with their own Grade sign-in. Nothing on this server changes data. Its URL is `https://mcp.usegrade.com/mcp`. People in your organization also find it in Grade, under **Account settings → AI agents**, and on the **Developer** page, beside the API base URL. During the beta, every other organization is refused with `403`, and where the server is off it answers `404`. ## Your own model Mint an agent token on your backend, as for a question ([Quickstart](/agent/overview#quickstart)), and send it as the bearer: | Header | Value | | - | - | | `Authorization` | `Bearer ` | | `Content-Type` | `application/json` | | `Accept` | `application/json, text/event-stream` | With Claude's [MCP connector](https://platform.claude.com/docs/en/agents-and-tools/mcp-connector), pass the server and the token with each request: ```bash theme={null} curl https://api.anthropic.com/v1/messages \ -H "Content-Type: application/json" \ -H "X-API-Key: $ANTHROPIC_API_KEY" \ -H "anthropic-version: 2023-06-01" \ -H "anthropic-beta: mcp-client-2025-11-20" \ -d '{ "model": "claude-sonnet-5-5", "max_tokens": 1024, "messages": [{ "role": "user", "content": "Which campaigns started this month?" }], "mcp_servers": [ { "type": "url", "url": "https:///mcp", "name": "grade", "authorization_token": "" } ], "tools": [{ "type": "mcp_toolset", "mcp_server_name": "grade" }] }' ``` Your model calls the reads it needs, on your key and at your cost. Grade keeps only which read was called and how it ended; your model's conversation never reaches Grade. The token lasts 15 minutes: mint another when it runs out, and keep it on your backend. ## Claude, for a person A person connects Claude with their own Grade sign-in, and no SDK key is involved. Claude then reads as that person, within what their role reaches, for up to 30 days, and they can disconnect it in **Account settings → AI agents**. The steps, with screenshots, are in the [Help Center](https://usegrade.com/v2/help#connect-ai-apps). ChatGPT comes later. ## What it lists The assistant's own reads, within the token's scopes: see [Reads](/agent/overview#reads). Each answers at most 20 rows, with the full count. Actions are never listed: a change goes through the assistant, as a proposal a person confirms. ## The protocol Streamable HTTP without sessions, answered in JSON: one JSON-RPC message per `POST`, in the protocol revisions `2025-11-25`, `2025-06-18` and `2025-03-26`. A read that fails comes back as a tool result with `isError: true` and a sentence your model can act on. ## Refusals | Status | Code | Meaning | | - | - | - | | `401` | | No token, or one that does not verify or ran out. Mint another. A person's token from Grade is refused too: this server takes an application's. | | `401` | `session_expired` | The token ran out while Grade was answering. Mint another. | | `403` | `refused_access` | The server is not open to your organization (it opens to organizations that pay out through Grade), the key's scopes reach no read, or the person left your organization. | | `403` | `origin_refused` | A browser page on another origin sent the request. | | `404` | | The server is off on this environment. | | `429` | `rate_limited` | Over your application's share this minute. Wait as long as `Retry-After` says. | | `503` | `paused`, `AGENT_UNCONFIGURED` | The assistant is paused, off for your organization, or not configured on Grade's side. | # Assistant API Source: https://api-docs.usegrade.com/agent/overview Put the Grade assistant in your own product, with four calls from your backend. **Beta.** The assistant API and its reads over MCP are in beta. They are open to every organization that pays out through Grade, and parts are not available yet, as each page says. The assistant API puts the assistant your team uses in Grade inside your own product. It reads your organization's data, answers in words, and prepares changes as proposals. Nothing is written until a person confirms a proposal and your backend commits it. Your backend holds every key and talks to Grade. Your interface talks only to your backend. ```mermaid theme={null} sequenceDiagram participant B as Your backend participant G as Grade API participant A as Grade assistant participant P as The person B->>G: POST /sdk/v1/agent/token, with the SDK key G-->>B: Agent token, valid for 15 minutes B->>A: POST /v2/api/agent, with the token and your model key A-->>B: The answer as it is written, then a proposal B->>P: Shows the answer and the confirmation P->>B: Confirms B->>G: POST /sdk/v1/agent/commit, with the proposal_token G-->>B: Receipt ``` ## Quickstart **1. Give your SDK key the Assistant access** In Grade, open **Developer**, then your application, and edit its key. **Full access** includes the assistant. With **Custom**, set **Assistant** to read and keep read access to the areas you want answers about. Existing keys don't get it on their own. **2. Mint an agent token** ```bash theme={null} curl -sS "$BASE_URL/sdk/v1/agent/token" \ -X POST \ -H "Content-Type: application/json" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" \ -d '{ "end_user": "user_8f3a2c" }' ``` `end_user` is your own id for the person asking: 1–128 letters, digits, `_` or `-`, never an email. The token lasts 15 minutes. Keep one per person and reuse it until shortly before `expires_at`. **3. Ask the assistant** The assistant's URL is `https://app.usegrade.com/v2/api/agent`. Send your model's id and your key for its provider: ```bash theme={null} curl -sS -N "$AGENT_URL" \ -X POST \ -H "Authorization: Bearer $AGENT_TOKEN" \ -H "x-model: claude-sonnet-5-5" \ -H "x-model-key: $MODEL_KEY" \ -H "Content-Type: application/json" \ -H "Accept: text/event-stream" \ -d '{ "messages": [{ "role": "user", "content": "Which campaigns still need payment terms?" }], "app_events": [], "prior_run_id": null, "formats": ["text", "card"] }' ``` Append each `text` event's `delta` to the answer. An `action` event is a proposal: show its `text` beside a confirm button, and keep its `proposal_token`. On Grade's development environment, also send the `cf-access-token` header Grade gives you for it. See [Ask the assistant](/agent/stream). **4. Commit what the person confirms** ```bash theme={null} curl -sS "$BASE_URL/sdk/v1/agent/commit" \ -X POST \ -H "Content-Type: application/json" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" \ -d '{ "proposal_token": "" }' ``` The answer is a receipt, `saved`, `partial` or `refused`, with one row per creator or post. Only this call writes, after a person confirms: a "yes" typed in the conversation never commits. Read [Commit a proposal](/agent/commit) before you retry one. > [!WARNING] > > Keep the SDK key, the agent token and the model key on your backend: never in a browser, a mobile > app or a log. An agent token reads your organization's data within its scopes until it expires. Notes for an AI agent writing an integration from these pages: * Keep the SDK key, the agent token and the model key on the backend. Never put them in a browser, a mobile app or a log. * Nothing is written until the backend sends `proposal_token` to `POST /sdk/v1/agent/commit` after a person confirms. A "yes" typed in the conversation is not a confirmation. * The assistant API offers no action that moves money. A payment an AI starts in Grade is only ever a proposal that a person approves in Grade, with two-factor authentication. ## What it can do A key needs `agent:read`, shown as **Assistant**, to mint a token and to commit. Its other scopes decide what the assistant offers. A read needs the read scope of the routes it calls. An action needs its write scope and the read scopes of what it reads first, since `write` does not imply `read`. A key whose scopes reach no read and no action is refused with `403` `refused_access`. Scopes are copied into the token, so a change applies from the next one. ### Reads | Read | What it returns | Scope | | - | - | - | | `search_campaigns` | Campaigns the person can see whose name contains every word given, with each one's status, start day, lifetime views and the day they were counted, and how many creators its roster lists (hidden creators aside, as the Campaigns list counts them). | `campaigns:read` | | `search_creators` | Creators of the organization whose name or email contains the words, or with a campaign only the creators on it: "who is on this campaign" is one call, and total\_matching counts them all. | `campaigns:read` | | `get_campaign` | One campaign: its status, days, time zone, how many creators (hidden and in a test phase among them), posts and views. | `campaigns:read` | | `list_campaign_dues` | What each campaign owes its creators now, per currency and before the platform fee: the fixed, CPM and bonus amounts pending, the pending manual bonuses (paid apart from the rest), and how many creators a payment now would leave out and why (hidden, in a test phase, awaiting approval, no email). | `payouts:read` | | `list_due_now` | What each campaign owes its creators now, one row per campaign and currency, before the platform fee: the amount due, how many creators it is for, and the day it was calculated. | `payouts:read` | | `explain_creator_payment` | Why one creator in one campaign is or is not paid: what is payable now (fixed, CPM, bonus, manual bonus), what is not and the reason code of each line, when a held line becomes payable, the calculation's state and the reason codes behind it, why the creator would be left out of a payment, and the creator's posts with each one's payment status and reasons. | `payouts:read` | | `search_posts` | Finds the post behind a link the person pasted: its campaign, creator and post ids for explain\_creator\_payment. | `campaigns:read` | | `search_payouts` | Payouts the person can see (for a Campaign Manager, only those of their campaigns), newest first, filtered by creator, campaign, payout references, phase and sent days. | `payouts:read` | | `list_top_posts` | Posts ranked by a metric, highest first: one campaign's posts, or, with campaign\_id empty, every post the organization tracks, in any campaign or none (for a Campaign Manager, the posts on their campaigns only). | `analytics:read` | | `get_creator_terms` | One creator's payment terms and their history, per campaign. | `campaigns:read` | | `list_creators_by_terms` | Creators on the campaigns the person can see, or on one campaign, by their payment terms: "who has no payment terms" is terms "none", and total\_matching counts every match. | `campaigns:read` | | `list_campaigns_needing_setup` | The campaigns the person can see whose setup is not done, as each campaign's page asks under "Set up this campaign": creators without payment terms (nothing can be paid until they are set), then creators without posts tracked. | `campaigns:read` | | `list_payment_templates` | The organization's payment terms templates, newest first, as the payment terms editor's Templates list shows them: each one's name, whether it is the default, its terms in the editor's words, and how many creators on the campaigns the person can see are on it. | `campaigns:read` | | `get_approval` | One payout approval request: its campaign, creator, amount, status and who submitted it. | `approvals:read` | | `list_pending_approvals` | Payout requests waiting for an Admin or Finance decision, newest first, as the Approvals page lists them: each one's campaign, creator, the debit approving it takes from the wallet, the day it was requested and how many days it has waited. | `approvals:read` | | `list_approval_history` | Payout requests already decided, newest decision first, as the Approvals page lists them: each one's campaign, creator, the debit approving it took or would have taken from the wallet, its status (approved, denied or cancelled), the day it was requested, and the day it was decided and by whom. | `approvals:read` | | `check_wallet_against_dues` | Whether the organization's wallet covers what is due: the balance, and per currency the amount due, the platform fee the organization pays and the debit in USD at today's rate, then what is needed in all and the shortfall. | `payouts:read` | | `get_payout_period` | Payouts sent between two UTC days, of one campaign or creator or all, grouped by campaign, creator, status or month, with each group's totals per currency and the whole period's totals, which are never cut: "how much did we pay per campaign this quarter" and "monthly spend this year" are one call each, and the totals are the answer, never the rows added up. | `payouts:read` | | `aggregate_performance` | Views, likes, comments and shares of the posts on the campaigns the person can see, with how many posts and creators, grouped by up to two of campaign, creator, platform and day, week or month (at most one of the last three), or not grouped: "views by platform last month", "which creators brought the most views across all campaigns", "weekly views of Summer Launch" and "posts per campaign this quarter" are one call each. total\_matching counts every group, and the whole set's totals (in prose) are never cut: they are the answer for any total, never the rows added up (a group's day never goes below zero on its own, so rows may not add up to the totals). | `analytics:read` | | `get_creator_overview` | One creator across the campaigns the person can see, by name or id, in one call: "how is Ana doing", "what do we owe Ana in all" and "what have we paid Ana" read here. | `payouts:read` | | `list_wallet_top_ups` | The organization's wallet top-ups, newest first: when each was made, how it was paid, its status, the top-up amount, the processing fee taken from it, the wallet credit, and when the money is or was available to pay with. | `payouts:read` | | `list_bounced_payout_emails` | Creators whose payout emails did not reach the email address Grade has for them now (the email bounced, failed or was rejected, or they marked it as spam or unsubscribed), most recent first: the creator, how many payout emails did not arrive, and the latest one's payout reference, day and what happened. | `payouts:read` | | `list_payout_disputes` | Payout disputes creators opened, as the Disputes tab of Payouts lists them, open ones first, then the oldest: each one's payout reference, its campaign (none for a Quick Pay payout), the creator, the reason (video\_missing, crosspost\_not\_counted, wrong\_amount or other), the status (open, resolved or rejected), whether the creator can still reopen a rejected one, since when the creator has waited for an answer, when Grade reminded the organization and when it escalated the dispute to Grade's team, the day it was opened and the day it was closed. | `disputes:read` | | `list_removed_posts` | One campaign's removed posts, the content taken off it with Remove content, that can still be restored, most recently removed first: each one's creator, platform, the day it went up, the day it was removed, and whether it sat in a cross-post group. | `campaigns:read` | | `list_campaign_posts` | One campaign's live posts, newest first: each one's creator, platform and the day it went up, whether its performance is frozen, and whether it counts toward CPM and bonuses and toward the fixed rate per post, or is excluded by its own setting or with its account. | `campaigns:read` | | `list_pay_cycles` | One creator's pay cycles on one campaign whose terms pay in recurring cycles, oldest first: each cycle's dates as the pay breakdown labels them, the amount due in it, and whether it is due, running (the cycle in progress, which can be waived only once it ends), awaiting approval (part of a payout awaiting approval) or waived, with why and when for a waived one. | `payouts:read` | | `list_earnings` | What one creator earned through recorded earnings, and what you agreed with them outside a campaign's payment terms. | `payouts:read` | | `get_earning` | One recorded earning in full: what it is for and what it covers, how it is calculated (the saved explanation and its steps), the evidence behind it (each source, its reference, when it was observed, whether it is complete and its notes; never the files themselves), the agreement version it was recorded under with that version's terms, Grade AI's check of the request (matches, changes or unclear, with its reason, the request and the differences), the amounts earned, paid, in progress and due, its approval and payout, and its history. | `payouts:read` | ### Actions Each action is offered when the key holds every scope listed (its write scope and the read scopes of what it reads first) and the action is on for your organization. Its commit calls the SDK v1 route listed, with your key. An action with no route is offered in words only: its confirmation comes with nothing to commit. | Action | What it does | Scope | Effect | SDK route | | - | - | - | - | - | | `prepare_tracking` Track links on a campaign | Proposes account or post links the person gave as tracking for one creator on one campaign. | `campaigns:write` + `campaigns:read` | Adds something that can be undone in Grade. | `POST /sdk/v1/campaigns/:id/creators/media` | | `prepare_tracked_media_add` Track links outside a campaign | Proposes account or post links the person gave for the organization's Tracking, outside any campaign. | `analytics:write` | Adds something that can be undone in Grade. | `POST /sdk/v1/analytics/tracked-media/bulk` | | `prepare_payment_terms` Set up payment terms | Proposes payment terms for one or more creators (up to 20) on one campaign. | `campaigns:write` + `campaigns:read` | Changes or removes something that may not be undoable. Read the confirmation with care. | None | | `prepare_campaign_complete` Complete a campaign | Proposes completing one open campaign, which stops its tracking and pending accrual and makes no new payouts from it until it is reopened. | `campaigns:write` + `campaigns:read` | Changes or removes something that may not be undoable. Read the confirmation with care. | `POST /sdk/v1/campaigns/:id/complete` | | `prepare_campaign_reopen` Reopen a campaign | Proposes reopening one closed campaign, which resumes its tracking and pending accrual under the creators' existing terms. | `campaigns:write` + `campaigns:read` | Changes or removes something that may not be undoable. Read the confirmation with care. | `POST /sdk/v1/campaigns/:id/reopen` | | `prepare_campaign_update` Edit a campaign | Proposes changing one campaign's title, description, start date, or its end date when it has one. | `campaigns:write` + `campaigns:read` | Changes or removes something that may not be undoable. Read the confirmation with care. | `PATCH /sdk/v1/campaigns/:id` | | `prepare_campaign_creators` Add creators to a campaign | Proposes creators of the organization to add to one campaign. | `campaigns:write` + `campaigns:read` | Adds something that can be undone in Grade. | `POST /sdk/v1/campaigns/:id/creators` | | `prepare_creator_removal` Remove creators from a campaign | Proposes creators to remove from one campaign. | `campaigns:write` + `campaigns:read` | Changes or removes something that may not be undoable. Read the confirmation with care. | `DELETE /sdk/v1/campaigns/:id/creators` | | `prepare_creator_hide` Hide a creator on a campaign | Proposes hiding one creator on one campaign: they stay on it but are left out of payouts due until unhidden. | `campaigns:write` + `campaigns:read` | Changes or removes something that may not be undoable. Read the confirmation with care. | `PATCH /sdk/v1/campaign-creators/:id/visibility` | | `prepare_creator_unhide` Unhide a creator on a campaign | Proposes unhiding one hidden creator on one campaign, which brings them back into the roster and payouts due. | `campaigns:write` + `campaigns:read` | Changes or removes something that may not be undoable. Read the confirmation with care. | `PATCH /sdk/v1/campaign-creators/:id/visibility` | | `prepare_creator_move` Move a creator to another campaign | Proposes moving one creator from one campaign to another open campaign, with their tracked accounts and posts, payouts, approvals and payment terms. | `campaigns:write` + `campaigns:read` | Changes or removes something that may not be undoable. Read the confirmation with care. | `POST /sdk/v1/campaign-creators/:id/move` | | `prepare_content_removal` Remove a post from a campaign | Proposes removing one post from a creator's content on one campaign. | `campaigns:write` + `campaigns:read` | Changes or removes something that may not be undoable. Read the confirmation with care. | `DELETE /sdk/v1/campaigns/:id/creators/media` | | `prepare_post_restore` Restore a removed post | Proposes restoring one removed post to its campaign, where it counts toward the creator's pay again. | `campaigns:write` + `campaigns:read` | Adds something that can be undone in Grade. | `POST /sdk/v1/campaign-media/:id/restore` | | `prepare_post_freeze` Freeze a post's performance | Proposes freezing one live post's performance on its campaign, so views it earns from now count toward neither CPM nor bonuses. | `campaigns:write` + `campaigns:read` | Changes or removes something that may not be undoable. Read the confirmation with care. | `POST /sdk/v1/campaign-media/:id/freeze-performance` | | `prepare_post_resume` Resume a post's performance | Proposes resuming one frozen post's performance on its campaign, so views it earns from now count again (those earned while it was frozen stay excluded). | `campaigns:write` + `campaigns:read` | Changes or removes something that may not be undoable. Read the confirmation with care. | `POST /sdk/v1/campaign-media/:id/unfreeze-performance` | | `prepare_post_exclude_performance` Exclude a post from CPM and bonuses | Proposes excluding one live post from CPM and bonuses on its campaign, so its views stop counting toward them. | `campaigns:write` + `campaigns:read` | Changes or removes something that may not be undoable. Read the confirmation with care. | `POST /sdk/v1/campaign-media/:id/exclude-performance` | | `prepare_post_include_performance` Include a post in CPM and bonuses | Proposes including one post excluded from CPM and bonuses on its campaign again, so its views count toward them again. | `campaigns:write` + `campaigns:read` | Changes or removes something that may not be undoable. Read the confirmation with care. | `POST /sdk/v1/campaign-media/:id/unexclude-performance` | | `prepare_post_exclude_fixed_rate` Exclude a post from the fixed rate | Proposes excluding one live post from the fixed rate per post on its campaign, so it stops earning it. | `campaigns:write` + `campaigns:read` | Changes or removes something that may not be undoable. Read the confirmation with care. | `POST /sdk/v1/campaign-media/:id/exclude-fixed-rate` | | `prepare_post_include_fixed_rate` Include a post in the fixed rate | Proposes including one post excluded from the fixed rate per post on its campaign again, so it earns it again. | `campaigns:write` + `campaigns:read` | Changes or removes something that may not be undoable. Read the confirmation with care. | `POST /sdk/v1/campaign-media/:id/unexclude-fixed-rate` | | `prepare_pay_bonus` Set a creator's pending bonus | Proposes setting one creator's pending manual bonus on one campaign to the amount the person said, in place of any pending one. | `payouts:write` + `campaigns:read` + `payouts:read` | Changes or removes something that may not be undoable. Read the confirmation with care. | `PUT /sdk/v1/campaign-creators/:id/pending-bonus` | | `prepare_pay_cycle_waive` Waive a creator's pay cycle | Proposes waiving one due pay cycle of one creator's recurring terms on one campaign, for the reason the person gave, so it stops being owed. | `payouts:write` + `campaigns:read` + `payouts:read` | Changes or removes something that may not be undoable. Read the confirmation with care. | `POST /sdk/v1/campaign-creators/:id/pay-cycle-windows/waive` | | `prepare_pay_cycle_restore` Restore a waived pay cycle | Proposes restoring one waived pay cycle of one creator on one campaign, so it is owed again. | `payouts:write` + `campaigns:read` + `payouts:read` | Changes or removes something that may not be undoable. Read the confirmation with care. | `POST /sdk/v1/campaign-creators/:id/pay-cycle-windows/restore` | Nothing that moves money is offered through the API: Quick Pay and paying payouts stay in Grade. ## Models | Model | `x-model` | Provider | Status | | - | - | - | - | | Claude Sonnet 5.5 | `claude-sonnet-5-5` | Anthropic | Certified | | GPT-6.1 Terra | `gpt-6.1-terra` | OpenAI | Being certified | | GPT-5.6 Terra | `gpt-5.6-terra` | OpenAI | Reserve, tried if GPT-6.1 Terra does not pass | Production serves only certified models: Grade runs its evaluation suite through the assistant with a model before it certifies it. During the beta, Grade's development environment also serves the OpenAI models as candidates. Your model key is used for its turn only and never stored, and your provider bills every question to your account. ## Limits | Limit | Value | | - | - | | Questions per end user | 30 in the last hour and 100 a UTC day | | Questions per application | 1,000 a UTC day, all end users together | | Commits per application | 60 a minute | | Creators or links per proposal | 20 | | One answer | 2 minutes, 6 model calls, about 150,000 input tokens per call, and an estimated US\$0.50 of model use | | Runs at a time | One per end user | A question over a limit gets a stream that ends at once with `budget_exhausted` and says when the limit opens again. A second question while one runs is refused with `409`, and a commit over the limit with `429`. # Ask the assistant Source: https://api-docs.usegrade.com/agent/stream The request, the events of the answer, and every refusal and ending. **Beta.** The assistant API and its reads over MCP are in beta. They are open to every organization that pays out through Grade, and parts are not available yet, as each page says. Each question is one `POST` to the assistant's URL, which ends in `/v2/api/agent`. Grade keeps no conversation for you: every request carries the history and the open proposals again. ## Headers | Header | Value | | - | - | | `Authorization` | `Bearer `, from [Mint an agent token](/agent/token). | | `x-model` | The id of a model Grade serves, such as `claude-sonnet-5-5`. See [Models](/agent/overview#models). | | `x-model-key` | Your API key for that model's provider. Used for this turn only, never stored. | | `x-model-workspace` | Optional, Claude only: your Anthropic workspace id (`wrkspc_…`), which a key not scoped to a workspace needs. | | `Content-Type` | `application/json` | | `Accept` | `text/event-stream` | | `cf-access-token` | Only on Grade's development environment: the header Grade gives you for it. | ## Request body JSON, at most 32 KB in UTF-8. A field this page does not name is refused with `400`. | Field | Type | Required | Meaning | | - | - | - | - | | `messages` | array | Yes | The conversation, oldest first: 1–400 messages of `{ "role": "user" \| "assistant", "content": string }`. The last one is the person's question: `user`, not blank, at most 2,000 characters. | | `app_events` | array | Yes | What became of proposals, at most 32 events (below). Send `[]` when there is none. | | `prior_run_id` | string or `null` | Yes | The `run_id` of the previous answer in this conversation; `null` for the first question. | | `formats` | array | No | The proposal formats you want: `text`, `card` or `composition`, 1–3 entries. Omitted, you get every format your organization has on. Composition is off in the beta. | | `conversation_id` | string | No | A UUID you choose per conversation, so Grade's records group its answers. | | `history_trimmed` | boolean | No | `true` when you left the oldest messages out to stay within the limits. | History is text only. An `assistant` message holds an answer's `text` deltas, joined. Proposals never go in `messages`: they go back as app events. ```json theme={null} { "messages": [ { "role": "user", "content": "Which campaigns still need payment terms?" }, { "role": "assistant", "content": "Two campaigns have creators without payment terms: ..." }, { "role": "user", "content": "Add Maya Chen and Leo Park to Summer Launch." } ], "app_events": [], "prior_run_id": "7d0c5c8e-2f61-4b8e-9a51-3c1f0f7a9e24", "formats": ["text", "card"] } ``` ### App events Both kinds carry `"type": "app_event"` and the time in `at`. * **`open_proposal`** goes with every question for the latest proposal of each action, until a newer one arrives, so the person can correct it in words ("add Maya too"). It carries the proposal's `action_id` and `action`, its `status` (`open`, or `applied` once a row saved) and the `draft` the `action` event gave. Only a proposal with a `draft`, which comes with the `card` format, has one. * **`action`** goes once, with what became of a proposal: ```json theme={null} { "type": "app_event", "kind": "action", "at": "2026-10-28T18:03:40.000Z", "action_id": "act_4f9c1b", "action": "prepare_campaign_creators", "outcome": "saved" } ``` | Commit result | `outcome` | | - | - | | Receipt `saved` | `saved` | | Receipt `partial` with a `saved` row | `saved`, with `counts` | | Receipt `partial` without one | `unconfirmed` | | Receipt `refused`, or a refused commit | `rejected` | | `504`, or no answer: it may have been written | `unconfirmed` | | The person dismissed it | `closed` | The optional `counts` holds whole numbers: `added` for `saved` rows, `failed` for `refused` and `not_sent`, and `unconfirmed` for `unknown`, leaving out zeros. ## Events The answer is `text/event-stream`: each frame is an `event:` line and a `data:` line with one JSON object. A frame starting with `:` (`: keep-alive`, every 15 seconds while the model thinks) is a comment: skip it. The `x-agent-run-id` response header carries the run's id, on refusals too: log it and quote it when you contact Grade. `run_started` comes first and `turn_completed` last, with any number of `step_started`, `step`, `text` and `action` between them. A stream that closes without `turn_completed`, or sends `error` instead, failed: treat it as `stream_error`. ```text theme={null} event: run_started data: {"run_id":"9b2e7f4a-1c3d-4e5f-8a6b-7c8d9e0f1a2b","context_version":"3f9a1c2e","api_version":1} event: step_started data: {"tool":"list_campaigns_needing_setup"} event: step data: {"tool":"list_campaigns_needing_setup","status":"ok","ms":412} event: text data: {"delta":"Two campaigns have creators without payment terms: "} event: turn_completed data: {"run_outcome":"answered","error_class":null,"usage":{"input":18234,"output":412,"cache_read":0,"cache_write":0},"cost_usd":0.061,"model":"claude-sonnet-5-5"} ``` | Event | What to do | | - | - | | `run_started` | Keep `run_id`: it is the next request's `prior_run_id`. | | `step_started` | A read or an action started; `tool` names it. You may show that the assistant is working. | | `step` | It ended: `status` is `ok` or `error`, with a `code` on error. Its other fields are diagnostics. | | `text` | Append `delta` to the answer. | | `action` | A proposal, below. | | `turn_completed` | The end. `run_outcome` says how it ended (below), with `usage`, `model` and `cost_usd`, an estimate: your provider bills the real cost. | | `error` | Grade could not finish the answer; `code` names why. | | `view_delta`, `view`, `view_rejected` | Only with composition, which is off in the beta. | The answer's text is a small Markdown subset (paragraphs, headings, lists, small tables, bold and inline code) with no links or images. Draw it with a renderer that escapes HTML, or as plain text: it is model-written, and it quotes data from people outside your team. ### A proposal ```json theme={null} { "action_id": "act_4f9c1b", "action": "prepare_campaign_creators", "text": "Add creators · Summer Launch\nTo add:\nMaya Chen: New on this campaign\nLeo Park: New on this campaign", "proposal_token": "eyJhbGciOiJFZERTQSIsInR5cCI6ImFnZW50LXByb3Bvc2FsK2p3cyIs...", "payload": { "...": "the card's data" }, "draft": { "campaign_id": "CAMP_123", "creator_ids": ["CR_1", "CR_2"] }, "args": null } ``` | Field | Meaning | | - | - | | `action_id`, `action` | The proposal's id and the action's name, from [Actions](/agent/overview#actions). | | `text` | The confirmation, at most 4,000 characters, written by Grade's code, never the model. Show it as plain text beside the confirm button. | | `proposal_token` | The signed proposal. Send it to [the commit](/agent/commit) unchanged. It is signed, not encrypted, and holds your organization's data: keep it on your backend. | | `payload` | The proposal's data, to draw your own card, or to ignore. | | `draft` | Only with `card`: send it back in `open_proposal`. | | `args` | For Grade's evaluations. Ignore it. | An `action` event without a `proposal_token` has nothing to commit: show no confirm button. When a newer proposal of the same action arrives, turn the older one's button off. When a proposal can't be sent, no `action` event comes: its `step` ends with `PROPOSAL_TOO_LONG` or `PROPOSAL_UNAVAILABLE`, and the assistant says so in words. ### Every event and its fields #### `run_started` | Field | Type | Sent | | - | - | - | | `run_id` | string (a UUID) | Always | | `context_version` | string (matching `^[a-f0-9]{8,64}$`) | Always | | `api_version` | `1` | When it applies | #### `step_started` | Field | Type | Sent | | - | - | - | | `tool` | string (matching `^[a-z][a-z0-9_]{0,63}$`) | Always | #### `step` | Field | Type | Sent | | - | - | - | | `tool` | string (matching `^[a-z][a-z0-9_]{0,63}$`) | Always | | `status` | one of `ok`, `error` | Always | | `ms` | number (at least 0) | Always | | `code` | string (matching `^[\w.:-]{1,80}$`) or `null` | When it applies | | `method` | `"GET"` or `null` | When it applies | | `route` | string (at most 256 characters) or `null` | When it applies | | `rows` | number (an integer, at least 0) or `null` | When it applies | | `args` | object or `null` | When it applies | | `output_keys` | array of string (at most 80 characters) or `null` | When it applies | | `detail` | object: `args`, `rows`, `truncated` | When it applies | #### `text` | Field | Type | Sent | | - | - | - | | `delta` | string | Always | #### `view_delta` | Field | Type | Sent | | - | - | - | | `view_id` | string (matching `^[\w-]{1,128}$`) | Always | | `seq` | number (an integer, at least 0) | Always | | `text` | string | Always | #### `view` | Field | Type | Sent | | - | - | - | | `view_id` | string (matching `^[\w-]{1,128}$`) | Always | | `program` | string | Always | | `statements` | number (an integer, at least 0) | Always | | `fallback` | boolean | When it applies | #### `view_rejected` | Field | Type | Sent | | - | - | - | | `view_id` | string (matching `^[\w-]{1,128}$`) | Always | | `rule_ids` | array (at most 100 items) of string (matching `^[\w.:-]{1,80}$`) | Always | | `next` | one of `repair`, `none` | Always | | `detail` | object: `lines` | When it applies | #### `action` | Field | Type | Sent | | - | - | - | | `action_id` | string (matching `^[\w-]{1,128}$`) | Always | | `action` | string (matching `^[a-z][a-z0-9_]{0,63}$`) | Always | | `payload` | object | Always | | `args` | object or `null` | When it applies | | `draft` | object | When it applies | | `text` | string (at most 4,000 characters) | When it applies | | `proposal_token` | string (at most 65,536 characters, matching `^[\w-]+\.[\w-]+\.[\w-]+$`) | When it applies | #### `turn_completed` | Field | Type | Sent | | - | - | - | | `run_outcome` | one of `answered`, `refused_access`, `session_expired`, `tool_failed`, `model_error`, `stream_error`, `max_tokens`, `refusal`, `step_cap`, `paused`, `budget_exhausted`, `client_aborted`, `worker_exception` | Always | | `error_class` | string (matching `^[\w.:-]{1,80}$`) or `null` | When it applies | | `usage` | object: `input`, `output`, `cache_read`, `cache_write` | When it applies | | `cost_usd` | number (at least 0) or `null` | When it applies | | `model` | string (matching `^[a-z0-9.-]{1,64}$`) or `null` | When it applies | | `resets_at` | string (an ISO 8601 timestamp) or `null` | When it applies | #### `error` | Field | Type | Sent | | - | - | - | | `code` | string (matching `^[\w.:-]{1,80}$`) | Always | ## Refusals before the stream A refused question answers JSON, `{ "code": "..." }`, and no stream. | Status | `code` | Meaning | | - | - | - | | `400` | `invalid_request` | The body does not match this page. | | `400` | `MODEL_KEY_MISSING` | Send your provider key in `x-model-key`. | | `400` | `MODEL_NOT_ALLOWED` | `x-model` names no model this environment serves; the body's `models` lists the ones it does. | | `400` | `MODEL_WORKSPACE_INVALID` | `x-model-workspace` is not an Anthropic workspace id, or the model is not Claude. | | `401` | `AGENT_TOKEN_MISSING`, `AGENT_TOKEN_INVALID` | Mint a new token and send the same request once more. | | `403` | `refused_access` | The key's scopes reach no read and no action, or the assistant is not open to your organization. | | `403` | `FORMATS_UNAVAILABLE` | Neither `text` nor `card` is left once your organization's formats meet the request's. | | `409` | `run_in_progress` | This end user already has an answer running. Wait for `turn_completed`. | | `503` | `AGENT_UNCONFIGURED` | Not configured on Grade's side. Contact Grade if it lasts. | ## How an answer ended `turn_completed.run_outcome` says how an accepted question ended, and `error_class` why, in one word. Try again resends the same request. | `run_outcome` | `error_class` | Meaning | Try again | | - | - | - | - | | `answered` | | The answer is complete. | | | `client_aborted` | | You stopped it. | | | `refused_access` | `access_revoked` | The assistant or your application's access was switched off since the token was minted. | No | | `session_expired` | | The token ran out. Mint a new one first. | Yes | | `paused` | none, `budget_unbound` | The assistant is paused. | No | | `paused` | `access_unavailable`, `budget_unavailable` | Busy for a moment. | Yes | | `budget_exhausted` | `end_user_hour`, `end_user_day`, `app_day` | A [limit](/agent/overview#limits) was reached; `resets_at` says when it opens again. | No | | `model_error` | `key_rejected` | Your provider refused the model key, or an Anthropic key needs `x-model-workspace`. | No | | `model_error` | `spend_limit` | Your provider account reached its spending limit or quota. | No | | `model_error` | `overloaded`, `rate_limited`, `api_error`, `timeout` | Your provider is busy. | Yes | | `model_error` | `invalid_request` | Your provider refused the request. Start a new conversation if it happens again. | No | | `tool_failed` | the read's code | Grade couldn't load the data. | Yes | | `step_cap` | `context_cap`, `run_cost_cap`, other | The question needs more than one answer can do. Ask a narrower one. | No | | `max_tokens` | | The answer was cut short. | No | | `refusal` | | The assistant can't help with that. | No | | `stream_error`, `worker_exception` | | Something went wrong. | Yes | ## Compatibility Events and fields are only ever added: ignore an event or a field you don't know, and read a new `run_outcome` or `error_class` as a failure. A change you would have to adapt to comes as a new `api_version`, which you ask for. The request is the other way round: Grade refuses what it doesn't know. # Mint an agent token Source: https://api-docs.usegrade.com/agent/token agent/openapi.json POST /sdk/v1/agent/token Trades the SDK key for an agent token for one person of yours, valid for 15 minutes. Requires the key's `agent:read` scope and the assistant switched on for the organization. Your backend sends the token to the assistant and to its MCP reads; it never reaches a browser. **Beta.** The assistant API and its reads over MCP are in beta. They are open to every organization that pays out through Grade, and parts are not available yet, as each page says. # Standalone analytics Source: https://api-docs.usegrade.com/analytics Track accounts and posts outside campaigns, organize them into collections, and query performance through /sdk/v1. All endpoints below require: * `X-Application-Id` * `X-Api-Key` Standalone analytics tracks social accounts and posts without adding them to a campaign. The API supports Instagram, TikTok, YouTube, Facebook, and X/Twitter URLs. Paginated list endpoints accept `page` and `limit`, and return a top-level `pagination` object with `page`, `limit`, `total`, and `totalPages`. The `/top` ranking uses a continuation cursor and `hasMore` instead of totals; see below. ## Track content ### POST /sdk/v1/analytics/tracked-media Track one account or post. Grade detects the platform and target type from the URL and schedules the first scrape. ```json theme={null} { "url": "https://www.tiktok.com/@creator/video/7350000000000000000", "trackStartAt": "2026-07-01T00:00:00.000Z", "collectionIds": ["collection_..."] } ``` Optional fields: * `platform`: `INSTAGRAM`, `TIKTOK`, `YOUTUBE`, `FACEBOOK`, or `TWITTER` * `isAccount`: explicitly identify an ambiguous URL as an account or post * `captionFilter`: account-only keyword, hashtag, mention, or phrase filter * `trackRelativeValue` and `trackRelativeUnit`: how long discovered posts are tracked after upload; use `DAYS` or `MONTHS` * `collectionIds`: collections to add the target to * `forceScrape`: request a manual retry when an existing target is already being tracked; the retry is subject to the manual refresh policy below The response includes the `trackedMediaId`, normalized URL, tracking configuration, scrape state, and whether the row was created, restored, or already existed. Reposting an existing or previously deleted target does not schedule another scrape unless `forceScrape` is true. Forced refreshes remain subject to the manual refresh policy below. ### POST /sdk/v1/analytics/tracked-media/bulk Track up to 200 URLs in one request. ```json theme={null} { "urls": [ "https://www.instagram.com/creator/", "https://www.youtube.com/shorts/abc123xyz" ], "captionFilter": "#gradepartner", "collectionIds": ["collection_..."] } ``` The response contains a result for each URL and a summary of created, existing, restored, duplicate, and failed items. Existing targets are not rescraped by the bulk endpoint. ## Manage tracked content ### GET /sdk/v1/analytics/tracked-media List standalone tracked targets. Query parameters: * `type`: `accounts` or `posts`; omit to return both * `page`: default `1` * `limit`: default `20`, maximum `100` * `q`: URL or normalized-target search Account rows include metrics aggregated across discovered posts. Post rows include their latest views, likes, comments, and shares, plus `bookmarks` (`null` or `0` until the first tracking snapshot lands; platforms that do not report bookmarks always read `0`) and `durationSeconds` (`null` when the actor supplied no length). Every row includes scrape state and issue information. Account media rows include `accountIssue`, independently of tracking tier. It is `null` when no warning is recorded, including before the first check. A successful completed check clears it. Do not render an “OK” badge or treat `null` as proof that all historical posts were discovered. ```json theme={null} { "accountIssue": { "code": "CHECK_FAILED", "reasonCode": "INCOMPLETE_RESPONSE", "message": "The provider did not finish retrieving this account.", "checkedAt": "2026-10-19T04:05:00.000Z" } } ``` | Code | Meaning | | - | - | | `PROFILE_NOT_FOUND` | The provider explicitly reported that the profile does not exist. Check its link or username. | | `PROFILE_PRIVATE` | The provider explicitly identified a private profile. | | `NO_ACCESSIBLE_VIDEOS` | No public posts could be retrieved. This may include a login wall; it does not prove the creator has never posted. | | `CHECK_FAILED` | The check could not finish reliably. Use `reasonCode` and `message` to explain why. | `CHECK_FAILED` reasons are `ACCESS_BLOCKED`, `RATE_LIMITED`, `TIMEOUT`, `INCOMPLETE_RESPONSE`, `INVALID_RESPONSE`, `PROCESSING_FAILED`, `PROFILE_UNAVAILABLE`, `PROVIDER_UNAVAILABLE`, and `PROVIDER_ERROR`. Other codes have a `null` reason. `PROCESSING_FAILED` identifies a Grade-side failure to prepare the check or process its results, including an invalid account target or missing tracking dates. Messages are safe for display; use codes for application logic. `checkedAt` is the UTC time of the reported issue. The previous warning remains while a new check is pending. An empty date-filtered window is not an account warning, and a failed individual post does not label its parent account missing or private. Results are scoped to each account, including when several accounts share a provider run. Providers include Apify actors and the official X API. Temporary `CHECK_FAILED` results remain internal while automatic recovery is pending. If recovery succeeds, no new warning appears. If recovery finishes unsuccessfully, Grade publishes the issue and its reason. Failures with no remaining automatic recovery can be published immediately. Explicit profile availability responses do not wait for technical retries. The official X API continues retrying without a fixed attempt limit. Its first transient failure stays internal; a subsequent failure at least three hours later publishes `CHECK_FAILED` if the account check still has not completed. Retries continue, and a successful completed check clears the warning. Instagram account checks combine the required posts and reels providers. Neither provider can clear a warning while the other is pending or recovering. Conflicting availability responses become `CHECK_FAILED` with `INCOMPLETE_RESPONSE`; Grade does not assert that a profile is private or missing when another required provider succeeds. A successful posts check with no accessible reels does not itself produce a warning. Tracked-media rows also expose normalized content metadata when the platform actor supplies it: * Author: `authorPlatformId`, `authorUsername`, `authorDisplayName` * Content: `title`, `captionText`, `hashtags` * Audio: `audioPlatformId`, `audioTitle`, `audioArtist`, `audioAlbum`, `audioIsOriginal` * Freshness: `metadataCollectedAt` Unavailable actor fields are `null`; `hashtags` is an empty array when none are available. These fields are returned by the tracked-media list, detail, and discovered-post endpoints. They also appear on the nested `trackedMedia` object returned for collection members, on tracked video results from `/top`, and in `data.meta` from `/media/tracked/:trackedMediaId`. ### GET /sdk/v1/analytics/tracked-media/:trackedMediaId Get one tracked account or post with its latest metrics and `asOfTimestamp`. ### GET /sdk/v1/analytics/tracked-media/:trackedMediaId/posts List posts discovered from a tracked account. Query parameters: * `page`: default `1` * `limit`: default `20`, maximum `100` ### PATCH /sdk/v1/analytics/tracked-media/:trackedMediaId/track-window Update tracking configuration. ```json theme={null} { "captionFilter": "#gradepartner", "trackRelativeValue": 30, "trackRelativeUnit": "DAYS" } ``` You can also update `trackStartAt`. Send `trackRelativeValue: null` and `trackRelativeUnit: null` together to clear the relative window. `captionFilter` is only valid for accounts. ### POST /sdk/v1/analytics/tracked-media/:trackedMediaId/scrape-now Request an immediate scrape. Scrape execution is asynchronous. This endpoint accepts standalone `trackedMediaId` values. For campaign accounts or posts, use [campaign media refresh](/campaign-media/management#refresh-an-account-or-post) with the `campaignCreatorMediaId` instead. Manual refreshes use the same policy as campaign media: each tracked target can be refreshed up to three times, with a four-hour cooldown after each successfully queued refresh. A target in its cooldown returns `429` with `Retry-After`, `refreshAvailableAt`, and `refreshCooldownMs`. A target that has used all three refreshes returns `409` with code `ATM_REFRESH_LIMIT_REACHED`. ### PATCH /sdk/v1/analytics/tracked-media/:trackedMediaId/tracking-tier Wake a sleeping target. ```json theme={null} { "trackingTier": 1 } ``` Already-active targets return a successful no-op response. ### DELETE /sdk/v1/analytics/tracked-media/:trackedMediaId Stop tracking a target. Deleting an account also soft-deletes its discovered child posts. ## Collections ### POST /sdk/v1/analytics/collections Create a collection. ```json theme={null} { "name": "Summer creators" } ``` ### GET /sdk/v1/analytics/collections List collections with account/video counts and current views, likes, comments, and shares. Every ongoing campaign is also returned as an automatically generated live collection. These records have `kind: "live"`, `automaticallyGenerated: true`, and a `campaignId`. Their counts and metrics follow the campaign automatically, including when the request is made through the SDK. Completed and deleted campaigns are not returned. Query parameters: * `page`: default `1` * `limit`: default `20`, maximum `100` * `q`: collection-name search * `kind`: `fixed` or `live` ### GET /sdk/v1/analytics/collections/:collectionId Resolve a collection by ID. The response includes `kind`, `filterQuery`, `surface`, `campaignId`, and `automaticallyGenerated` so clients can distinguish fixed, user-authored live, and campaign-generated collections. ### PATCH /sdk/v1/analytics/collections/:collectionId Rename a collection. ```json theme={null} { "name": "Updated collection name" } ``` Automatically generated campaign collections are read-only. Rename, filter update, freeze, delete, and membership mutations return `409 Conflict`; update the campaign instead. ### DELETE /sdk/v1/analytics/collections/:collectionId Delete a collection and its member associations. This does not delete the tracked media itself. Collections that also contain campaign members cannot be deleted through the standalone analytics API and return `409 Conflict`. Automatically generated campaign collections are also managed by the campaign and cannot be deleted directly. ### GET /sdk/v1/analytics/collections/:collectionId/members List materialized standalone tracked accounts and posts in a fixed collection. Live collections compute their scope from their saved filter and do not create membership rows. Query parameters: * `page`: default `1` * `limit`: default `20`, maximum `100` * `q`: target URL search ### POST /sdk/v1/analytics/collections/:collectionId/members Add a tracked account or post to a collection. ```json theme={null} { "trackedMediaId": "atm_..." } ``` Adding an existing membership succeeds with `meta.duplicate: true`. ### DELETE /sdk/v1/analytics/collections/:collectionId/members/:memberId Remove a tracked member from a collection without stopping its tracking. ## Query analytics Analytics endpoints default to `scope=tracked`. Direct campaign scopes require both `analytics:read` and `campaigns:read`: use `scope=campaign` or `campaigns` with `campaignId`/`campaignIds`, `scope=creator` or `creators` with `creatorProfileId`/`creatorProfileIds`, or `scope=media` with `campaignCreatorMediaId`. `scope=collections` retains its collection behavior, including automatically generated campaign collections. All identifiers are scoped to the API key's agency. Common query parameters: * `startDate` and `endDate`: optional `YYYY-MM-DD` date range; defaults to the latest 30 days * `platform`: `FACEBOOK`, `YOUTUBE`, `INSTAGRAM`, `TIKTOK`, or `TWITTER` * `collectionIds`: comma-separated collection IDs * `trackedMediaIds`: comma-separated tracked post IDs * `trackedAccountIds`: comma-separated tracked account IDs; account IDs expand to their discovered posts * `includeIncomplete`: include the current incomplete day You can combine collection and tracked-ID filters. IDs are always scoped to the agency associated with the SDK application. For `/summary`, `/series`, and `/top`, pass `includeHidden=false` to stop counting a currently hidden campaign creator's performance at their saved hide date. This applies to campaign media included through campaign-generated collections. Standalone tracked media is unaffected. Omitting the parameter or passing `includeHidden=true` keeps the existing behavior, including all snapshots. The last available snapshot at or before `hidden_at` is used: earlier contributions remain, cumulative totals freeze, and subsequent growth is zero. This uses the one current hide date, without reconstructing past hide/unhide periods. Unhiding removes the cutoff; hiding again sets a new date. A legacy hidden creator without a saved date contributes no snapshots with this option. Existing stored snapshots are used, so no backfill is required. ### GET /sdk/v1/analytics/summary Return views, likes, comments, shares, bookmarks, engagements, engagement rate, virality, videos tracked, active accounts, and growth comparisons. ### GET /sdk/v1/analytics/series Return daily values for one metric. Additional parameters: * `metric`: `views`, `likes`, `comments`, `shares`, `bookmarks`, `engagements`, `engagement_rate`, or `virality` * `mode`: `delta` for change during each day or `total` for cumulative totals ### GET /sdk/v1/analytics/top Rank videos or accounts in the selected scope, including campaign media from campaign-generated collections. Tracked video results include the normalized author, content, hashtag, and audio fields described above. Tracked account results include available author identity fields and `metadataCollectedAt`. Additional parameters: * `type`: `videos` or `accounts` * `metric`: supported analytics metric * `mode`: `delta` or `total` * `limit`: rows per page; default `20`, maximum `100` * `page=1`: start a paginated ranking * `cursor`: continue from the previous response's `pagination.nextCursor`; omit `page` when supplying a cursor Start with `page=1&limit=100`. The response includes `pagination: { "page": 1, "limit": 100, "hasMore": true, "nextCursor": "..." }`. For the next request, replace `page` with `cursor=`, keeping the other filters and `limit` unchanged. Continue until `hasMore` is `false` and `nextCursor` is `null`. There is no total-results cap. Direct jumps such as `page=100000` are rejected; each request fetches at most 101 candidates per source. Omitting both `page` and `cursor` preserves the existing response shape. Equal metric values use a stable ID tie-break. Rankings remain live; restart with `page=1` if campaign membership, visibility, or filters change during pagination. First request: `/sdk/v1/analytics/top?scope=collections&collectionIds=ACOLL_CAMP_123&type=videos&metric=views&mode=delta&includeHidden=false&page=1&limit=100`. Next request: `/sdk/v1/analytics/top?scope=collections&collectionIds=ACOLL_CAMP_123&type=videos&metric=views&mode=delta&includeHidden=false&cursor=&limit=100`. ### GET /sdk/v1/analytics/posting-activity Return the number of posts published on each date, including account coverage metadata. ### GET /sdk/v1/analytics/posting-schedule Group publishing performance by day of week and hour. Additional parameters: * `metric`: supported analytics metric * `mode`: `delta` or `total` ### GET /sdk/v1/analytics/video-lengths Group post performance by video-duration bucket. Additional parameters: * `metric`: supported analytics metric * `mode`: `delta` or `total` * `bucketPreset`: optional; defaults to `shortform_v1` (`0-15s`, `16-30s`, `31-60s`, `61-90s`, `90s+`). `shortform_v2` splits the open tail at three minutes (`91-180s`, `180s+`), the point where YouTube Shorts and Instagram Reels stop counting as short-form. Each post contributes one observation to the bucket matching its positive whole-second duration. The bucket value is the exact median across posts with an available metric result; posts without an in-range tracking observation or usable metric denominator are excluded from both the median and post count. `engagement_rate` and `virality` are always evaluated in `total` (lifetime) mode for this endpoint. The chart cohort is posts uploaded inside the selected date range, so a pre-range baseline generally does not exist for a truthful delta rate. If a client requests `mode=delta` for either metric, the response reports `meta.mode: "total"`, `meta.requestedMode: "delta"`, and `meta.modeAdjusted: true`. Other metrics preserve the requested mode. Virality values are shares per 1,000 views, not percentages. ### GET /sdk/v1/analytics/media/tracked/:trackedMediaId Return the date-range summary and daily series for one tracked post. `data.meta` includes the normalized author, content, hashtag, audio, and metadata-freshness fields described above. Optional query parameters: * `startDate` and `endDate` * `metric` * `mode`: `delta` or `total` ## Metric freshness Analytics responses include `meta.asOfTimestamp`. This is the latest stored tracking snapshot used by the response and may be `null` before the first scrape completes. Metric availability differs by platform. Responses include availability metadata when a metric is unsupported or only partially supported across the selected targets. ## Campaign-media detail `GET /sdk/v1/analytics/media/campaign/:campaignCreatorMediaId` requires `analytics:read` and `campaigns:read`. It supports the same date range and aggregation options as tracked-media detail. ## Bulk collection membership and freezing `POST /sdk/v1/analytics/collections/:collectionId/members/bulk` requires `analytics:write`: ```json theme={null} { "trackedMediaIds": ["tracked-id"], "campaignCreatorMediaIds": ["campaign-media-id"] } ``` The combined maximum is 1000 unique IDs per call. All IDs must belong to the agency. Campaign IDs additionally require `campaigns:read`; send an empty `trackedMediaIds` array when adding only campaign media. Duplicate members are counted as already present. The response includes `requestedCount`, `addedCount`, and `alreadyPresentCount`. Collection and member lists still default to standalone content. Pass `source=all` with both `analytics:read` and `campaigns:read` to include campaign members. Keys with `campaigns:read` may also remove campaign members or delete a mixed collection with `analytics:write`. To freeze a live collection, first harvest the desired members through the bulk endpoint with `forFreeze: true`. After every batch succeeds, call `POST /sdk/v1/analytics/collections/:collectionId/freeze` with `{}`. This requires `analytics:write` and converts the saved filter to a fixed list using the members already written. **Freeze does not harvest rows automatically.** The conversion has no undo; create a new live collection to use a filter again. Automatically generated collections cannot be modified or frozen. # Bonus templates Source: https://api-docs.usegrade.com/bonus-templates Create, list, edit, and delete tiered bonus templates via /sdk/v1. All endpoints below require: * `X-Application-Id` * `X-Api-Key` Bonus templates define reusable tiered view bonuses for campaign creator contracts. The legacy contract endpoint that accepted `paymentTermTemplateId` is deprecated. To use a template through the API, read its scope and tiers and put those values into `bonusPayment` on the unified human-readable contract-history endpoint. > [!NOTE] > > These endpoints configure tiered campaign bonuses. They do not issue a payout. `POST /sdk/v1/payouts/trigger` is still a direct payout endpoint and only pays the explicit `payoutAmount` or `lineItems` you send. ## Bonus flow 1. Create a bonus template with thresholds and amounts. 2. Read the creator's current contract and its `versionId`. 3. Copy the template's scope and tiers into the contract's `bonusPayment`. 4. Write the complete contract with `basedOnVersionId`. 5. Add tracked campaign media for those creators. 6. Grade calculates eligible tiered bonus line items from tracked views and the contract's bonus settings. ## GET /sdk/v1/bonus-templates List active tiered bonus templates for your agency. ### Query parameters **includeHidden** `boolean` (default: false) Include templates hidden by `DELETE /sdk/v1/bonus-templates/:templateId`. ### Response ```json theme={null} { "success": true, "data": [ { "templateId": "ptt_...", "name": "Launch view bonus", "description": "Bonus for high-performing launch posts", "colorCode": "#22C55E", "currency": "USD", "metric": "VIEWS", "tierScope": "CREATOR", "tiers": [ { "threshold": 100000, "amount": 50 }, { "threshold": 500000, "amount": 250 } ], "components": [ { "type": "TIERED", "currency": "USD", "metric": "VIEWS", "tier_scope": "CREATOR", "tiers": [ { "threshold": 100000, "amount": 50 }, { "threshold": 500000, "amount": 250 } ] } ], "isDefault": false, "hidden": false, "createdAt": "2026-05-19T12:00:00.000Z", "updatedAt": "2026-05-19T12:00:00.000Z" } ] } ``` ## GET /sdk/v1/bonus-templates/:templateId Fetch one tiered bonus template. ### Path parameters **templateId** `string` *required* Bonus template ID returned by create or list. ### Query parameters **includeHidden** `boolean` (default: false) Allow fetching a hidden template. ### Common errors * `404`: template not found, belongs to another agency, is hidden, or is not a tiered bonus template ## POST /sdk/v1/bonus-templates Create a tiered bonus template. ### Body ```json theme={null} { "name": "Launch view bonus", "description": "Bonus for high-performing launch posts", "colorCode": "#22C55E", "currency": "USD", "metric": "VIEWS", "tierScope": "CREATOR", "tiers": [ { "threshold": 100000, "amount": 50 }, { "threshold": 500000, "amount": 250 } ] } ``` **name** `string` *required* Display name. Names must be unique among visible bonus templates for the agency. **description** `string` Optional description. **colorCode** `string` *required* Six-digit hex color, such as `#22C55E`. **currency** `string` *required* Bonus payout currency. All tiers in one template use the same currency. **metric** `string` (default: VIEWS) Must be `VIEWS`. Other metrics are rejected because they are not supported by the payout calculator. **tierScope** `string` (default: CREATOR) How views are counted for the bonus. Use `CREATOR`, `MEDIA`, or `BEST_MEDIA`. **tiers** `object[]` *required* Threshold/amount pairs. Each `threshold` and `amount` must be a non-negative number. **isDefault** `boolean` (default: false) Marks this template as an agency default for selection UIs. You can also send raw tiered components instead of `currency` plus `tiers`: ```json theme={null} { "name": "Per-video bonus", "colorCode": "#0EA5E9", "components": [ { "type": "TIERED", "currency": "USD", "metric": "VIEWS", "tier_scope": "MEDIA", "tiers": [ { "threshold": 250000, "amount": 100 } ] } ] } ``` ### Response Returns `201` with the created template in `data`. ### Common errors * `400`: missing name, color, currency, tiers, or invalid tier values * `400`: metric is not `VIEWS` * `400`: component type is not `TIERED` * `409`: a visible template with this name already exists ## PATCH /sdk/v1/bonus-templates/:templateId Edit a tiered bonus template. `PUT` is also accepted with the same body. ### Body Send at least one updatable field: * `name` * `description` * `colorCode` * `tiers` * `components` * `tierScope` * `isDefault` ```json theme={null} { "name": "Launch view bonus v2", "applicablePostsUploadedOnOrAfter": "2026-07-24", "tiers": [ { "threshold": 100000, "amount": 75 }, { "threshold": 500000, "amount": 300 } ] } ``` **applicablePostsUploadedOnOrAfter** `string` Required when changing tiers on a template that is already applied to creator contracts. The same date creates the new bonus-term history boundary for every linked contract. > [!WARNING] > > If a template is already applied to creator contracts, you can only edit TIERED threshold and amount values, and you must provide `applicablePostsUploadedOnOrAfter`. Currency, metric, component shape, and `tierScope` are locked until those contracts use a different template. ### Common errors * `400`: no updatable fields * `400`: invalid tier values or non-tiered components * `400`: missing or invalid `applicablePostsUploadedOnOrAfter` for an in-use tier change * `400`: attempted currency, metric, or scope change while the template is applied * `409`: a visible template with this name already exists * `409`: template is locked by a pending payout approval ## DELETE /sdk/v1/bonus-templates/:templateId Hide a tiered bonus template from future selection. > [!NOTE] > > Delete is a soft delete. Hidden templates stay available to existing calculations if they were already applied to contracts. ### Response ```json theme={null} { "success": true, "message": "Deleted" } ``` ## Use a bonus template in a contract After you create or fetch a template, read the creator's contract history, copy the template values into `bonusPayment`, and submit the complete contract. Map `tierScope` to `appliesTo` as follows: `CREATOR` → `CREATOR`, `MEDIA` → `POST`, and `BEST_MEDIA` → `BEST_POST`. For a template with `tierScope: "MEDIA"`, use `appliesTo: "POST"`: ```json theme={null} { "basedOnVersionId": "CCCH_CURRENT", "effectiveDate": "2026-05-01", "contract": { "...": "all fields returned by the contract-history GET", "bonusPayment": { "appliesTo": "POST", "pays": "CAMPAIGN_COMPLETION", "rules": [ { "currency": "USD", "conversionPolicy": null, "metric": "VIEWS", "tiers": [ { "minimum": 100000, "amount": 50 }, { "minimum": 500000, "amount": 250 } ] } ] } } } ``` See [Create a contract version](/campaign-creators/create-contract-version) for the required complete contract shape and stale-write safeguard. Payout timing is a contract setting, separate from the template's tiers. Choose `bonusPayment.pays` as `CAMPAIGN_COMPLETION`, `NOW`, or `NOW_AND_STOP`. The last option makes the currently earned bonus payable and closes further tiers for that rule and payout scope after settlement. Read [bonus payout timing](/campaign-creators/create-contract-version#bonus-payout-timing) before selecting it. # Campaign contracts Source: https://api-docs.usegrade.com/campaign-contracts Manage campaign creator contracts and payment terms via /sdk/v1. All endpoints below require: * `X-Application-Id` * `X-Api-Key` Contracts are **optional**. A campaign creator can exist and have media tracked without any contract or payment terms set. Contracts define how a creator gets paid for their work on a campaign. For the human-readable contract timeline addressed by `campaignCreatorRecordId`, see [Read contract history](/campaign-creators/contract-history) and [Create a contract version](/campaign-creators/create-contract-version). ## Unified contract history Contract history is an ordered timeline of complete, frozen payment-term snapshots. An effective date is an inclusive upload/published business date: media uploaded on or after that date uses that version until the next version starts. Every write supplies one complete snapshot and identifies the version it was based on; the API does not merge a partial payload with an older version. The API never creates separate fixed, performance, bonus, or pay-cycle history items. `crosspost.captionFilter` in a terms snapshot enables [caption-based grouping](/crosspost-groups#automatic-grouping-and-caption-matching). Matching posts share a local-day group using campaign timezone, then agency timezone, then UTC, overriding upload-window and duration-tolerance checks. The same setting is named `crosspostRequirements.captionContains` in the human-readable contract API. Use `null` to disable the override; use an [account tracking filter](/campaign-media) if you only want to select posts to track. Reserved, settled, and ambiguous payout coverage is protected. A history mutation that could reprice, hide, or resurface that coverage returns `409` with `errorCode: "CONTRACT_HISTORY_PROTECTED_BOUNDARY"` and an `earliestAllowedEffectiveDate` explanation in the message. Previously paid items remain paid. ### GET /sdk/v1/campaigns/:campaignId/creators/contract/history Returns all active complete versions, their inclusive effective windows, the protected payout boundary, and retained revision provenance. Query parameter: * `email` (required) ```json theme={null} { "success": true, "data": { "campaignId": "camp_...", "creatorEmail": "creator@example.com", "campaignCreatorRecordId": "ccr_...", "contractInstanceId": "CCCI_...", "contractInstanceState": "OPEN", "protectedCoverage": { "protectedFromUploadDate": "2026-06-02", "protectedThroughUploadDate": "2026-06-12", "earliestAllowedEffectiveDate": "2026-06-13", "protectedEntitlementCount": 4, "stateCounts": { "SETTLED": 4 }, "coverageKinds": ["MEDIA"] }, "versions": [ { "campaignCreatorContractHistoryId": "CCCH_...", "effectiveFromUploadDate": "2026-06-01", "effectiveThroughUploadDate": null, "isCurrent": true, "protectedCoverage": { "protectedFromUploadDate": "2026-06-02", "protectedThroughUploadDate": "2026-06-12", "earliestAllowedEffectiveDate": "2026-06-13", "protectedEntitlementCount": 4, "stateCounts": { "SETTLED": 4 }, "coverageKinds": ["MEDIA"] }, "termsSnapshot": { "schemaVersion": 2, "contractInstanceId": "CCCI_...", "effectiveFromUploadDate": "2026-06-01", "payoutType": "FIXED", "currency": "USD", "fixed": { "active": true, "amount": "15", "paymentOption": "STANDARD", "rateScope": "CREATOR", "mediaPayoutMode": null, "platforms": [], "proratedByUploads": false, "prorationAssumedUploads": null, "minimumUploads": null, "prorateByTime": false, "upfrontPercentage": null }, "performance": { "active": false, "amount": null, "unitSize": null, "unit": null, "viewScope": null, "minViews": null, "maxViews": null, "excludeMinimumViews": false, "payoutTiming": null, "spendCaps": { "amount": null, "scope": "NONE", "period": "LIFETIME" }, "groupingMode": "NONE" }, "crosspost": { "minDistinctPlatforms": 1, "requiredPlatforms": [], "captionFilter": null }, "bonus": { "active": false, "payoutTiming": null, "tierScope": null, "components": [], "templateProvenance": null }, "payCycle": { "active": false, "timesPerPeriod": null, "period": null, "weekday": null, "monthDay": null, "startImmediately": false, "firstDueAt": null, "timeZone": "UTC" }, "eligibility": { "uploadedOnOrAfter": null, "postTestPhaseUploadCutoff": null, "testPhaseCreator": false }, "provenance": { "source": "AUTHORED", "sourceIds": ["phase5-writer:SDK_CONTRACT_ENDPOINT"] }, "compatibility": { "state": "COMPLETE", "missingEvidence": [] } } } ], "revisionHistory": [] } } ``` `protectedCoverage` summarizes the reserved, settled, and ambiguous payouts that cover the contract's upload days, and each item in `versions` carries the same summary for that version. `protectedFromUploadDate` and `protectedThroughUploadDate` are the earliest and latest upload days those payouts cover; both are `null` when there are none. A version's summary counts the payouts in its effective window and the payouts attached to that version, and an attached payout can cover a day before the version starts. A version's `protectedFromUploadDate` can therefore fall before its `effectiveFromUploadDate`, so do not read it as the version's first paid day. ### POST /sdk/v1/campaigns/:campaignId/creators/contract/history Uses one mutation contract for `CREATE`, `MOVE`, `REPLACE`, and `VOID`. For `CREATE`, send the complete `desiredTerms` snapshot and the `predecessorContractHistoryId` returned by the timeline GET. The server rejects a stale predecessor rather than merging fields from different versions. ```json theme={null} { "email": "creator@example.com", "operation": "CREATE", "contractInstanceId": "CCCI_...", "predecessorContractHistoryId": "CCCH_...", "effectiveFromUploadDate": "2026-06-13", "desiredTerms": { "schemaVersion": 2, "contractInstanceId": "CCCI_...", "effectiveFromUploadDate": "2026-06-13", "...": "all other complete snapshot fields" }, "changeReason": "CPM rate increased" } ``` For `MOVE`, send `campaignCreatorContractHistoryId`, the new effective date, and one complete `desiredTerms` snapshot whose effective date matches the new date. The existing immutable row is superseded in the same transaction that inserts the moved version. The server rejects moves that cross another active version or overlap reserved or settled payout coverage. For `REPLACE`, send `campaignCreatorContractHistoryId`, the unchanged effective date, and one complete `desiredTerms` snapshot. For `VOID`, send the history ID, effective date, and reason, but omit `desiredTerms`. The response's `data` includes the updated `timeline`, which carries the same `protectedCoverage` summaries as the GET. Every active bonus component in `desiredTerms` must use `metric: "VIEWS"`. Other metrics are rejected because the payout calculator does not support them. For active bonuses, `desiredTerms.bonus.payoutTiming` accepts `AT_COMPLETION`, `NOW`, or `NOW_STOP_AFTER_PAYOUT`. In the public campaign-creator contract shape, these correspond to `bonusPayment.pays` values `CAMPAIGN_COMPLETION`, `NOW`, and `NOW_AND_STOP`, respectively. See [bonus payout timing](/campaign-creators/create-contract-version#bonus-payout-timing) for scope, cancellation, and reversal behavior. ## Deprecated campaign contract resource The following legacy resource is fully deprecated: * `GET /sdk/v1/campaigns/:campaignId/creators/contract` * `PUT /sdk/v1/campaigns/:campaignId/creators/contract` * `DELETE /sdk/v1/campaigns/:campaignId/creators/contract` Every method returns `410 Gone`: ```json theme={null} { "success": false, "errorCode": "SDK_CONTRACT_API_DEPRECATED", "message": "This endpoint has been deprecated. Use GET or POST /sdk/v1/campaign-creators/:campaignCreatorRecordId/contract-history immediately." } ``` Use [Read contract history](/campaign-creators/contract-history) and [Create a contract version](/campaign-creators/create-contract-version) immediately. Those endpoints use the unified contract timeline and require a complete, explicit human-readable contract plus stale-write protection. # Read campaign creator contract history Source: https://api-docs.usegrade.com/campaign-creators/contract-history Read a campaign creator's contract timeline and identify the current contract. ## GET /sdk/v1/campaign-creators/:campaignCreatorRecordId/contract-history Returns the creator's contract timeline in a UI-ready format. The response identifies the current contract, the next scheduled contract, and every historic or scheduled version. All requests require `X-Application-Id` and `X-Api-Key`. ### Path parameter * `campaignCreatorRecordId` (required): the campaign creator whose contracts you want to read. ### Example request ```bash theme={null} curl -sS "$BASE_URL/sdk/v1/campaign-creators/CCR_123/contract-history" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" ``` ### Response ```json theme={null} { "success": true, "data": { "campaignCreatorRecordId": "CCR_123", "campaignId": "camp_123", "campaignName": "Summer launch", "creatorProfileId": "CP_123", "creatorEmail": "jordan@example.com", "businessDate": "2026-08-01", "timeZone": "America/Los_Angeles", "current": { "versionId": "CCCH_CURRENT", "effectiveDate": "2026-07-01", "effectiveThroughDate": "2026-07-31", "status": "CURRENT", "isCurrent": true, "contract": { "type": "FIXED", "currency": "USD", "fixedPayment": { "currency": "USD", "conversionPolicy": null, "amount": 500, "per": "CREATOR", "calculation": "STANDARD", "upfrontPercentage": null, "expectedPosts": null, "minimumPosts": null, "prorateByTime": false, "platforms": [], "crossposts": null }, "cpmPayment": null, "bonusPayment": null, "crosspostRequirements": null, "recurringPayment": null, "postsUploadedOnOrAfter": null } }, "nextScheduled": { "versionId": "CCCH_SCHEDULED", "effectiveDate": "2026-08-15", "status": "SCHEDULED", "isNextScheduled": true, "contract": { "type": "FIXED", "currency": "USD", "fixedPayment": { "currency": "USD", "conversionPolicy": null, "amount": 600, "per": "CREATOR", "calculation": "STANDARD", "upfrontPercentage": null, "expectedPosts": null, "minimumPosts": null, "prorateByTime": false, "platforms": [], "crossposts": null }, "cpmPayment": null, "bonusPayment": null, "crosspostRequirements": null, "recurringPayment": null, "postsUploadedOnOrAfter": null } }, "history": [ { "versionId": "CCCH_HISTORIC", "effectiveDate": "2026-06-01", "effectiveThroughDate": "2026-06-30", "status": "HISTORIC", "contract": { "type": "FIXED", "currency": "USD", "fixedPayment": { "currency": "USD", "conversionPolicy": null, "amount": 400, "per": "CREATOR", "calculation": "STANDARD", "upfrontPercentage": null, "expectedPosts": null, "minimumPosts": null, "prorateByTime": false, "platforms": [], "crossposts": null }, "cpmPayment": null, "bonusPayment": null, "crosspostRequirements": null, "recurringPayment": null, "postsUploadedOnOrAfter": null } }, { "versionId": "CCCH_CURRENT", "effectiveDate": "2026-07-01", "effectiveThroughDate": "2026-07-31", "status": "CURRENT", "isCurrent": true, "contract": { "type": "FIXED", "currency": "USD", "fixedPayment": { "currency": "USD", "conversionPolicy": null, "amount": 500, "per": "CREATOR", "calculation": "STANDARD", "upfrontPercentage": null, "expectedPosts": null, "minimumPosts": null, "prorateByTime": false, "platforms": [], "crossposts": null }, "cpmPayment": null, "bonusPayment": null, "crosspostRequirements": null, "recurringPayment": null, "postsUploadedOnOrAfter": null } } ] } } ``` `timeZone` is the campaign's effective IANA timezone, after applying the campaign override, agency fallback, and final `UTC` fallback. `businessDate` and contract effective dates are evaluated in this timezone. `status` is one of: * `CURRENT`: active on `businessDate` * `SCHEDULED`: begins on a future effective date * `HISTORIC`: ended before `businessDate` When a contract enables bonuses, `bonusPayment.pays` is `CAMPAIGN_COMPLETION`, `NOW`, or `NOW_AND_STOP`. These same values are accepted when creating a contract version. See [bonus payout timing](/campaign-creators/create-contract-version#bonus-payout-timing) for the stop policy and its payout scopes. A version saved as Simplified payment terms has `type: "RULES"`, `null` payment sections, and one more field, `paymentRules`: the payment agreement as Grade stored it. You can send that contract back to the create endpoint. See [Simplified payment terms](/campaign-creators/create-contract-version#simplified-payment-terms-rules). An empty timeline returns `current: null`, `nextScheduled: null`, and `history: []`. To create its first contract, send `basedOnVersionId: null` to the create endpoint. `null` is an explicit empty-timeline concurrency assertion, not a default: the write fails if another contract appears first. Keep the `versionId` for the version governing the date you intend to edit. Pass it as `basedOnVersionId` when creating a version. If another writer changes that part of the timeline first, the write is rejected instead of silently overwriting newer contract terms. ### Common errors * `401`: missing or invalid SDK credentials * `404`: campaign creator record not found Use [Create a contract version](/campaign-creators/create-contract-version) to add a new effective date to this timeline. # Create a campaign creator contract version Source: https://api-docs.usegrade.com/campaign-creators/create-contract-version Add a dated contract version to a campaign creator's contract timeline. ## POST /sdk/v1/campaign-creators/:campaignCreatorRecordId/contract-history Adds a contract version that becomes effective for media uploaded on or after the selected date. This is the same contract timeline used throughout Grade. All requests require `X-Application-Id` and `X-Api-Key`. ### Path parameter * `campaignCreatorRecordId` (required): the campaign creator whose contract you want to update. ### Body * `effectiveDate` (required): a real date in `YYYY-MM-DD` format. * `basedOnVersionId` (required): the `versionId` of the contract version that currently governs `effectiveDate`. Get it from [Read campaign creator contract history](/campaign-creators/contract-history). Send an explicit JSON `null` only when that response has an empty `history` and both `current` and `nextScheduled` are `null`. This creates the first contract without guessing that the timeline is still empty. * `contract` (required): the complete contract terms that should apply from that date. > [!WARNING] > > The contract must be complete and explicit. Do not omit fields to imply a > default or to inherit an earlier value. Start with the complete `contract` > returned by the history GET, change the intended values, and send every > field back. Use `null`, `false`, or `[]` explicitly where shown. Grade-managed test-phase cutoffs, template identity, and internal history IDs are intentionally not writable through this public shape. Existing values are preserved from the governing unified version; for a first contract, test-phase guards are copied from the creator record. Payment amounts, source currencies, conversion behavior, eligibility dates, grouping, timing, and schedules are all explicit in the request and are never inferred from omitted fields. > [!NOTE] > > To create a creator's first contract, send the same complete contract shape > with `"basedOnVersionId": null`. The server locks the creator record and > rejects the request with `409 CONTRACT_VERSION_STALE` if another writer > creates a contract first. ### Contract fields * `type` (required): `NONE`, `FIXED`, `PERFORMANCE`, `BONUS`, `HYBRID`, or `RULES`. A classic type must match the enabled payment sections. `RULES` carries its payments in `paymentRules` instead; see [Simplified payment terms](#simplified-payment-terms-rules). * `currency` (required): `USD`, `EUR`, `GBP`, `CAD`, `AUD`, `CHF`, `JPY`, `HKD`, `NZD`, `CNY`, `INR`, or `SGD`. * `fixedPayment` (required): a complete fixed-payment object, or `null`. * `currency`: the currency in which the fixed amount is authored. * `conversionPolicy`: `null` when this matches `contract.currency`; otherwise it must be `LEGACY_PAYMENT_REPOSITORY_FX`. * `amount`: payment amount. * `per`: `CREATOR` or `POST`. * `calculation`: `STANDARD`, `PER_POST`, `SPLIT`, `PRORATED`, or `UPLOAD_THRESHOLD`. * Also required: `upfrontPercentage`, `expectedPosts`, `minimumPosts`, `prorateByTime`, `platforms`, and `crossposts`. Use `null`, `false`, or `[]` when a field does not apply. * `upfrontPercentage` is non-null only for `SPLIT`; `expectedPosts` is non-null only for `PRORATED`; `minimumPosts` is non-null only for `UPLOAD_THRESHOLD`; `crossposts` is `EACH_POST` or `ONE_PAYMENT_PER_GROUP` only for `PER_POST`, and otherwise is `null`. `prorateByTime` can be `true` only for `STANDARD`, and `platforms` must be empty when `per` is `CREATOR`. * `cpmPayment` (required): a complete view-based payment object, or `null`. * Required: `currency`, `conversionPolicy`, `rate`, `perViews`, `viewsFrom`, `minimumViews`, `maximumViews`, `excludeMinimumViews`, `maximumSpend`, `crossposts`, and `pays`. Currency rules are the same as fixed payments. * `maximumSpend` is `null` or an object containing `amount`, `per` (`CREATOR` or `POST`), and `period` (`LIFETIME`, `DAY`, `WEEK`, or `MONTH`). * `crossposts` is `EACH_POST`, `BEST_POST`, or `COMBINE_POSTS`. `pays` is `CAMPAIGN_COMPLETION`, `NOW`, or `NOW_AND_STOP`. * `bonusPayment` (required): complete bonus rules, or `null`. * `appliesTo`: `CREATOR`, `POST`, or `BEST_POST`. * `pays`: `CAMPAIGN_COMPLETION`, `NOW`, or `NOW_AND_STOP`. See [bonus payout timing](#bonus-payout-timing) for when further tiers stop. * `rules`: `VIEWS` rules and their `minimum`/`amount` tiers. Every rule also requires `currency` and `conversionPolicy` under the same currency rules. `VIEWS` is the only supported metric. * `crosspostRequirements` (required): `minimumPlatforms`, `requiredPlatforms`, and `captionContains`, or `null`. * `captionContains`: a caption grouping override, or `null` to disable it. Matching posts are grouped by the same local calendar day, using campaign timezone, then agency timezone, then UTC. This overrides the upload window and duration tolerance and permits multiple posts from the same platform. Read [caption matching](/crosspost-groups#automatic-grouping-and-caption-matching) before using a hashtag shared by several videos. This differs from an account's tracking filter. * `recurringPayment` (required): `paymentsPerPeriod`, `period`, `weekday`, `dayOfMonth`, `startsImmediately`, `firstPaymentAt`, and `timeZone`, or `null`. * Use `weekday` only for weekly schedules and `dayOfMonth` only for a once-monthly schedule. `firstPaymentAt` must be `null` when `startsImmediately` is `true`; otherwise provide an ISO timestamp. * `postsUploadedOnOrAfter` (required): a `YYYY-MM-DD` eligibility date or `null`. ### Bonus payout timing Set `bonusPayment.pays` to one of: | Value | Behavior | | - | - | | `CAMPAIGN_COMPLETION` | Wait until the media tracking window ends before the earned bonus becomes payable. | | `NOW` | Make the currently earned bonus payable. Higher tiers can pay the additional amount later. | | `NOW_AND_STOP` | Make the currently earned bonus payable. Once a positive bonus payout settles, stop all further tiers for that rule and payout scope within the current contract instance. | `NOW_AND_STOP` is the API value for **Now, stop after payout** in Grade. It controls bonus eligibility; saving the contract does not initiate a payout. For `appliesTo: "POST"`, a payout closes the rule only for the paid post or crosspost group. Other posts or groups remain eligible. For `CREATOR` and `BEST_POST`, it closes the rule across the creator's current contract instance, including later uploads. Other bonus rules and manual bonuses are unaffected. A pending approval or processing payout reserves that rule and scope against another payout. If the reservation is released after cancellation or failure, the scope becomes eligible again. After settlement, only a verified full reversal of that payout reopens it; a partial reversal does not. Existing payouts and older approvals retain the timing recorded when they were created. Changing the contract to `NOW_AND_STOP` does not retroactively close scopes paid under `NOW`. ### Simplified payment terms (RULES) Agencies that use Simplified payment terms save terms as a payment agreement: the agreement the Grade payment terms editor and the Grade assistant save. Send it with `"type": "RULES"` and Grade stores the version exactly as the editor would store the same terms on the same date. A `RULES` contract sends the same eight fields as any contract, plus `paymentRules`: * `type`: `RULES`. * `currency` (required): `USD`, `CAD`, `GBP`, or `EUR`. * `paymentRules` (required): the payment agreement, `version` `3`. * `fixedPayment`, `cpmPayment`, `bonusPayment`, `crosspostRequirements`, and `recurringPayment` (required): `null`. Every payment, crosspost setting, and payout schedule is part of `paymentRules`. * `postsUploadedOnOrAfter` (required): the value of the version the new terms follow, which is `null` for a first contract. `RULES` terms keep that version's eligibility date, as the editor does, so this field cannot change it. The new version also keeps the payout time zone of the version it follows. A first contract uses the campaign's effective time zone. Start from an agreement you read: the history GET returns `paymentRules` on every `RULES` version, and you can send it back with your changes. Each element of `rules` is one payment component with an `id`, a `name`, and `parts`: | Part `kind` | Fields | Meaning | | - | - | - | | `PAYMENT` (required) | `reward`, `amount`, `unitSize`, `tiers`, `tierMode` | `FIXED` pays `amount`; `RATE` pays `amount` per `unitSize` views; `BONUS` pays the reached `tiers`. | | `SCOPE` (required) | `scope` | What one payment counts: `CREATOR`, `VIDEO` (each post), or `CROSSPOST_GROUP`. | | `MINIMUM` | `minimumViews`, `excludeMinimumViews` | Views a post needs before it earns. | | `VIEW_LIMIT` | `maximumViews` | Views a payment for views counts at most. | | `VIDEO_LIMIT` | `videoLimit`, `period` | Posts paid at most. `period` is `WINDOW`. | | `MONEY_LIMIT` | `spendLimit`, `period`, `spendLimitScope` | Spend cap, for the creator (`CREATOR`) or each post (`UNIT`). `period` is `WINDOW`. | | `SPLIT` | `upfrontPercentage` | Part of a fixed payment paid upfront. | | `CONDITIONS` | `conditions` | Requirements such as a number of posts before payment. | | `PLATFORMS` | `platforms` | Platforms the component pays for. | | `SELECTION` | `selection`, `metric` | Count only the creator's best post. | `period` sets the earning period for the whole agreement (`window` is `ONCE`, `ONGOING`, `DAY`, `WEEK`, `MONTH`, or `BATCH`). `qualification` holds the crosspost settings, and `payout` holds when earnings become payable. Every part needs an `id` that is unique in the agreement. Grade validates the agreement with the same rules as the editor and answers a refusal with `400` and a message that starts with `contract.paymentRules:`. Daily, weekly, and monthly agreements need their own start date: their `effectiveDate` must be `1901-01-01` or later, so they cannot use `1900-01-01`, the date that covers every upload. After a `RULES` version, send `RULES` terms. A classic type is refused after `RULES` terms. ```bash theme={null} curl -sS "$BASE_URL/sdk/v1/campaign-creators/CCR_123/contract-history" \ -X POST \ -H "Content-Type: application/json" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" \ -d '{ "basedOnVersionId": null, "effectiveDate": "2026-08-15", "contract": { "type": "RULES", "currency": "USD", "fixedPayment": null, "cpmPayment": null, "bonusPayment": null, "crosspostRequirements": null, "recurringPayment": null, "postsUploadedOnOrAfter": null, "paymentRules": { "version": 3, "period": { "window": "ONCE", "batchSize": 17 }, "rules": [ { "id": "fixed_fee", "name": "Fixed payment", "parts": [ { "id": "fixed_fee_pay", "kind": "PAYMENT", "reward": "FIXED", "amount": "500", "unitSize": 1000, "tiers": [], "tierMode": "HIGHEST" }, { "id": "fixed_fee_scope", "kind": "SCOPE", "scope": "CREATOR" } ] }, { "id": "view_pay", "name": "View payment", "parts": [ { "id": "view_pay_pay", "kind": "PAYMENT", "reward": "RATE", "amount": "2", "unitSize": 1000, "tiers": [], "tierMode": "HIGHEST" }, { "id": "view_pay_scope", "kind": "SCOPE", "scope": "CREATOR" }, { "id": "view_pay_cap", "kind": "MONEY_LIMIT", "spendLimit": "1000", "period": "WINDOW", "spendLimitScope": "CREATOR" } ] } ], "qualification": { "platforms": [], "captionIncludes": "", "minimumPlatforms": 1, "requiredPlatforms": [], "groupViews": "BEST" }, "payout": { "timing": "NOW", "date": null, "schedule": "ON_DEMAND", "weekdays": [1], "monthDays": [15], "stackMissed": true, "prorateFirstPeriod": false, "stopAfterPayment": false, "remainderTiming": "AFTER_UPFRONT", "remainderDate": null } } } }' ``` This saves a fixed payment of 500 USD and 2 USD per 1,000 views, capped at 1,000 USD for the creator. The response returns the saved contract, with `paymentRules` as Grade stored it. The agency must have Simplified payment terms. Otherwise a `RULES` contract is refused with `403`. ### Example request ```bash theme={null} curl -sS "$BASE_URL/sdk/v1/campaign-creators/CCR_123/contract-history" \ -X POST \ -H "Content-Type: application/json" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" \ -d '{ "basedOnVersionId": "CCCH_CURRENT", "effectiveDate": "2026-08-15", "contract": { "type": "HYBRID", "currency": "USD", "fixedPayment": { "currency": "USD", "conversionPolicy": null, "amount": 500, "per": "CREATOR", "calculation": "STANDARD", "upfrontPercentage": null, "expectedPosts": null, "minimumPosts": null, "prorateByTime": false, "platforms": [], "crossposts": null }, "cpmPayment": { "currency": "USD", "conversionPolicy": null, "rate": 5, "perViews": 1000, "viewsFrom": "POST", "minimumViews": 1000, "maximumViews": null, "excludeMinimumViews": false, "maximumSpend": null, "crossposts": "EACH_POST", "pays": "NOW" }, "bonusPayment": { "appliesTo": "POST", "pays": "NOW_AND_STOP", "rules": [ { "currency": "USD", "conversionPolicy": null, "metric": "VIEWS", "tiers": [ { "minimum": 1000, "amount": 10 }, { "minimum": 10000, "amount": 50 }, { "minimum": 100000, "amount": 100 } ] } ] }, "crosspostRequirements": null, "recurringPayment": null, "postsUploadedOnOrAfter": "2026-08-15" } }' ``` > [!NOTE] > > Bonus tier amounts are totals, not increments. A post with 50,000 views in > the example above earns the 10,000-view tier amount of 50. With > `NOW_AND_STOP`, paying that bonus closes the rule for that post, so reaching > 100,000 views later does not earn another bonus from that rule. ### Response Successful creation returns `201` with the public contract that was saved. ```json theme={null} { "success": true, "data": { "campaignId": "camp_123", "campaignCreatorRecordId": "CCR_123", "creatorProfileId": "CP_123", "versionId": "CCCH_NEW", "effectiveDate": "2026-08-15", "contract": { "type": "HYBRID", "currency": "USD", "fixedPayment": { "currency": "USD", "conversionPolicy": null, "amount": 500, "per": "CREATOR", "calculation": "STANDARD", "upfrontPercentage": null, "expectedPosts": null, "minimumPosts": null, "prorateByTime": false, "platforms": [], "crossposts": null }, "cpmPayment": { "currency": "USD", "conversionPolicy": null, "rate": 5, "perViews": 1000, "viewsFrom": "POST", "minimumViews": 1000, "maximumViews": null, "excludeMinimumViews": false, "maximumSpend": null, "crossposts": "EACH_POST", "pays": "NOW" }, "bonusPayment": { "appliesTo": "POST", "pays": "NOW_AND_STOP", "rules": [ { "currency": "USD", "conversionPolicy": null, "metric": "VIEWS", "tiers": [ { "minimum": 1000, "amount": 10 }, { "minimum": 10000, "amount": 50 }, { "minimum": 100000, "amount": 100 } ] } ] }, "crosspostRequirements": null, "recurringPayment": null, "postsUploadedOnOrAfter": "2026-08-15" } } } ``` ### Safeguards The endpoint applies the same contract-history safeguards as the Grade app. It will not add a version that changes protected paid or approved work, conflicts with another effective date, bypasses a pending payout approval, or changes a completed campaign where edits are not allowed. The server also checks `basedOnVersionId` twice: once before validating the contract and again in the transaction that writes it. For a first contract, the explicit `null` assertion is also checked while the creator record is locked. If the timeline changes between your read and write, the API returns `409 CONTRACT_VERSION_STALE`. Writing the same `effectiveDate` is allowed and replaces that date's version when `basedOnVersionId` identifies the existing same-date version and all other safeguards pass. ### Common errors * `400 CONTRACT_VERSION_REQUIRED`: `basedOnVersionId` is omitted or invalid; it must be a governing version ID or explicit `null` for an empty timeline * `400`: invalid date, incomplete contract, or unsupported contract terms * `401`: missing or invalid SDK credentials * `403`: a `RULES` contract for an agency without Simplified payment terms * `404`: campaign creator record not found * `409 CONTRACT_VERSION_STALE`: the governing contract version changed; read history again before retrying * `409`: no existing contract covers the effective date, or the change crosses a protected contract boundary Read the updated timeline with [Read campaign creator contract history](/campaign-creators/contract-history). # External settlements Source: https://api-docs.usegrade.com/campaign-creators/external-settlements Remove reviewed earnings from the amount payable in Grade without sending money. External settlement means the selected earnings are **no longer payable in Grade**. It does not assert that the creator received a payment. Grade sends no money, debits no wallet, and sends no creator email. These endpoints use the same settlement history, preview, confirmation, and safe undo as the dashboard. All requests require `X-Application-Id` and `X-Api-Key`. Paths below start with `/sdk/v1/campaign-creators/:campaignCreatorRecordId`. | Method and path | Scope | Purpose | | - | - | - | | `GET /external-settlements` | `payouts:read` | History and eligible recurring contract periods | | `POST /external-settlements/preview` | `payouts:write` | Review the exact items and native-currency totals | | `POST /external-settlements/apply` | `payouts:write` | Apply the reviewed settlement | | `POST /external-settlements/:settlementId/undo-preview` | `payouts:write` | Check whether undo is safe | | `POST /external-settlements/:settlementId/undo` | `payouts:write` | Restore the covered amounts to payable | ## Preview ```json theme={null} { "cutoffExclusive": "2026-11-01", "reason": "October balance closed by agreement" } ``` `cutoffExclusive` is a real calendar date interpreted in the campaign timezone. This example includes earnings through October 31. For an active creator, choose a historical boundary that has already passed. `reason` is required, 3–1000 characters. The server determines amounts; do not submit line items or amounts. For supported monthly recurring contracts, provide explicit whole contract periods: ```json theme={null} { "cutoffExclusive": "2026-11-01", "reason": "October balance closed by agreement", "monthlyPeriods": [ { "startDate": "2026-10-01", "endDateExclusive": "2026-11-01" } ] } ``` Use the `contractPeriods` from history. Partial or overlapping periods are refused. Normal external settlement does not make deferred earnings payable or end future accrual. To close a collaboration, first [offboard the creator](/campaign-creators/offboarding), then settle the frozen balance. In that case omit `monthlyPeriods` and choose a cutoff date after the offboarding instant, including the next local day when offboarding happened today. The frozen balance can include payment-rule earnings. The response is `{ "success": true, "data": ... }`. `data` contains `previewId`, `planHash`, `expiresAt`, `cutoffExclusive`, `reason`, `timeZone`, `totals` by currency, and `items` with `key`, `description`, decimal-string `amount`, and `currency`. No settlement is applied by preview. Unused previews expire after 30 minutes. ## Confirm and retry ```json theme={null} { "previewId": "creator-external-00000000-0000-4000-8000-000000000001", "planHash": "", "confirmed": true } ``` Send this to `/external-settlements/apply` using the same application that created the preview. Success returns `data.settlementId` and `data.status: "APPLIED"`. If the response is lost, retry the **same** preview ID and hash. The operation is idempotent. Changed financial evidence or an expired preview returns `409`; obtain a fresh preview and review it before confirming again. ## Undo Send `{}` to `/:settlementId/undo-preview`. If its status is `READY_TO_UNDO`, send `{ "confirmed": true }` to `/:settlementId/undo`. Grade rechecks safety at apply time. Later payments or changed financial evidence can block undo with `409`. Repeating a completed undo returns `UNDONE`. Undo never sends or reverses money. For an offboarded creator, undo restores only the frozen final balance; it does not restart earnings. Both read and write operations derive agency ownership from the API key. Completed campaigns are read-only. Unsupported contracts and unreconciled payment evidence return a conflict explaining what needs review; nothing is partially settled. # List campaign creator line items Source: https://api-docs.usegrade.com/campaign-creators/line-items See the fixed, CPM, and bonus items included in a campaign creator's calculated payment. ## POST /sdk/v1/campaign-creators/line-items/query Returns the calculated payment items for specific campaign creators or for one campaign. Each media item includes its URL and `campaignCreatorMediaId`. All requests require `X-Application-Id` and `X-Api-Key`. ### Choose creators Send exactly one of: * `campaignCreatorRecordIds`: up to 500 campaign creator record IDs. * `campaignId`: one campaign. You can also send `page` and `limit`; `limit` defaults to `100` and cannot exceed `500`. ### Optional fields * `startDate` and `endDate`: an inclusive `YYYY-MM-DD` payment range. Send both or neither. * `includeNonPayable`: include items that are not currently payable and the reason for each. Default: `true`. ### Example request ```bash theme={null} curl -sS "$BASE_URL/sdk/v1/campaign-creators/line-items/query" \ -X POST \ -H "Content-Type: application/json" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" \ -d '{ "campaignCreatorRecordIds": ["CCR_123", "CCR_456"], "startDate": "2026-07-01", "endDate": "2026-07-31", "includeNonPayable": true }' ``` To read a campaign one page at a time, use this body instead: ```json theme={null} { "campaignId": "camp_123", "page": 1, "limit": 500, "startDate": "2026-07-01", "endDate": "2026-07-31" } ``` ### Response ```json theme={null} { "success": true, "data": [ { "campaignId": "camp_123", "campaignName": "Summer launch", "campaignCreatorRecordId": "CCR_123", "creatorProfileId": "CP_123", "creatorEmail": "jordan@example.com", "effectiveTimeZone": "America/New_York", "dateRange": { "startDate": "2026-07-01", "endDate": "2026-07-31" }, "currency": "USD", "totalAmount": 550, "paymentBreakdown": { "fixed": 300, "cpm": 250, "bonus": 0, "total": 550 }, "lineItems": [ { "campaignCreatorMediaId": "CCMEDIA_123", "url": "https://www.tiktok.com/@jordan/video/123", "platform": "TIKTOK", "uploadedAt": "2026-07-08", "eligibleOn": "2026-07-08", "crosspostGroupKey": null, "paymentType": "CPM", "amount": 250, "currency": "USD", "payable": true }, { "campaignCreatorMediaId": "CCMEDIA_456", "url": "https://www.instagram.com/p/example/", "platform": "INSTAGRAM", "uploadedAt": "2026-07-10", "eligibleOn": "2026-07-10", "crosspostGroupKey": null, "paymentType": "BONUS", "amount": 0, "currency": "USD", "payable": false, "reason": "The post has not reached a bonus tier." } ] } ], "failures": [], "pagination": { "page": 1, "limit": 2, "total": 2, "totalPages": 1 } } ``` Each result includes the campaign's `effectiveTimeZone`, resolved from the campaign override, agency fallback, or `UTC`. The `dateRange` and media business dates should be interpreted in that IANA timezone. Every line item includes these three fields, including `BONUS` items and non-payable items: | Field | Meaning | | - | - | | `uploadedAt` | The post's canonical upload business date, in `YYYY-MM-DD` format, using the same stored date as fixed payments. `null` when no post or upload date applies. | | `eligibleOn` | The calculated timing eligibility date, in `YYYY-MM-DD` format. For media items, this is the upload business date for `NOW` and `NOW_AND_STOP`, or the tracking completion date for `CAMPAIGN_COMPLETION`. Fixed per-post payments use the upload business date. `null` when the calculation has no applicable date. | | `crosspostGroupKey` | The post's current crosspost group key, matching the [payout report data](/campaign-creators/payout-report-data). `null` for ungrouped posts or items with no single group. | Media-backed `BONUS` items also include `platform`. Creator-level payments can cover multiple posts and therefore have no single upload date or platform. Canonical upload dates are preserved as calendar dates; tracking-completion timestamps are converted to the campaign's `effectiveTimeZone`. `eligibleOn` describes contract timing, not when a bonus threshold was reached or when funds were sent. Other requirements can still make an item non-payable; use `payable` and `reason` for its current status. For completion-based payments without a configured tracking window, the calculation falls back to the upload date. Crosspost groups and creator-level aggregates use the date selected by the payout calculation, which can differ from the displayed post's own date. > [!NOTE] > > Bonus tiers do not stack. If the tiers pay 10 at 1,000 views and 50 at > 10,000 views, a post with 50,000 views earns 50—not 60. An unknown or inaccessible creator, a creator whose requested `endDate` predates their first contract terms, or a creator with a payout item that predates those terms is returned in `failures` without stopping the rest of the request. The failure reason distinguishes the requested-date and payout-item cases. ### Common errors * `400`: invalid selector, more than 500 creators, or incomplete date range * `401`: missing or invalid SDK credentials * `404`: selected campaign not found # List campaign creators (v2) Source: https://api-docs.usegrade.com/campaign-creators/list List campaign creators with the compact v2 response, selected fields, date-scoped performance, and pagination. ## GET /sdk/v2/campaigns/:campaignId/creators Returns the creators in one campaign. Use `fields` to request only the data your application needs. Every response includes `campaignId`, `campaignCreatorRecordId`, and `creatorProfileId` so you can use the creator in the other campaign endpoints. > [!NOTE] > > Use this v2 endpoint for new integrations. The [v1 creator list](/campaign-creators/list-v1) > remains available with its original response for existing clients. All requests require `X-Application-Id` and `X-Api-Key`. ### Path parameter * `campaignId` (required): the campaign to list. ### Query parameters * `page` (optional): page number, starting at `1`. Default: `1`. * `limit` (optional): creators per page. Default: `100`; maximum: `500`. * `fields` (optional): comma-separated response fields. * `startDate` and `endDate` (optional): an inclusive `YYYY-MM-DD` range. Send both or neither. The maximum range is 366 days. * `search` or `query` (optional): searches creator names and email addresses. * `includeHidden` (optional): set to `true` to include hidden campaign creators. * `sortBy` (optional): `creatorName`, `totalViews`, `totalLikes`, `totalComments`, or `totalShares`. * `sortOrder` (optional): `asc` or `desc`. When you use a date range, performance totals and `pendingValue` are calculated for that range. Current contract fields still describe the contract active today. Date-scoped results can only be sorted by `creatorName`. ### Available fields * Identity: `campaignId`, `campaignCreatorRecordId`, `creatorProfileId`, `creatorName`, `creatorEmail`, `isVerified`, `hidden` * Payment: `pendingValue`, `currency`, `payoutType`, `fixedRate`, `performanceRate` * Performance: `totalPosts`, `totalViews`, `totalLikes`, `totalComments`, `totalShares`, `lastCalculatedAt` * Contract: `currentContract`, `nextScheduledContract` If you omit `fields`, the response includes identity, pending payment, performance, current contract, and next scheduled contract data. ### Example request ```bash theme={null} curl -sS "$BASE_URL/sdk/v2/campaigns/camp_123/creators?page=1&limit=100&fields=creatorName,creatorEmail,pendingValue,currency,totalViews,currentContract&startDate=2026-07-01&endDate=2026-07-31" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" ``` ### Response ```json theme={null} { "success": true, "data": [ { "campaignId": "camp_123", "campaignCreatorRecordId": "CCR_123", "creatorProfileId": "CP_123", "creatorName": "Jordan Lee", "creatorEmail": "jordan@example.com", "pendingValue": 550, "currency": "USD", "totalViews": 50000, "currentContract": { "effectiveDate": "2026-07-01", "contract": { "type": "HYBRID", "currency": "USD", "fixedPayment": { "currency": "USD", "conversionPolicy": null, "amount": 300, "per": "CREATOR", "calculation": "STANDARD", "upfrontPercentage": null, "expectedPosts": null, "minimumPosts": null, "prorateByTime": false, "platforms": [], "crossposts": null }, "cpmPayment": { "currency": "USD", "conversionPolicy": null, "rate": 5, "perViews": 1000, "viewsFrom": "POST", "minimumViews": 0, "maximumViews": null, "excludeMinimumViews": false, "maximumSpend": null, "crossposts": "EACH_POST", "pays": "NOW" }, "bonusPayment": null, "crosspostRequirements": null, "recurringPayment": null, "postsUploadedOnOrAfter": null } } } ], "pagination": { "page": 1, "limit": 100, "total": 1, "totalPages": 1 }, "dateRange": { "startDate": "2026-07-01", "endDate": "2026-07-31" }, "effectiveTimeZone": "America/New_York" } ``` `effectiveTimeZone` is the IANA timezone Grade uses for the campaign after applying the campaign override, agency fallback, and final `UTC` fallback. Use it when interpreting business dates in campaign payment and contract data. ### Common errors * `400`: unsupported field, invalid pagination, or invalid date range * `401`: missing or invalid SDK credentials * `404`: campaign not found Use the returned `campaignCreatorRecordId` to [preview a payout](/campaign-creators/payout-preview), [read line items](/campaign-creators/line-items), or [read contract history](/campaign-creators/contract-history). # List campaign creators (v1 legacy) Source: https://api-docs.usegrade.com/campaign-creators/list-v1 Compatibility reference for the original v1 campaign creator response. ## GET /sdk/v1/campaigns/:campaignId/creators Returns the original campaign creator record used by existing SDK v1 clients. The response includes creator profile, role, media, payout, contract, and operational fields in one object. > [!NOTE] > > Existing clients can continue using this endpoint without changing their > response parsing. Use the [v2 creator list](/campaign-creators/list) for new > integrations and a smaller response. All requests require `X-Application-Id` and `X-Api-Key`. ### Query parameters * `page` (optional): page number, starting at `1`. Default: `1`. * `limit` (optional): creators per page. Default: `100`; maximum: `100`. * `startDate` and `endDate` (optional): an inclusive `YYYY-MM-DD` range. Send both or neither. * `search` or `query` (optional): searches creator names and email addresses. * `includeHidden` (optional): set to `true` to include hidden campaign creators. * `sortBy` (optional): `creatorName`, `totalViews`, `totalLikes`, `totalComments`, `totalShares`, or `cpmResultValue`. * `sortOrder` (optional): `asc` or `desc`. The v1 endpoint always returns the legacy record. It does not project the response with a `fields` parameter. ### Response fields Each item may include: * Creator: `creatorName`, `creatorProfileId`, `creatorImage`, `creatorEmail`, `isVerified`, `isRetainer`, `isHidden`, `testPhaseCreator`, `campaignCreatorRecordId` * Role: `roleName`, `rolePay`, `rolePayFrequency`, `rolePayFrequencyTimePeriod`, `roleColor` * Payment: `payoutType`, `campaignPaymentStatus`, `pendingValue`, `pendingManualBonusValue`, `spentValue`, `currency`, `invoiceId`, `hasCancelledPayout`, `installments`, `paidThroughUploadDate`, `waitingVideoCount` * Media and performance: `contentUrls`, `mediaCount`, `totalViews`, `totalLikes`, `totalComments`, `totalShares`, `cpmResultValue` * Contract: `contractId`, fixed-rate, CPM, crosspost, bonus, pay-cycle, and payment-template fields * Operational: fixed-media history, sheet-sync overrides, accrual cutoff, and score-calculation state Fields without a value may be `null` or omitted. `paidThroughUploadDate` is the last upload day (`YYYY-MM-DD`) the creator's contract is paid through: the latest day a reserved, settled, or ambiguous payout covers. `waitingVideoCount` counts the tracked videos uploaded after that day. When nothing is paid yet, `paidThroughUploadDate` is `null` and `waitingVideoCount` counts every tracked video. Both are `null` when the creator has no contract history. ### Example response ```json theme={null} { "success": true, "data": [ { "creatorName": "Jordan Lee", "creatorProfileId": "CP_123", "creatorImage": "https://example.com/jordan.jpg", "creatorEmail": "jordan@example.com", "isVerified": true, "isRetainer": false, "isHidden": false, "payoutType": "HYBRID", "campaignPaymentStatus": "PARTIALLY_PAID", "pendingValue": 550, "spentValue": 300, "currency": "USD", "paidThroughUploadDate": "2026-05-31", "waitingVideoCount": 1, "contentUrls": ["https://www.tiktok.com/@jordan/video/123"], "mediaCount": 4, "totalViews": 50000, "totalLikes": 3000, "totalComments": 200, "totalShares": 100, "fixedRate": 300, "performanceRate": 5, "campaignCreatorRecordId": "CCR_123" } ], "pagination": { "page": 1, "limit": 100, "total": 1, "totalPages": 1 }, "effectiveTimeZone": "America/New_York" } ``` `effectiveTimeZone` is the IANA timezone Grade uses for campaign business dates after applying the campaign override, agency fallback, and final `UTC` fallback. ### Common errors * `400`: invalid date range * `401`: missing or invalid SDK credentials * `404`: campaign not found # Move a creator between campaigns Source: https://api-docs.usegrade.com/campaign-creators/move Move an existing campaign creator and their history to another campaign in your agency. ## POST /sdk/v1/campaign-creators/:campaignCreatorRecordId/move Moves a creator's existing campaign membership to another campaign in your agency, using the same behavior as moving a creator in the Grade platform. All requests require `X-Application-Id`, `X-Api-Key`, and the `campaigns:write` API key scope. The agency comes from your credentials; do not include `agencyId` in the request. ### Path parameter * `campaignCreatorRecordId` (required): the campaign creator record to move. Get this value from the [v2 campaign creator list](/campaign-creators/list) or [v1 campaign creator list](/campaign-creators/list-v1). Use `includeHidden=true` when listing creators to find a hidden record. ### Body * `destinationCampaignId` (required): a non-empty string identifying an ongoing (`ONGOING`) campaign in the same agency. Get the campaign ID from [List campaigns](/campaigns). Both IDs accept 1–128 characters after trimming surrounding whitespace. ### Example request ```bash theme={null} curl -sS "$BASE_URL/sdk/v1/campaign-creators/CCR_123/move" \ -X POST \ -H "Content-Type: application/json" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" \ -d '{"destinationCampaignId": "camp_summer_launch"}' ``` ### Response ```json theme={null} { "success": true, "data": { "campaignCreatorRecordId": "CCR_123", "sourceCampaignId": "camp_spring_launch", "destinationCampaignId": "camp_summer_launch", "creatorProfileId": "cp_123" } } ``` ### Move behavior * The `campaignCreatorRecordId` and linked media IDs stay the same. * The creator's media, contract history, payouts, payout approvals, and associated campaign history follow the membership to the destination. Creators with existing payments can be moved. * Existing contract terms and visibility are retained. If the campaigns use different effective timezones, future calendar pay-cycle dates are realigned to the destination timezone, as in the platform. * A completed source campaign is allowed; the destination must be ongoing. * The source and destination campaign summaries are refreshed after the move. * The move does not merge memberships. An existing active creator record in the destination returns `409`. Repeating the request after a successful move returns `400` because the creator is already assigned to the destination. If a response is lost, check the destination's creator list for the same `campaignCreatorRecordId`. ### Common errors * `400`: an ID is missing or invalid, the request includes `agencyId`, the destination is the current campaign, or the destination is not ongoing * `401`: missing or invalid SDK credentials * `403`: the API key lacks `campaigns:write` * `404`: the creator record or either campaign is deleted, missing, or unavailable to your agency * `409`: the creator already has an active record in the destination campaign Missing and cross-agency resources return the same not-found response: ```json theme={null} { "success": false, "message": "Creator record or destination campaign not found" } ``` # Offboard a campaign creator Source: https://api-docs.usegrade.com/campaign-creators/offboarding Finalize earnings at a cutoff and stop future accrual while preserving paid history. Offboarding permanently ends earnings for one creator in one campaign. Grade calculates the final balance at the selected cutoff, releases earned deferred CPM and bonuses, and freezes that balance. Already-paid items stay closed. Later views, uploads, and recurring periods do not create more earnings for this record. Offboarding does not send money or settle the balance. Use the normal [payout flow](/campaign-creators/payout-preview) to pay it, or [external settlement](/campaign-creators/external-settlements) when it should no longer be payable in Grade. Contract history and prior payments remain intact. All requests require `X-Application-Id` and `X-Api-Key`. Paths below start with `/sdk/v1/campaign-creators/:campaignCreatorRecordId`. | Method and path | Scope | Purpose | | - | - | - | | `GET /offboarding` | `payouts:read` | Status and finalization receipt | | `POST /offboarding/preview` | `payouts:write` | Review the final earnings | | `POST /offboarding/apply` | `payouts:write` | Freeze the reviewed result | ## Review final earnings ```json theme={null} { "cutoffAt": "2026-11-11T10:30:00Z", "reason": "Collaboration ended by agreement" } ``` `cutoffAt` is optional; omit it to use server time now. When provided, it must be an ISO timestamp with an offset, at or before now. Grade uses recorded metrics available at the cutoff and the existing contract's earning rules. Offboarding does not invent a new prorating policy. `reason` is required, 3–1000 characters. The response is `{ "success": true, "data": ... }`. `data` contains `previewId`, `planHash`, `expiresAt`, `cutoffAt`, `reason`, `timeZone`, numeric `amount`, `currency`, `appliedAt: null`, and `items` with `key`, `description`, `amount`, and `currency`. A zero final balance is valid. Preview creates no payment and does not freeze earnings. ## Confirm ```json theme={null} { "previewId": "00000000-0000-4000-8000-000000000001", "planHash": "", "confirmed": true } ``` Send this to `/offboarding/apply` using the same application that previewed it. Unused previews expire after 30 minutes. Grade rechecks earnings and payment activity before applying. Success returns the receipt with `status: "OFFBOARDED"` and `appliedAt` populated. There is no undo operation for offboarding. Retry the same preview ID and hash after a lost response. A successful retry returns the existing receipt without finalizing twice. A stale or expired preview returns `409`; review a new preview before confirming. Finish or cancel pending payouts and approvals first. Ambiguous payment evidence, completed campaigns, missing payment terms, and records already offboarded cannot be finalized again. Financial conflicts return `409`; invalid input returns `400`; records and previews outside the API key's agency return `404`. `GET /offboarding` returns `campaignCreatorRecordId`, `campaignId`, `creatorName`, `timeZone`, `canChange`, and `offboarding` (the receipt or `null`). The receipt's amount is the original final amount; use normal payout line items for the remaining balance after payments or external settlements. In the dashboard, use the creator context menu → **Manage creator** → **Offboard creator**. # Payment adjustments and scoring Source: https://api-docs.usegrade.com/campaign-creators/payment-adjustments Set or clear a pending manual bonus, waive a recurring cycle, and control score calculation. ## Pending manual bonus `PUT /sdk/v1/campaign-creators/:campaignCreatorRecordId/pending-bonus` requires `payouts:write`. ```json theme={null} { "amount": 75, "currency": "USD" } ``` `amount` must be nonnegative. `currency` is optional; when present it is a three-letter uppercase currency code. Send `{ "amount": 0 }` to clear the pending bonus. This changes the pending bonus using the platform's currency and contract rules; it does not send money or reverse a paid payout. ## Waive a recurring cycle `POST /sdk/v1/campaign-creators/:campaignCreatorRecordId/pay-cycle-windows/waive` requires `payouts:write`. ```json theme={null} { "cycleStartAt": "2026-09-01T00:00:00Z", "reason": "Agreed unpaid warm-up cycle" } ``` Use the exact `payPeriodStart` instant from the creator's payout line items. Date-only strings are refused, since a campaign timezone or hourly cadence can place the boundary elsewhere. A reason is required (1–2000 characters). Only a due recurring window can be waived. The currently running cycle cannot be waived. A cycle in a pending or approving payout returns `409` with `APPROVAL_PENDING`. A successful response includes the waiver's ID, period boundaries, amount, currency, reason, and actor. ## Restore a waived cycle `POST /sdk/v1/campaign-creators/:campaignCreatorRecordId/pay-cycle-windows/restore` accepts the same body and scope. It revokes the live waiver and recalculates pending totals. A missing waiver returns `404`. ## Control score calculation `PATCH /sdk/v1/campaign-creators/:campaignCreatorRecordId/scoring` requires `campaigns:write`. ```json theme={null} { "enabled": false } ``` Send `true` to re-enable score calculation. The equivalent campaign-wide endpoint is `PATCH /sdk/v1/campaigns/:campaignId/scoring`. These controls govern score calculation; use [payment exclusions](/campaign-media/payment-exclusions) for payment eligibility. All writes on this page derive agency ownership from the API key and reject completed campaigns with `409`. # Preview campaign creator payouts Source: https://api-docs.usegrade.com/campaign-creators/payout-preview Calculate campaign creator payouts and see whether each one is ready to send. ## POST /sdk/v1/campaign-creators/payout-previews/query Calculates the fixed, CPM, and bonus parts of each creator's payout. The response separates payable and non-payable media and tells you whether the calculation is ready to pay. All requests require `X-Application-Id` and `X-Api-Key`. ### Choose creators Send exactly one of: * `campaignCreatorRecordIds`: up to 500 campaign creator record IDs. * `campaignId`: one campaign, with optional `page` and `limit` pagination. `limit` defaults to `100` and cannot exceed `500`. ### Optional fields * `startDate` and `endDate`: an inclusive `YYYY-MM-DD` payment range. Send both or neither. * `includeNonPayable`: include non-payable calculated line items. Default: `true`. ### Example request ```bash theme={null} curl -sS "$BASE_URL/sdk/v1/campaign-creators/payout-previews/query" \ -X POST \ -H "Content-Type: application/json" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" \ -d '{ "campaignCreatorRecordIds": ["CCR_123"], "startDate": "2026-07-01", "endDate": "2026-07-31" }' ``` ### Response ```json theme={null} { "success": true, "data": [ { "campaignId": "camp_123", "campaignName": "Summer launch", "campaignCreatorRecordId": "CCR_123", "creatorProfileId": "CP_123", "creatorEmail": "jordan@example.com", "effectiveTimeZone": "America/New_York", "dateRange": { "startDate": "2026-07-01", "endDate": "2026-07-31" }, "payout": { "currency": "USD", "fixed": 300, "cpm": 250, "bonus": 50, "total": 600 }, "payableMedia": [ { "campaignCreatorMediaId": "CCMEDIA_123", "url": "https://www.tiktok.com/@jordan/video/123", "platform": "TIKTOK", "uploadedAt": "2026-07-08", "views": 50000, "amount": 300, "currency": "USD", "paymentTypes": ["CPM", "BONUS"] } ], "nonPayableMedia": [ { "campaignCreatorMediaId": "CCMEDIA_456", "url": "https://www.instagram.com/p/example/", "platform": "INSTAGRAM", "uploadedAt": "2026-07-10", "views": 800, "reason": "The post has not reached the minimum views." } ], "otherLineItems": [], "calculation": { "status": "READY", "readyToPay": true, "message": "Ready to pay.", "calculatedAt": "2026-08-01T08:00:00.000Z" } } ], "failures": [], "pagination": { "page": 1, "limit": 1, "total": 1, "totalPages": 1 } } ``` Each preview includes the campaign's `effectiveTimeZone`, resolved from the campaign override, agency fallback, or `UTC`. Use it when interpreting payout business dates and the requested `dateRange`. An unknown or inaccessible creator, a creator whose requested `endDate` predates their first contract terms, or a creator with a payout item that predates those terms is returned in `failures` without stopping the rest of the request. The failure reason distinguishes the requested-date and payout-item cases. ### Calculation statuses * `READY`: calculation is complete. `readyToPay` is `true` only when the total is greater than zero. * `CALCULATING`: the calculated values are refreshing. Try again later. * `BLOCKED`: the payout could not be calculated. Try again later. > [!NOTE] > > Bonus tiers do not stack. The bonus value is the highest tier the creator or > post qualifies for. Use the returned `payout.total` and `payout.currency` when you [send the payout](/campaign-creators/send-payouts). Grade recalculates the amount before sending and rejects the item if it changed. If you also send `additionalLineItems`, keep `amount` equal to this calculated `payout.total`; Grade adds those one-off items at payment time. This preview does not include request-time additional items. See [Send campaign creator payouts](/campaign-creators/send-payouts) for the combined total and invoice behavior. ### Common errors * `400`: invalid selector, pagination, or date range * `401`: missing or invalid SDK credentials * `404`: selected campaign not found # Download a campaign creator payout report Source: https://api-docs.usegrade.com/campaign-creators/payout-report Download a campaign creator's payout report as a PDF for a selected date range. ## GET /sdk/v1/campaign-creators/:campaignCreatorRecordId/payout-report Returns the campaign creator's payout report as PDF data. You can display the response in a browser, embed it in a PDF viewer, or save it as a file. To read the same report row by row as JSON, use [Get payout report data](/campaign-creators/payout-report-data). All requests require `X-Application-Id`, `X-Api-Key`, and the `payouts:read` scope. ### Path parameter * `campaignCreatorRecordId` (required): the campaign creator to report on. ### Query parameters * `startDate` (required): first included activity date in `YYYY-MM-DD` format. * `endDate` (required): last included activity date in `YYYY-MM-DD` format. The dates are interpreted in the campaign's time zone. ### Example request ```bash theme={null} curl -sS "$BASE_URL/sdk/v1/campaign-creators/CCR_123/payout-report?startDate=2026-07-01&endDate=2026-07-31" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" \ --output creator-payout-report.pdf ``` ### Response * Content type: `application/pdf` * Content disposition: `inline` * Body: raw PDF bytes This endpoint does not return a JSON success wrapper when the report is generated successfully. ### Common errors * `400`: missing or invalid date range * `401`: missing or invalid SDK credentials * `403`: missing `payouts:read` scope, SDK access disabled, or origin not allowed * `404`: campaign creator record not found * `413`: the report exceeds 10,000 rows; use a shorter date range # Get payout report data Source: https://api-docs.usegrade.com/campaign-creators/payout-report-data Get the rows, amounts, and totals behind a campaign creator's payout report as JSON. ## GET /sdk/v1/campaign-creators/:campaignCreatorRecordId/payout-report/data Returns the same agency-view report used to generate the [payout report PDF](/campaign-creators/payout-report), as JSON. Use it to read each post, tracked account, and non-media line item without parsing a PDF. All requests require `X-Application-Id`, `X-Api-Key`, and the `payouts:read` API key scope. The campaign creator must belong to your application's agency. ### Parameters | Parameter | Location | Description | | - | - | - | | `campaignCreatorRecordId` | Path | Required campaign creator record ID. | | `startDate` | Query | Required first included activity date, in `YYYY-MM-DD` format. | | `endDate` | Query | Required last included activity date, in `YYYY-MM-DD` format. | Dates are inclusive and interpreted in the campaign's time zone. You can request a single day by using the same start and end date. The range selects payout activity, using the same rules as the PDF; it is not an upload-date filter. Do not send `agencyId`: the API derives it from your SDK credentials. ### Example request ```bash theme={null} curl -sS "$BASE_URL/sdk/v1/campaign-creators/CCR_123/payout-report/data?startDate=2026-07-01&endDate=2026-07-31" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" ``` ### Response The response is `application/json` with `{ "success": true, "data": ... }`. `data` contains the complete report: | Field | Contents | | - | - | | `metadata` | Creator and agency details, generation timestamp, activity range, paid status, invoice numbers, and view-snapshot coverage. | | `summary` | Post counts, total paid, total payable, and totals grouped by currency. | | `trackedAccounts` | Rows from the PDF's Tracked Accounts table. | | `resultPosts` | Rows from the PDF's Result Posts table, in report order. | | `nonMediaLineItems` | Non-media rows, including paid, payable, and informational entries. | The endpoint does not paginate or truncate rows. Empty sections are empty arrays. Reports with more than 10,000 rows across the three arrays return `413`; request a shorter activity range. The report is built when requested, just like the date-range PDF. Values can change as tracking and payout activity change between requests. ### Post rows | Fields | Contents | | - | - | | `rowNumber`, `postId`, `campaignCreatorMediaId` | Report row number, its string identifier, and the persistent campaign media ID. | | `uploadDate`, `uploadDateTimeZone` | Upload timestamp and the time zone used to display it. The timestamp can be `null`. | | `description`, `caption`, `postUrl`, `platform` | Post description, caption, link, and platform. Caption and link can be `null`. | | `views`, `viewsAsOf` | View count and optional snapshot timestamp. The snapshot timestamp can be `null`. | | `crossPostedWith`, `crosspostGroupKey`, `crosspost` | Linked report `postId` values, group key, and the PDF's crosspost label. The key and label can be `null`. | | `status`, `includedInPayout` | Report status and inclusion flag. | | `reason`, `reasons`, `reasonLinks`, `warnings` | Explanations, optional linked reports, and optional data warnings. | | `amountsApplied` | Numeric USD amounts for `fixed`, `cpm`, `bonus`, and `total`. Each is a money object. | | `componentDisplay` | Display text for `fixed`, `cpm`, and `bonus`, including explanations such as `No bonus achieved`. The PDF may display `--` for a component that does not apply. | | `payoutAmount`, `totalPaid` | Payable and already-paid money objects from the report. | | `payoutComponents`, `paidComponents` | Optional component arrays, each with `type` and an `amount` money object. | Post `status` is `PAID`, `PAYABLE`, `PAID VIA CROSSPOST`, `PAYABLE VIA CROSSPOST`, `NOT PAYABLE`, `NOT PAID`, or `null`. Linked posts remain separate rows, including rows with zero amounts. ### Tracked account rows Each row contains `accountUrl`, `platform`, `trackingStartDate`, `trackVideosFor`, `showTrackingDuration`, and `reason`. The URL and tracking start timestamp can be `null`. The PDF uses `showTrackingDuration` to decide whether to display the tracking duration. ### Non-media rows Each row contains `lineItem`, `type`, `activityDate`, `status`, `invoice`, `amount`, and `note`. The activity timestamp and invoice can be `null`. An optional `payCycleWindow` includes `startAt`, `endAt`, and `timeZone`. `status` is `Paid`, `Will be paid`, or `Not included`. The line-item types are `Bonus`, `Performance`, `Fixed`, `Platform fee`, `Rounding adjustment`, and `Other`. Amounts can be zero or negative; preserve them when exporting rows. ### Money and totals Money objects contain `amount` (a number in major currency units, not cents), `currency`, and `display` (formatted text), for example: ```json theme={null} { "amount": 50, "currency": "USD", "display": "$50.00" } ``` Use `summary.totalPaidByCurrency` and `summary.totalPayableByCurrency` for currency-specific totals. Do not add amounts with different currencies or sum the display strings. `amountsApplied` is expressed in USD; other money objects carry their own currency. ### Read rows in JavaScript ```javascript theme={null} const url = new URL( `${BASE_URL}/sdk/v1/campaign-creators/${campaignCreatorRecordId}/payout-report/data` ); url.searchParams.set('startDate', '2026-07-01'); url.searchParams.set('endDate', '2026-07-31'); const response = await fetch(url, { headers: { 'X-Application-Id': APP_ID, 'X-Api-Key': API_KEY } }); const body = await response.json(); if (!response.ok) throw new Error(body.message); for (const post of body.data.resultPosts) { console.log(post.rowNumber, post.postUrl, post.views, post.status, post.payoutAmount); } for (const item of body.data.nonMediaLineItems) { console.log(item.lineItem, item.status, item.amount, item.note); } ``` ### Common errors * `400`: missing, invalid, or reversed date range; client-supplied `agencyId` * `401`: missing or invalid SDK credentials * `403`: missing `payouts:read` scope, SDK access disabled, or origin not allowed * `404`: campaign creator record not found in your agency * `413`: report exceeds 10,000 rows; use a shorter date range * `500`: report could not be generated # Campaign quick pay Source: https://api-docs.usegrade.com/campaign-creators/quick-pay Send or submit a campaign payment for approval, with custom line items, fee allocation, and safe retries. ## POST /sdk/v1/campaign-creators/:campaignCreatorRecordId/quick-pay Send a one-off payment to an existing campaign creator, using the same direct payout flow as the campaign screen. You supply the line items and amounts. Grade records the payment as `DIRECT` against that creator and campaign, includes it in campaign spend and payout history, and creates the invoices. Quick pay does **not** settle calculated fixed fees, CPM earnings, or tiered bonuses, and does not change the creator's contract. Those earnings remain payable through [calculated campaign payouts](/campaign-creators/send-payouts). For a payment without campaign attribution, use [Payouts](/payouts). > [!WARNING] > > When agency approvals are enabled, Quick Pay always requires approval, > including requests from admins and finance users in the campaign screen. > Otherwise, it initiates payment immediately unless you set `requireApproval: true`. > Keep keys with `payouts:write` on your server. ## Prerequisites * An SDK application and API key with `payouts:write`. Use `campaigns:read` to discover records and `payouts:read` to check payment status and invoices. * An existing, active campaign creator record in your agency. Find its `campaignCreatorRecordId` through the [creator list](/campaign-creators/list). A creator profile ID or email cannot replace this record ID. * An eligible creator and usable wallets. Sufficient funds are required when payment executes, under your agency's settlement settings; submitting an approval does not reserve or debit funds. Removed or deleted records, staged creators, and test phase creators when that feature is enabled cannot be paid. ## Headers | Header | Required | Meaning | | - | - | - | | `X-Application-Id` | Yes | Your SDK application ID. | | `X-Api-Key` | Yes | An API key with `payouts:write`. | | `X-Idempotency-Key` | Yes | A unique key for this intended payment, 1–100 characters after trimming. Persist it before sending the request. | | `Content-Type` | Yes | `application/json`. | The authenticated application determines the agency. Do not send an `agencyId`, `campaignId`, recipient email, or creator profile ID in the body. ## Request body | Field | Type | Required | Meaning | | - | - | - | - | | `currency` | string | Yes | `USD`, `CAD`, `GBP`, or `EUR`, in uppercase. Applies to every line item. | | `lineItems` | array | Yes | 1–100 custom line items. The gross payout is their sum. | | `lineItems[].amount` | number | Yes | Positive amount with at most two decimal places. Send a JSON number, not a numeric string. | | `lineItems[].description` | string | No | Up to 255 characters after trimming. Omitted or blank descriptions become `Direct payout`. | | `requireApproval` | boolean | No | Defaults to `false`. Set to `true` to queue for approval even when agency approvals are disabled. `false` cannot bypass agency approvals. | | `confirmHighValuePayout` | boolean | No | Defaults to `false`. Set to `true` to acknowledge a payout above your agency's threshold. | | `platformFeePayerOverride` | object | No | Override who pays the platform fee for this payment only. Omit to inherit configured defaults. | Unknown fields are rejected, including fields inside line items and fee overrides. Amounts and their sum must fit within JavaScript's safe integer range when expressed in cents. Sub-cent amounts are rejected rather than rounded. ### Platform fees `platformFeePayerOverride` accepts one of these objects: ```json theme={null} { "mode": "INHERIT" } ``` ```json theme={null} { "mode": "CREATOR_PAYS_ALL" } ``` ```json theme={null} { "mode": "AGENCY_PAYS_ALL" } ``` ```json theme={null} { "mode": "CUSTOM_SPLIT", "agencySharePercent": 40 } ``` For `CUSTOM_SPLIT`, `agencySharePercent` is required and must be between 0 and 100 inclusive. Other modes do not accept it. This changes fee allocation, not the configured fee rate or cap. The creator's net receipt can be lower than the gross line-item sum; the agency's debit can be higher when it pays fees. ### Currency conversion and confirmation Grade converts the requested amount to the creator's existing wallet currency when needed. A new creator wallet uses the requested currency. The response includes both the requested gross total and its creator-currency equivalent. Neither amount is a guarantee of the final net receipt after fees. The high-value threshold is evaluated in your agency's preferred currency. If confirmation is required, the API returns `400` with `code: "THRESHOLD_CONFIRMATION_REQUIRED"`, `requiresThresholdConfirmation: true`, `thresholdAmount`, and `thresholdCurrency`. Review the amount, then send `confirmHighValuePayout: true` with a **new idempotency key**, because the request body has changed. Confirmation does not bypass eligibility or balance checks. ## Example request `BASE_URL` is the API origin and prefix before `/sdk/v1`, for example `https://infra-sandbox.usegrade.com/api` for sandbox or `https://infra.usegrade.com/api/email` for production. Use credentials issued for the selected environment. ```bash theme={null} curl -sS "$BASE_URL/sdk/v1/campaign-creators/CCR_123/quick-pay" \ -X POST \ -H "Content-Type: application/json" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" \ -H "X-Idempotency-Key: event-appearance-2026-10-03-001" \ -d '{ "currency": "USD", "lineItems": [ { "description": "Event appearance fee", "amount": 150 }, { "description": "Travel reimbursement", "amount": 75.5 } ], "platformFeePayerOverride": { "mode": "AGENCY_PAYS_ALL" } }' ``` ### JavaScript integration Persist your payment record, body, and idempotency key together before calling the API. Pass that same saved record to this function again after a timeout. ```javascript theme={null} async function quickPayCampaignCreator({ recordId, idempotencyKey, body }) { const response = await fetch( `${process.env.GRADE_BASE_URL}/sdk/v1/campaign-creators/${encodeURIComponent(recordId)}/quick-pay`, { method: "POST", headers: { "Content-Type": "application/json", "X-Application-Id": process.env.GRADE_APP_ID, "X-Api-Key": process.env.GRADE_API_KEY, "X-Idempotency-Key": idempotencyKey, }, body: JSON.stringify(body), }, ); const result = await response.json(); if (!response.ok) { const error = new Error(result.message || "Quick pay failed"); error.status = response.status; error.code = result.code; throw error; } return result; } ``` ## Immediate payment response — HTTP 200 ```json theme={null} { "success": true, "payoutId": "CCPAY_123", "invoiceId": "INV_CREATOR_123", "agencyInvoiceId": "INV_AGENCY_123", "transactionId": "TXN_123", "campaignId": "CAMP_123", "campaignCreatorRecordId": "CCR_123", "amount": 225.5, "currency": "USD", "creatorAmount": 225.5, "creatorCurrency": "USD", "lineItems": [ { "description": "Event appearance fee", "amount": 150 }, { "description": "Travel reimbursement", "amount": 75.5 } ] } ``` * `amount` and `currency`: the gross sum in the currency you requested. * `creatorAmount` and `creatorCurrency`: the gross amount in the creator's wallet currency. * `lineItems`: normalized descriptions and amounts in the requested currency. * `payoutId`: use with [payout status and breakdowns](/payouts). * `invoiceId` and `agencyInvoiceId`: creator and agency invoice IDs for [PDF downloads](/invoices). * `transactionId`: the agency payment transaction. `200` means the payment was initiated, or the original response was replayed. It does **not** mean the creator has received or withdrawn the funds. Check `POST /sdk/v1/payouts/status` using the same application and a key with `payouts:read`. Campaign quick pay creates no `pending_payout_id`. ## Require approval — HTTP 202 Add `"requireApproval": true` to the same request body to request review: ```json theme={null} { "currency": "USD", "requireApproval": true, "lineItems": [{ "description": "Event appearance fee", "amount": 150 }] } ``` | Agency approvals | `requireApproval` | Result | | - | - | - | | Off | Omitted or `false` | `200`: payment initiated. | | Off | `true` | `202`: queued for approval. | | On | Any value or omitted | `202`: queued for approval. | A queued request creates invoices in `PENDING_APPROVAL` and a request in the Grade **Approvals** queue. No payment transaction or wallet debit occurs at submission. Admins or finance users with access to the campaign can review it there, including when agency approvals are disabled. The submitter is displayed as **API application**. Approval uses the existing permissions and review workflow. ```json theme={null} { "success": true, "status": "PENDING", "approvalId": "cd098819-cb2c-442b-a44b-80bd1de6e0e3", "invoiceId": "INV_CREATOR_123", "agencyInvoiceId": "INV_AGENCY_123", "campaignId": "CAMP_123", "campaignCreatorRecordId": "CCR_123", "amount": 150, "currency": "USD", "creatorAmount": 150, "creatorCurrency": "USD", "lineItems": [{ "description": "Event appearance fee", "amount": 150 }] } ``` `202` means **submitted for approval**, not paid. There is no `payoutId` or `transactionId` yet. Both `200` and `202` are successful HTTP responses; check for `approvalId` before attempting to track a payout. High-value confirmation is still required when applicable and does not replace approval. Requested line items and fee allocation are frozen for review. USD settlement amounts are repriced at approval time using the current exchange rate. Wallet, funding, campaign, and creator checks still apply at execution. Rejected or cancelled requests do not execute a payment. To submit a replacement, use a new idempotency key. Changing the agency approval setting does not approve an existing pending request. ### GET /sdk/v1/campaign-creators/:campaignCreatorRecordId/quick-pay/approvals/:approvalId Read the current approval state using the **same application** that submitted it and an API key with `payouts:read`. This endpoint needs no idempotency key. It returns `404` if the approval, agency, application, or creator record does not match. A different application in the same agency cannot read the request. ```bash theme={null} curl -sS "$BASE_URL/sdk/v1/campaign-creators/CCR_123/quick-pay/approvals/$APPROVAL_ID" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" ``` ```json theme={null} { "success": true, "approvalId": "cd098819-cb2c-442b-a44b-80bd1de6e0e3", "status": "APPROVED", "campaignId": "CAMP_123", "campaignCreatorRecordId": "CCR_123", "invoiceId": "INV_CREATOR_123", "agencyInvoiceId": "INV_AGENCY_123", "payoutId": "CCPAY_123", "rejectionNote": null, "createdAt": "2026-10-05T09:00:00.000Z", "decidedAt": "2026-10-05T10:00:00.000Z" } ``` | Status | Meaning | | - | - | | `PENDING` | Waiting for review; no debit. | | `APPROVING` | Execution is in progress; poll with backoff. | | `APPROVED` | Payment initiated. Use `payoutId` with [payout status](/payouts) to track delivery. | | `REJECTED` | Review declined; `rejectionNote` contains the reason when supplied. | | `CANCELLED` | Request cancelled; no payout from this request. | `payoutId` and `decidedAt` are `null` until applicable; `rejectionNote` is nullable. After approval, the originating application can access payout status, breakdowns, and invoice PDFs using its existing `payouts:read` permission. Pending invoice IDs identify the frozen approval invoices. Invoice PDF access follows the existing agency access rules. The status endpoint returns `401` for invalid credentials, `403` for missing read permission, and `500` for a temporary read failure. Retry read failures with backoff. ## Safe retries Keys are scoped to your application and the campaign quick pay operation. The URL record ID and normalized request body are part of the request identity. Reusing a key for another creator or changed amounts returns `409`. Successful payment or approval submission and replay data commit together. Replaying a queued submission always returns its original `202` response, even after review. Use the GET approval endpoint for its current state. Completed responses have no time-based expiry. If the network times out or the server returns `500`, retry with the **same record ID, body, and key**. Do not generate a fresh key to recover an uncertain payment. A request still running returns `409`; retry it with backoff. An interrupted worker's processing lease becomes recoverable after five minutes. Business failures after processing starts, such as insufficient funds or a required high-value confirmation, are also replayed. After resolving a known failure, use a new key for the new payment attempt. Authentication and input validation failures happen before the key is claimed. ## Errors Errors return `{ "success": false, "code": "...", "message": "..." }`, except authentication and scope errors, which may omit `code`. | HTTP | Code | Meaning and next step | | - | - | - | | `400` | `INVALID_IDEMPOTENCY_KEY`, `INVALID_REQUEST` | Correct the key or request fields. No payment started. | | `400` | `CREATOR_NOT_PAYABLE`, `TEST_PHASE_CREATOR` | Resolve the creator's eligibility before a new attempt. | | `400` | `PAYOUT_PREPARATION_FAILED`, `CURRENCY_CONVERSION_FAILED` | The amount could not be prepared or the threshold could not be evaluated. | | `400` | `THRESHOLD_CONFIRMATION_REQUIRED` | Review, then explicitly confirm with a new key. | | `400` | `APPROVAL_SUBMISSION_FAILED` | Invoice or approval validation failed; no payment started. | | `400` | `PAYOUT_FAILED` | Wallet, balance, fee, or payment validation failed. `insufficientFundsDetails` may include available and required USD amounts. | | `401` | — | Missing or invalid credentials. | | `403` | — | Missing `payouts:write`, SDK access disabled, or origin disallowed. | | `404` | `NOT_FOUND` | No active campaign creator in your agency matches the record ID. | | `409` | `IDEMPOTENCY_PAYLOAD_MISMATCH` | This key belongs to a different request. | | `409` | `IDEMPOTENCY_IN_PROGRESS`, `PAYOUT_IN_PROGRESS` | Retry the original request and key with backoff. | | `500` | `INTERNAL_ERROR` | Outcome may be uncertain; retry the original request and key. | | `503` | `IDEMPOTENCY_UNAVAILABLE` | Protection unavailable; retry the original request and key. | # Send campaign creator payouts Source: https://api-docs.usegrade.com/campaign-creators/send-payouts Send calculated campaign payouts to up to 100 campaign creators in one request. ## POST /sdk/v1/campaign-creators/payouts/bulk Sends calculated campaign payouts for up to 100 creators. Each creator is recalculated immediately before payment so the amount cannot silently change between preview and payment. For a custom one-off amount that should appear in campaign spend without settling calculated earnings, use [Campaign quick pay](/campaign-creators/quick-pay). > [!WARNING] > > This endpoint sends real payouts. Call > [Preview campaign creator payouts](/campaign-creators/payout-preview) first > and verify that `calculation.readyToPay` is `true`. ### Headers * `X-Application-Id` (required) * `X-Api-Key` (required) * `X-Idempotency-Key` (required): a unique value for this payout request. Retry the same request with the same key to receive the original result without paying twice. ### Body `payouts` is a non-empty array with no more than 100 items. Each item accepts: * `campaignCreatorRecordId` (required) * `amount` (required): the exact calculated `payout.total` returned by the preview, excluding any `additionalLineItems`. * `currency` (required): the exact `payout.currency` returned by the preview. * `startDate` and `endDate` (optional): the same inclusive `YYYY-MM-DD` range used for the preview. Send both or neither. * `confirmHighValuePayout` (optional): set to `true` when the combined calculated amount and additional line items exceed your agency's payout confirmation threshold. * `additionalLineItems` (optional): up to 100 one-off items to pay on top of this CCR's calculated earnings. Omit it or send `[]` for the existing behavior. * `platformFeePayerOverride` (optional object): who pays the platform fee for this payout only, using the same format as [Campaign quick pay](/campaign-creators/quick-pay). ### Platform fee allocation Each payout can use its own fee allocation. To split the platform fee equally between your agency and a selected creator, include: ```json theme={null} { "platformFeePayerOverride": { "mode": "CUSTOM_SPLIT", "agencySharePercent": 50 } } ``` | `mode` | Meaning | | - | - | | `INHERIT` | Use the agency default, as when you omit the override. | | `CREATOR_PAYS_ALL` | The creator covers the entire platform fee. | | `AGENCY_PAYS_ALL` | Your agency covers the entire platform fee. | | `CUSTOM_SPLIT` | Your agency covers `agencySharePercent` of the fee; the creator covers the remainder. | For `CUSTOM_SPLIT`, `agencySharePercent` is required and must be a JSON number between 0 and 100 inclusive. Other modes do not accept it. Unknown fields inside the override are rejected. An invalid override rejects the whole batch before any payment executes. The override applies to this payout, including its additional line items. It does not change the agency default, save a creator preference, or change the fee rate or cap. Keep sending the calculated gross `amount` from the preview; the override changes the creator's net receipt and your agency's wallet debit. Retry with the same fee override and idempotency key. Changing or removing an override while reusing the key returns `409`. Omission and `INHERIT` are equivalent. ### Additional line items Each additional item accepts exactly two fields: | Field | Type | Meaning | | - | - | - | | `description` | string | Required invoice label, 1–500 characters after trimming. Control characters are rejected. | | `amount` | number or decimal string | Required positive amount with at most two decimal places, such as `25` or `"25.00"`. | Every additional item uses the payout's `currency`. Do not send a per-item currency, quantity, or calculated line-item metadata. Amounts, their sum, and the combined payout must fit within JavaScript's safe integer range in cents. Zero, negative, non-finite, and sub-cent amounts are rejected. The gross payout is `amount + sum(additionalLineItems[].amount)`. Grade applies its existing platform fees, wallet balance checks, and high-value confirmation to that combined amount. Each description is saved as a separate line on both invoices and in the [saved payout breakdown](/payouts). The creator's net receipt and agency's debit depend on their fee allocation. These items apply only to this payment. They do not change the contract, create recurring earnings, or replace a saved manual bonus on the CCR. This endpoint still requires payable calculated earnings; use [Campaign quick pay](/campaign-creators/quick-pay) for a standalone payment when there are none. Retry with the same idempotency key and items. Changing either an item's description or amount while reusing a key returns `409`. Identical descriptions are allowed and remain separate invoice lines. ### Example request ```bash theme={null} curl -sS "$BASE_URL/sdk/v1/campaign-creators/payouts/bulk" \ -X POST \ -H "Content-Type: application/json" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" \ -H "X-Idempotency-Key: campaign-payout-2026-07-31-001" \ -d '{ "payouts": [ { "campaignCreatorRecordId": "CCR_123", "startDate": "2026-07-01", "endDate": "2026-07-31", "amount": 600, "currency": "USD", "additionalLineItems": [ { "description": "Launch bonus", "amount": "50.00" }, { "description": "Travel expenses", "amount": "25.00" } ], "confirmHighValuePayout": true, "platformFeePayerOverride": { "mode": "CUSTOM_SPLIT", "agencySharePercent": 50 } } ] }' ``` ### Response The example pays a gross total of `675 USD`: `600 USD` calculated earnings plus `75 USD` additional items. The successful response's `amount` includes the extras. The request can contain both paid and failed items. A failure for one creator does not hide the results for the others. ```json theme={null} { "success": true, "paidCount": 1, "failedCount": 1, "results": [ { "campaignCreatorRecordId": "CCR_123", "status": "PAID", "payoutId": "pay_123", "transactionId": "txn_123", "amount": 675, "currency": "USD" }, { "campaignCreatorRecordId": "CCR_456", "status": "FAILED", "reason": "The expected payout changed. Preview the payout again." } ] } ``` Common item failures include: * the creator or campaign record was not found * the payout is still calculating or has no payable amount * the amount or currency no longer matches the current calculation * high-value confirmation is required * the agency wallet has insufficient available funds ### Request errors * `400`: missing idempotency key, invalid body, additional line items, or fee override, or more than 100 payouts. Invalid additional items or fee overrides reject the request before any payment. * `401`: missing or invalid SDK credentials * `409`: the idempotency key was reused with different data, or the original request is still running * `409` with `code: "APPROVAL_REQUIRED"`: the agency has approval mode on. This endpoint pays at once, so it pays nothing for that agency; submit the payouts for approval in Grade. The idempotency key is not used up, so you can retry it once approval mode is off. * `503`: idempotency protection is temporarily unavailable # Update campaign creator visibility Source: https://api-docs.usegrade.com/campaign-creators/visibility Hide or unhide a creator within a campaign. ## PATCH /sdk/v1/campaign-creators/:campaignCreatorRecordId/visibility Hides or unhides one campaign creator record. Visibility is scoped to this campaign membership; it does not hide the creator's profile from other campaigns. All requests require `X-Application-Id` and `X-Api-Key`. ### Path parameter * `campaignCreatorRecordId` (required): the campaign creator record to update. Get this value from the [v2 campaign creator list](/campaign-creators/list) or [v1 campaign creator list](/campaign-creators/list-v1). ### Body * `hidden` (required): a boolean. Send `true` to hide the creator or `false` to unhide the creator. ### Example request ```bash theme={null} curl -sS "$BASE_URL/sdk/v1/campaign-creators/CCR_123/visibility" \ -X PATCH \ -H "Content-Type: application/json" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" \ -d '{"hidden": true}' ``` ### Response ```json theme={null} { "success": true, "data": { "campaignCreatorRecordId": "CCR_123", "hidden": true } } ``` Hidden campaign creators are excluded from creator lists by default. Set `includeHidden=true` when listing campaign creators to retrieve them and their `campaignCreatorRecordId`, then send `{"hidden": false}` to unhide one. Repeating `{"hidden": true}` preserves the existing hide date. Unhiding clears that date, and a later hide records a new date. Analytics `summary`, `series`, and `top` can use this date as a performance cutoff with `includeHidden=false`; see [analytics](/analytics). ### Common errors * `400`: the record ID is invalid, `hidden` is missing or is not a boolean, or the request supplies an `agencyId` * `401`: missing or invalid SDK credentials * `404`: the campaign creator record does not exist or belongs to another agency # Campaign media Source: https://api-docs.usegrade.com/campaign-media Track media, manage creator content, and read performance metrics via /sdk/v1. All endpoints below require: * `X-Application-Id` * `X-Api-Key` Media can be added and tracked independently of contracts. You do not need to set up a contract before tracking a creator's media. To keep warm-up posts tracked while excluding them from fixed-rate or CPM and bonus calculations, see [Payment exclusions](/campaign-media/payment-exclusions). The API supports both exclusion and undo for posts and tracked accounts. To read or update eligibility scores for tracked posts, see [List eligibility scores](/campaign-media/eligibility-scores) and [Update eligibility scores](/campaign-media/update-eligibility-scores). To list groups by campaign-creator ID, inspect their members, or correct grouping, see [Crosspost groups](/crosspost-groups). ## GET /sdk/v1/campaigns/:campaignId/media List all tracked media across the campaign with aggregate metrics. For integrations that maintain a local copy, use [Sync campaign media](/campaign-media/sync) to download bounded pages initially and then receive changed records and removals. ### Query parameters * `query` (optional; searches creator display names) * `platform` (optional; filter by platform, e.g., `instagram`, `tiktok`, `youtube`) ### Response ```json theme={null} { "success": true, "data": [ { "campaignCreatorMediaId": "ccm_...", "mediaUrl": "https://www.tiktok.com/@creator/video/7350000000000000000", "platform": "tiktok", "mediaType": "post", "isSlideshow": true, "authorUsername": "creator", "authorDisplayName": "Creator Name", "title": "Launch video", "captionText": "Our spring launch", "hashtags": ["springlaunch", "partner"], "audioTitle": "Original sound", "audioArtist": "Creator Name", "audioIsOriginal": true, "views": 5000, "likes": 320, "comments": 15, "shares": 8 } ], "metrics": { "trackedMediaCount": 12, "trackedPostCount": 10, "trackedAccountCount": 2, "uniqueCreatorsCount": 3, "totalViews": 25000, "totalLikes": 1200, "totalComments": 80, "totalShares": 45, "totalBookmarks": 30 }, "asOfTimestamp": "2026-03-03T12:00:00.000Z" } ``` > [!NOTE] > > `asOfTimestamp` indicates when tracking metrics were last refreshed. It may be `null` if no scraping has occurred yet. > [!NOTE] > > TikTok and Instagram media rows include `isSlideshow`: `true` for carousel/slideshow posts and `false` for known non-carousel posts, including videos, Instagram Reels, and single-image Instagram posts. Successfully scraped YouTube videos and Shorts return `false`. The value is `null` when the type is not known yet or not applicable. Use this field instead of deriving carousel status from the `mediaUrl` path; `false` alone does not distinguish an Instagram Reel from a single-image post. When the platform actor supplies it, campaign media rows include normalized author fields (`authorPlatformId`, `authorUsername`, `authorDisplayName`), content fields (`title`, `captionText`, `hashtags`), audio fields (`audioPlatformId`, `audioTitle`, `audioArtist`, `audioAlbum`, `audioIsOriginal`), and `metadataCollectedAt`. Unavailable fields are `null`, and `hashtags` is an empty array when none are available. ## Account check warnings Account media rows include `accountIssue`, independently of tracking tier. It is `null` when no warning is recorded, including before the first check. A successful completed check clears it. Do not render an “OK” badge or treat `null` as proof that all historical posts were discovered. ```json theme={null} { "accountIssue": { "code": "CHECK_FAILED", "reasonCode": "INCOMPLETE_RESPONSE", "message": "The provider did not finish retrieving this account.", "checkedAt": "2026-10-19T04:05:00.000Z" } } ``` | Code | Meaning | | - | - | | `PROFILE_NOT_FOUND` | The provider explicitly reported that the profile does not exist. Check its link or username. | | `PROFILE_PRIVATE` | The provider explicitly identified a private profile. | | `NO_ACCESSIBLE_VIDEOS` | No public posts could be retrieved. This may include a login wall; it does not prove the creator has never posted. | | `CHECK_FAILED` | The check could not finish reliably. Use `reasonCode` and `message` to explain why. | `CHECK_FAILED` reasons are `ACCESS_BLOCKED`, `RATE_LIMITED`, `TIMEOUT`, `INCOMPLETE_RESPONSE`, `INVALID_RESPONSE`, `PROCESSING_FAILED`, `PROFILE_UNAVAILABLE`, `PROVIDER_UNAVAILABLE`, and `PROVIDER_ERROR`. Other codes have a `null` reason. `PROCESSING_FAILED` identifies a Grade-side failure to prepare the check or process its results, including an invalid account target or missing tracking dates. Messages are safe for display; use codes for application logic. `checkedAt` is the UTC time of the reported issue. The previous warning remains while a new check is pending. An empty date-filtered window is not an account warning, and a failed individual post does not label its parent account missing or private. Results are scoped to each account, including when several accounts share a provider run. Providers include Apify actors and the official X API. Temporary `CHECK_FAILED` results remain internal while automatic recovery is pending. If recovery succeeds, no new warning appears. If recovery finishes unsuccessfully, Grade publishes the issue and its reason. Failures with no remaining automatic recovery can be published immediately. Explicit profile availability responses do not wait for technical retries. The official X API continues retrying without a fixed attempt limit. Its first transient failure stays internal; a subsequent failure at least three hours later publishes `CHECK_FAILED` if the account check still has not completed. Retries continue, and a successful completed check clears the warning. Instagram account checks combine the required posts and reels providers. Neither provider can clear a warning while the other is pending or recovering. Conflicting availability responses become `CHECK_FAILED` with `INCOMPLETE_RESPONSE`; Grade does not assert that a profile is private or missing when another required provider succeeds. A successful posts check with no accessible reels does not itself produce a warning. ## GET /sdk/v1/campaigns/:campaignId/creators/media List a campaign creator's tracked media, broken down into accounts and posts. ### Query parameters * `email` (required) * `includeGroups` (optional; `true` to include explicit group rows) * `page` (default `1`) * `limit` (default `5`) ### Response ```json theme={null} { "success": true, "data": { "creatorEmail": "creator@example.com", "creatorProfileId": "cp_...", "campaignCreatorRecordId": "ccr_...", "accounts": [ { "campaignCreatorMediaId": "ccm_...", "mediaUrl": "https://www.instagram.com/creatorhandle", "platform": "instagram", "mediaType": "account", "isSlideshow": null } ], "posts": [ { "campaignCreatorMediaId": "ccm_...", "mediaUrl": "https://www.tiktok.com/@creator/video/7350000000000000000", "platform": "tiktok", "mediaType": "post", "isSlideshow": true, "authorUsername": "creator", "captionText": "Our spring launch", "hashtags": ["springlaunch", "partner"], "audioTitle": "Original sound", "views": 5000, "likes": 320, "comments": 15, "shares": 8 } ] }, "pagination": { "accounts": { "page": 1, "limit": 50, "totalPages": 1, "totalItems": 1 }, "posts": { "page": 1, "limit": 50, "totalPages": 1, "totalItems": 1 } }, "asOfTimestamp": "2026-03-03T12:00:00.000Z" } ``` When `includeGroups=true`, the response includes an additional `groups` array and `pagination.groups` object. Group rows also include `isSlideshow` when the winning media item has a known slideshow state. Normalized author, content, hashtag, and audio metadata on a group row comes from that group's winning media item. ### Common errors * `400`: missing `email` * `404`: creator not found in this campaign ## POST /sdk/v1/campaigns/:campaignId/creators/media Add or update tracked media for a campaign creator. If the creator is not yet a member of the campaign, they are **automatically added** (implicit membership). Background scraping is triggered automatically after media is saved. ### Body ```json theme={null} { "email": "creator@example.com", "media": [ { "mediaUrl": "https://www.instagram.com/creatorhandle", "platform": "instagram", "startDate": "2026-03-01T00:00:00.000Z", "trackForValue": 7, "trackForUnit": "DAYS" } ] } ``` > [!NOTE] > > Tracking is start-based. Provide `startDate` (or legacy `trackStartAt`) and > omit media-level end dates. For account URLs, Grade continues discovering > eligible posts automatically, while `trackForValue` and `trackForUnit` define > each discovered post's relative payable tracking window. **email** `string` *required* Creator email address. **media** `array` *required* Array of media items to track. Each item in the `media` array accepts: **media\[].mediaUrl** `string` *required* URL of the post or account to track. **media\[].platform** `string` Platform name (e.g., `instagram`, `tiktok`, `youtube`). Optional if the platform can be derived from the URL. **media\[].startDate** `string` Optional ISO date when tracking starts. If omitted, tracking starts at save time. **media\[].trackStartAt** `string` Backward-compatible alias for `startDate`. **media\[].trackForValue** `number` Relative tracking duration for discovered posts. Provide this together with `trackForUnit`, for example `7` with `DAYS`. **media\[].trackForUnit** `string` Relative tracking unit. Must be `DAYS` or `MONTHS` when `trackForValue` is provided. ### Relative tracking windows Use `trackForValue` and `trackForUnit` to choose how long each discovered post is tracked after it is uploaded. Examples: * 7-day window: `"trackForValue": 7`, `"trackForUnit": "DAYS"` * 30-day window: `"trackForValue": 30`, `"trackForUnit": "DAYS"` * 2-month window: `"trackForValue": 2`, `"trackForUnit": "MONTHS"` For example, if a creator uploads a video on March 1 and you send `trackForValue: 7` with `trackForUnit: "DAYS"`, Grade counts the video's views for the first 7 days after upload. If the campaign pays CPM or bonuses after tracking completes, the video becomes payable after that 7-day window is complete. **media\[].captionFilter** `string` Selects which posts to track from an account-type URL (max 256 characters). Only applies to account media. This does not change crosspost grouping rules. The contract's [caption grouping override](/crosspost-groups#automatic-grouping-and-caption-matching) is a separate setting. **media\[].campaignCreatorMediaId** `string` Existing media record ID to update. Omit to create a new media entry. ### Response ```json theme={null} { "success": true, "data": { "campaignId": "camp_...", "creatorEmail": "creator@example.com", "creatorProfileId": "cp_...", "campaignCreatorRecordId": "ccr_...", "saved": true } } ``` ### Common errors * `400`: missing `email` or `media` * `400`: `startDate` is invalid * `400`: `endDate` and `trackEndAt` are not supported for creator media. Use `trackForValue` and `trackForUnit` for relative tracking windows. * `400`: `trackForValue` and `trackForUnit` must be provided together * `400`: `trackForUnit` must be `DAYS` or `MONTHS` ## DELETE /sdk/v1/campaigns/:campaignId/creators/media Remove a tracked media item from a campaign creator. ### Body ```json theme={null} { "email": "creator@example.com", "campaignCreatorMediaId": "ccm_..." } ``` ### Response ```json theme={null} { "success": true, "data": { "campaignId": "camp_...", "creatorEmail": "creator@example.com", "creatorProfileId": "cp_...", "campaignCreatorRecordId": "ccr_...", "campaignCreatorMediaId": "ccm_...", "removed": true } } ``` ### Common errors * `400`: missing `email` or `campaignCreatorMediaId` * `404`: media item not found ## GET /sdk/v1/campaigns/:campaignId/media/discovered-posts List posts discovered for an account-type media item. When you track an account URL (e.g., `https://www.instagram.com/creatorhandle`), the system periodically discovers new posts from that account and tracks them automatically. ### Query parameters * `sourceCampaignCreatorMediaId` (required; the account media item ID) * `page` (default `1`) * `limit` (default `5`) * `startDate` / `endDate` (optional, `YYYY-MM-DD`; provide both together) * `performanceWindowDays` (optional integer, 1-366) By default, metric fields such as `views` return the latest cumulative scrape value. When `startDate` and `endDate` are provided, those same fields return the metric delta for that date range, using the latest scrape inside the range minus the latest scrape before the range. When `performanceWindowDays` is provided, each post uses its own `uploadDate` as the window start and returns the metric delta for the first N days after that upload. Use either `startDate` / `endDate` or `performanceWindowDays`, not both. Windowed responses also include `viewsTotal`, `likesTotal`, `commentsTotal`, `sharesTotal`, and `metricsWindow` so you can distinguish the current cumulative totals from the requested window deltas. If `performanceWindowDays` is requested but a post does not yet have an `uploadDate`, window metric fields are `null` and `metricsWindow.status` is `missingUploadDate`. ### Response ```json theme={null} { "success": true, "data": [ { "campaignCreatorMediaId": "ccm_...", "mediaUrl": "https://www.tiktok.com/@creator/video/7350000000000000001", "platform": "tiktok", "isSlideshow": false, "authorUsername": "creator", "captionText": "A newly discovered post", "hashtags": ["partner"], "audioTitle": "Original sound", "views": 1200, "likes": 85, "comments": 5, "uploadDate": "2026-03-01T14:22:00.000Z" } ], "pagination": { "page": 1, "limit": 50, "totalPages": 1, "totalItems": 3 } } ``` Example first-7-days response: ```json theme={null} { "success": true, "data": [ { "campaignCreatorMediaId": "ccm_...", "mediaUrl": "https://www.tiktok.com/@creator/video/7350000000000000001", "isSlideshow": false, "views": 4200, "viewsTotal": 8900, "uploadDate": "2026-03-01T14:22:00.000Z", "metricsWindow": { "mode": "performanceWindowDays", "days": 7, "startAt": "2026-03-01T14:22:00.000Z", "endAt": "2026-03-08T14:22:00.000Z", "status": "ready", "asOfTimestamp": "2026-03-08T12:15:00.000Z" } } ], "pagination": { "page": 1, "limit": 50, "totalPages": 1, "totalItems": 1 } } ``` ### Common errors * `400`: missing `sourceCampaignCreatorMediaId` * `400`: `startDate` and `endDate` must be provided together * `400`: `performanceWindowDays` must be an integer between 1 and 366 * `400`: use either `startDate` / `endDate` or `performanceWindowDays`, not both * `404`: source media item not found or does not belong to your agency # List media eligibility scores Source: https://api-docs.usegrade.com/campaign-media/eligibility-scores List tracked campaign posts and their current eligibility scores. ## GET /sdk/v1/campaign-media/eligibility-scores Lists tracked campaign posts and their eligibility scores. Account-tracking rows are not included. All requests require `X-Application-Id` and `X-Api-Key`. ### Query parameters * `campaignId` (optional): limit results to one campaign. * `page` (optional): page number, starting at `1`. Default: `1`. * `limit` (optional): posts per page. Default: `100`; maximum: `500`. ### Example request ```bash theme={null} curl -sS "$BASE_URL/sdk/v1/campaign-media/eligibility-scores?campaignId=camp_123&page=1&limit=500" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" ``` ### Response `score` is `null` when no score has been provided yet. ```json theme={null} { "success": true, "data": [ { "campaignCreatorMediaId": "CCMEDIA_123", "campaignCreatorRecordId": "CCR_123", "campaignId": "camp_123", "url": "https://www.tiktok.com/@jordan/video/123", "platform": "TIKTOK", "score": 82.5 } ], "pagination": { "page": 1, "limit": 500, "total": 1, "totalPages": 1 } } ``` ### Common errors * `400`: invalid pagination or a limit greater than 500 * `401`: missing or invalid SDK credentials Use `campaignCreatorMediaId` with [Update media eligibility scores](/campaign-media/update-eligibility-scores). # Manage campaign media Source: https://api-docs.usegrade.com/campaign-media/management Refresh campaign accounts and posts, freeze performance payments, restore media, and edit tracking or metrics. All writes below require `campaigns:write`. IDs must belong to the API key's agency. Completed campaigns return `409` with `code: "CAMPAIGN_COMPLETED"`; reopen the campaign before editing. Deleted or retired media cannot be edited, except a soft-deleted row can be restored explicitly. ## Refresh an account or post `POST /sdk/v1/campaign-media/:campaignCreatorMediaId/refresh` Use the `campaignCreatorMediaId` returned by the [campaign media API](/campaign-media). An account refresh checks for new posts within its existing tracking settings; a post refresh updates that post's metrics. Send an empty JSON object or omit the body. This operation keeps the account's original tracking start date. ```bash theme={null} curl -X POST "$BASE_URL/sdk/v1/campaign-media/$CAMPAIGN_MEDIA_ID/refresh" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" \ -H "Content-Type: application/json" \ -d '{}' ``` A `200` response confirms the scrape was queued; execution is asynchronous. ```json theme={null} { "success": true, "data": { "campaignCreatorMediaId": "CCMEDIA_...", "campaignId": "CMP_...", "manualRefreshCount": 1, "manualRefreshLastRequestedAt": "2026-10-28T10:00:00.000Z", "refreshLimit": 3, "refreshCooldownMs": 14400000 } } ``` Each account or post shares its allowance with refreshes requested in the app: three manual refreshes total, with a four-hour cooldown after each successfully queued refresh. The count increases only when work is queued. | Status | Code | Meaning | | - | - | - | | `409` | `CCM_REFRESH_ALREADY_IN_PROGRESS` | A refresh is already running. | | `409` | `CCM_REFRESH_LIMIT_REACHED` | All three manual refreshes have been used. | | `429` | `CCM_REFRESH_COOLDOWN` | Wait until `data.refreshAvailableAt` before retrying. | | `409` | `CCM_REFRESH_NOT_SUPPORTED` | The media cannot be scraped, for example an uploaded file. | | `503` | `CCM_REFRESH_QUEUE_FAILED` | Work could not be queued; no refresh allowance was consumed. | For standalone tracked content, use [tracked-media scrape-now](/analytics). Campaign media IDs cannot be used with that standalone endpoint. ## Freeze and unfreeze performance `POST /sdk/v1/campaign-media/:campaignCreatorMediaId/freeze-performance` ```json theme={null} { "notes": "Warm-up period", "pausedAt": "2026-10-01T00:00:00Z" } ``` Both fields are optional; omitting `pausedAt` uses the current time. This opens a performance-pause window for CPM and performance bonuses. Tracking continues. Fixed-rate eligibility is controlled by [payment exclusions](/campaign-media/payment-exclusions). `POST /sdk/v1/campaign-media/:campaignCreatorMediaId/unfreeze-performance` ```json theme={null} { "unpausedAt": "2026-10-15T00:00:00Z" } ``` Omit `unpausedAt` to resume at the current time. This closes the pause window; it does not erase its history. The same platform validation and grouped-media rules apply. > [!NOTE] > > To make a warm-up post ineligible for both fixed and performance payments, use both payment-exclusion operations. Setting a score to zero is not a substitute for payment eligibility. ## Restore deleted media `POST /sdk/v1/campaign-media/:campaignCreatorMediaId/restore` with `{}` restores a soft-deleted row using its original ID and history. Restoring an account also restores its eligible discovered posts under the platform's restore rules. Media limits still apply. Tracking-retired rows cannot be restored through this operation. ## Restart account tracking `POST /sdk/v1/campaign-media/:campaignCreatorMediaId/restart-tracking` ```json theme={null} { "effectiveFrom": "2026-10-01T00:00:00Z" } ``` Use an account media ID. This restarts account tracking from the supplied instant using the same history-preserving rules as the platform. It can retire old child posts and schedule account discovery; it is not a generic refresh button. Existing payout and approval protections still apply. ## Change account tracking settings `PATCH /sdk/v1/campaign-media/:campaignCreatorMediaId/tracking-settings` ```json theme={null} { "trackStartAt": "2026-10-01", "trackForValue": 30, "trackForUnit": "DAYS" } ``` All three fields are required. `trackForUnit` is `DAYS` or `MONTHS`; `trackForValue` is a positive integer. The platform applies the settings to the account and eligible child posts while preserving protected history. ## Enter manual analytics `PUT /sdk/v1/campaign-media/:campaignCreatorMediaId/manual-analytics` ```json theme={null} { "views": 12000, "likes": 650, "comments": 48, "shares": 20, "bookmarks": 10 } ``` Provide at least one metric. Values must be integers from `0` through `9007199254740991` (JavaScript's maximum safe integer); larger values return `400`. Counts above the 32-bit integer limit are supported. Use a post ID, not an account. The operation writes a manual snapshot, recalculates affected summaries, and uses the existing platform rules for omitted metrics. Review the resulting analytics before sending a payout. Successful writes return `{ "success": true, "data": ... }` with the operation's result and, where applicable, a message. These operations do not send a payout. # Exclude media from payments Source: https://api-docs.usegrade.com/campaign-media/payment-exclusions Keep posts tracked while excluding them from fixed-rate or CPM and bonus calculations, and undo those exclusions. Use payment exclusions to keep warm-up posts tracked without including them in the corresponding payment calculations. Fixed-rate and performance exclusions are independent: apply both when a post should contribute to neither. All requests require `X-Application-Id`, `X-Api-Key`, and the `campaigns:write` scope. No request body or idempotency key is required. ## Endpoints All four endpoints use `POST`: | Path | Effect | | - | - | | `/sdk/v1/campaign-media/:campaignCreatorMediaId/exclude-fixed-rate` | Exclude the media from applicable fixed-rate calculations. | | `/sdk/v1/campaign-media/:campaignCreatorMediaId/unexclude-fixed-rate` | Undo its fixed-rate exclusion. | | `/sdk/v1/campaign-media/:campaignCreatorMediaId/exclude-performance` | Exclude the media from CPM and bonus calculations. | | `/sdk/v1/campaign-media/:campaignCreatorMediaId/unexclude-performance` | Undo its CPM and bonus exclusion. | ### Path parameter `campaignCreatorMediaId` is the ID of a tracked post or account returned by [Campaign media](/campaign-media). It must contain 1–128 characters. Grade resolves the campaign from this media ID and checks that it belongs to your agency. Do not supply `agencyId` or `campaignId` in the body or query string. ### Exclude a warm-up post ```bash theme={null} curl --fail-with-body -sS \ "$BASE_URL/sdk/v1/campaign-media/CCMEDIA_123/exclude-fixed-rate" \ -X POST \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" curl --fail-with-body -sS \ "$BASE_URL/sdk/v1/campaign-media/CCMEDIA_123/exclude-performance" \ -X POST \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" ``` Check each response: the two operations are separate requests. Neither changes the post's eligibility score or stops tracking. These exclusions do not require score-based payment filtering to be enabled. ### Undo an exclusion Use the corresponding `unexclude-` endpoint for the same media ID: ```bash theme={null} curl --fail-with-body -sS \ "$BASE_URL/sdk/v1/campaign-media/CCMEDIA_123/unexclude-performance" \ -X POST \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" ``` To undo both exclusions, also call `unexclude-fixed-rate`. ### Response Fixed-rate endpoints return `isFixedRateExcluded`; performance endpoints return `isPerformanceExcluded`. The flag is `true` after excluding and `false` after undoing the exclusion. ```json theme={null} { "success": true, "data": { "campaignCreatorMediaId": "CCMEDIA_123", "campaignId": "camp_123", "campaignCreatorRecordId": "CCR_123", "isAccount": false, "isPerformanceExcluded": true } } ``` Grade refreshes the affected creator's payment summaries after a change. ## Payment and account behavior * An account exclusion also applies to its linked posts. To re-include an individual post, first undo the corresponding exclusion on its parent account. * Undoing an account exclusion preserves exclusions set on individual posts. * Exclusions change payment eligibility; they do not reverse existing payments or cancel a creator-level flat fee that is independent of individual posts. * Undoing an exclusion restores eligibility under the existing payment terms. It does not start a new earnings window: earlier tracked activity can become payable. Other eligibility rules, including scores and contract dates, still apply. * Completed campaigns are read-only. Deleted or retired media cannot be changed through these endpoints. ## Common errors | Status | Meaning | | - | - | | `400` | Invalid media ID, client-supplied `agencyId` or `campaignId`, or undo requested when the media is not directly excluded (`NOT_EXCLUDED`). | | `401` | Missing or invalid SDK credentials. | | `403` | The API key lacks `campaigns:write`. | | `404` | Media is unavailable or belongs to another agency. | | `409` | The campaign is completed, the media is already excluded (`ALREADY_EXCLUDED`), or its parent account is still excluded (`ACCOUNT_EXCLUDED`). | Repeating an exclusion returns `409` with `ALREADY_EXCLUDED`; repeating an undo returns `400` with `NOT_EXCLUDED`. These responses leave the existing state unchanged. # Sync campaign media Source: https://api-docs.usegrade.com/campaign-media/sync Keep a local campaign media copy current with bounded pages, changed records, and removals. This endpoint is part of [Syncing](/syncing/overview). Its URL, cursor format, and record identity remain unchanged. ## GET /sdk/v1/campaigns/:campaignId/media/sync Use this endpoint when you keep a local copy of campaign media. The first run downloads the current records in pages. Later runs return records affected by changes and IDs to remove. Each `data` item is a **complete replacement record** with the same fields as the [campaign media list](/campaign-media). Requests require `X-Application-Id`, `X-Api-Key`, and the `campaigns:read` scope. The existing `/media` endpoint continues to return its complete list. ## One cursor for pages and future polls 1. Start without a cursor and with an empty local collection for this campaign. 2. Upsert every `data` item by `campaignCreatorMediaId`; delete every `removedIds` entry. 3. Save `nextCursor` **in the same local transaction** as those changes. 4. If `hasMore` is `true`, request the next page using `cursor=nextCursor`. 5. Otherwise, keep the cursor and use it the next time you poll. An empty response is normal. Save its cursor too. Continue while `hasMore` is true even if `data` is empty: a page can contain only removals. > [!NOTE] > > Cursors have no time-based expiry. You can pause polling, restart your service, > rotate an API key, or change the page size and continue with the saved cursor. > There is no routine full reload after a retention window. ### Query parameters | Parameter | Behavior | | - | - | | `cursor` | Opaque value from the previous response. Omit only to start a new copy. | | `limit` | Maximum IDs processed per page: 1–100, default 100. Removals count toward this limit. | | `platform` | Optional platform for a new sync, for example `tiktok`. Case-insensitive. | | `query` | Optional creator display-name search for a new sync, at most 256 characters. | Filters are saved in the cursor, so you can omit them on subsequent calls. Use a separate local collection and a new cursor when starting a different filtered view. A record that leaves a filtered view appears in `removedIds`. Pages also target 1 MiB of record data. A single larger record is returned intact. The number of returned records can therefore be lower than `limit`. ### Example request ```bash theme={null} curl --get "$BASE_URL/sdk/v1/campaigns/$CAMPAIGN_ID/media/sync" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" \ --data-urlencode "cursor=$SAVED_CURSOR" \ --data-urlencode "limit=100" ``` Omit the `cursor` argument on the first request. ### Response ```json theme={null} { "success": true, "data": [ { "campaignCreatorMediaId": "CCMEDIA_123", "creatorProfileId": "CP_123", "creatorName": "Jordan", "creatorEmail": "jordan@example.com", "platform": "TIKTOK", "thumbnail": null, "mediaUrl": "https://www.tiktok.com/@jordan/video/7350000000000000000", "authorPlatformId": null, "authorUsername": "jordan", "authorDisplayName": "Jordan", "title": null, "captionText": "Launch day", "hashtags": [], "audioPlatformId": null, "audioTitle": null, "audioArtist": null, "audioAlbum": null, "audioIsOriginal": null, "metadataCollectedAt": null, "isSlideshow": false, "mediaFile": false, "isAccount": false, "accountIssue": null, "views": 12500, "likes": 420, "comments": 38, "shares": 21, "bookmarks": 9, "score": null, "trackingTier": null, "tierChangedAt": null } ], "removedIds": ["CCMEDIA_OLD"], "hasMore": false, "nextCursor": "opaque-cursor" } ``` `removedIds` covers deletion, tracking retirement, movement to another campaign, creator removal, and records that no longer match your filters. Deleting a local ID you do not have is harmless. Restored records return as complete upserts. The sync also captures metric changes, creator names and email addresses, agency display names, metadata, and account totals affected by child posts. It sends the latest available state, so multiple changes to one record can become one upsert. It is not an audit history of every intermediate edit. ## Changes during paging and retries Pages read current records. Changes during a run can appear in a later page or on the next poll. The cursor preserves changes committed after the run began, including transactions that were already in progress. A run finishes after its bounded set of IDs; ongoing writes do not require a frozen database transaction. Delivery is at least once. A record may repeat during retries, concurrent edits, or catch-up. Apply complete replacements and removals idempotently. Serialize requests and page application for each local copy so an older response cannot overwrite a newer one. Independent integrations may maintain independent cursors. If a request or local transaction fails, retain your data and retry the last saved cursor. Never clear your local collection on an API error. Only start without a cursor when intentionally creating a new local copy. Campaign-wide `metrics` and `asOfTimestamp` are not included. For totals from your local copy, avoid counting both an account's aggregate and its child posts. ## Client example The repository demo exports `mediaSync` from `sdk-demo/backend/src/sdkClient.js`. It follows pages sequentially and stops on an API or storage error. Supply your own transaction implementation: ```javascript theme={null} const { mediaSync } = require('./src/sdkClient'); // Load the cursor for this agency, campaign, and optional filter scope. // Run only one worker at a time for this local copy. const cursor = await store.readCursor(syncScope); await mediaSync.run(campaignId, { cursor, limit: 100, applyPage: async ({ data, removedIds, nextCursor }) => { await store.transaction(async (tx) => { for (const media of data) { await tx.replaceMedia(syncScope, media.campaignCreatorMediaId, media); } for (const id of removedIds) { await tx.deleteMedia(syncScope, id); } await tx.saveCursor(syncScope, nextCursor); }); } }); ``` The `store` methods above represent your database adapter. The API client and page loop are provided; your adapter must make the page and cursor atomic. ### Errors * `400`: malformed parameters, a damaged cursor, a cursor for another campaign or agency, or filters different from the cursor's saved filters. * `401` or `403`: invalid credentials or insufficient scope. Fix authorization and retain your saved cursor. * `404`: the campaign is unavailable to the authenticated agency. * `429` or `5xx`: follow `Retry-After` when present; otherwise retry with backoff using the same cursor. Cursor age is not an error condition. Cursors are continuation state, not credentials; every request still checks your current authorization. # Update media eligibility scores Source: https://api-docs.usegrade.com/campaign-media/update-eligibility-scores Apply eligibility scores to up to 500 tracked campaign posts in one request. ## POST /sdk/v1/campaign-media/eligibility-scores/bulk Applies eligibility scores to up to 500 tracked posts. Grade verifies every `campaignCreatorMediaId` belongs to your agency before saving it. All requests require `X-Application-Id` and `X-Api-Key`. ### Body `scores` is a non-empty array with no more than 500 items. Each item requires: * `campaignCreatorMediaId`: the ID returned by campaign media or the eligibility score list. * `score`: a number from `0` through `100`. Values are stored to two decimal places. Each media ID can appear only once in a request. ### Example request ```bash theme={null} curl -sS "$BASE_URL/sdk/v1/campaign-media/eligibility-scores/bulk" \ -X POST \ -H "Content-Type: application/json" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" \ -d '{ "scores": [ { "campaignCreatorMediaId": "CCMEDIA_123", "score": 82.5 }, { "campaignCreatorMediaId": "CCMEDIA_456", "score": 67 } ] }' ``` ### Response The response follows the input order and reports each item separately. Media that was not found or does not belong to your agency is skipped. ```json theme={null} { "success": true, "appliedCount": 1, "failedCount": 1, "results": [ { "campaignCreatorMediaId": "CCMEDIA_123", "status": "APPLIED", "score": 82.5 }, { "campaignCreatorMediaId": "CCMEDIA_456", "status": "FAILED", "reason": "Campaign creator media was not found." } ] } ``` After scores are applied, Grade refreshes the affected creators' calculated payment summaries. For warm-up posts that should remain tracked but be excluded from payments, use [Payment exclusions](/campaign-media/payment-exclusions). Those controls operate independently of score-based payment filtering and support undo. ### Common errors * `400`: empty batch, invalid score, duplicate media ID, or more than 500 items * `401`: missing or invalid SDK credentials # Campaigns Source: https://api-docs.usegrade.com/campaigns Create, list, update, and delete campaigns, and manage campaign creators via /sdk/v1. All endpoints below require: * `X-Application-Id` * `X-Api-Key` ## GET /sdk/v1/campaigns List campaigns for your agency with optional filtering, sorting, and pagination. ### Query parameters * `page` (default `1`) * `limit` (default `50`) * `search` or `query` (optional; searches campaign name) * `sortBy` (optional) * `sortOrder` (`asc` or `desc`) * `status` (optional) * `campaignStatuses` (optional; comma-separated) * `paymentStatuses` (optional; comma-separated) * `timeStart` and `timeEnd` (optional; ISO timestamps) * `endingBefore` (optional; ISO timestamp) * `endingDate` (optional; ISO timestamp) ### Response ```json theme={null} { "success": true, "data": [ { "campaignId": "camp_...", "campaignName": "Spring launch", "campaignStatus": "ONGOING", "tiktokScrapeCountryCode": null, "startDate": "2026-03-01T00:00:00.000Z", "endDate": null, "timeZone": "America/New_York", "agencyTimeZone": "America/Los_Angeles", "effectiveTimeZone": "America/New_York" } ], "pagination": { "page": 1, "limit": 50, "totalPages": 1, "totalItems": 1 }, "asOfTimestamp": "2026-03-03T12:00:00.000Z", "metrics": { "campaignCount": 1, "totalCreatorsCount": 5, "pendingValue": 0, "spentValue": 500, "committedValue": 1000, "totalViews": 25000, "totalLikes": 1200, "totalComments": 80, "totalShares": 45 } } ``` `timeZone` is the campaign override and may be `null`. `agencyTimeZone` is the agency default and may also be `null`. `effectiveTimeZone` is always present and resolves in this order: campaign timezone, agency timezone, then `UTC`. ## TikTok scraping country Grade can enable scraping locations for your agency. Check [SDK settings](/settings) for access and the supported country list. Set `tiktokScrapeCountryCode` to a supported uppercase country code, such as `"VN"`, on campaign creation or update. Send `null` to use default scraping; omitting the field on update preserves the saved value. List and detail responses include the saved value. The country applies to subsequent TikTok account discovery and video refreshes for this campaign, including manual refreshes and retries. It does not change campaign timezone or trigger an immediate scrape. If Grade disables agency access, scraping returns to default and the saved country is retained. ```json theme={null} { "tiktokScrapeCountryCode": "VN" } ``` Creating or updating this field requires `campaigns:write` and agency access. An unsupported code returns `400` (`INVALID_TIKTOK_SCRAPE_COUNTRY`); disabled agency access returns `403` (`TIKTOK_SCRAPE_LOCATION_DISABLED`). Completed campaigns cannot change country (`403`, `CAMPAIGN_COMPLETED`). ## POST /sdk/v1/campaigns Create a campaign. Campaigns are created as **active** (`ONGOING`). ### Body ```json theme={null} { "campaignName": "Summer campaign", "startDate": "2026-06-01", "endDate": "2026-08-31", "campaignDescription": "Influencer campaign for summer product line", "brandId": "brand_...", "timeZone": "America/New_York", "activate": true } ``` **campaignName** `string` *required* Campaign name. You can also use `campaignTitle` as an alias. **startDate** `string` *required* Campaign start date (ISO format). **endDate** `string` Campaign end date (ISO format). Omit for open-ended campaigns. **campaignDescription** `string` Free-text description. **brandId** `string` Associate the campaign with an existing brand. **timeZone** `string` Optional IANA timezone name, such as `America/New_York` or `Europe/Paris`. Omit it or send `null` to inherit the agency timezone. Use the [timezone catalog](/timezones) to get accepted names and display labels. **activate** `boolean` (default: true) Optional. If provided, this must be `true`. `false` is not supported in SDK campaign creation. ### Response ```json theme={null} { "success": true, "data": { "campaignId": "camp_...", "campaignStatus": "ONGOING", "tiktokScrapeCountryCode": null, "timeZone": "America/New_York", "agencyTimeZone": "America/Los_Angeles", "effectiveTimeZone": "America/New_York" } } ``` ### Common errors * `400`: missing `campaignName` or `startDate` * `400`: `activate` is invalid or set to `false` * `400`: `timeZone` is not a valid IANA timezone ## GET /sdk/v1/campaigns/:campaignId Fetch a single campaign with its details and high-level analytics in one response. ### Response ```json theme={null} { "success": true, "data": { "campaign": { "campaignId": "camp_...", "campaignName": "Summer campaign", "campaignStatus": "ONGOING", "tiktokScrapeCountryCode": null, "startDate": "2026-06-01T00:00:00.000Z", "endDate": "2026-08-31T00:00:00.000Z", "campaignDescription": "Influencer campaign for summer product line", "timeZone": "America/New_York", "agencyTimeZone": "America/Los_Angeles", "effectiveTimeZone": "America/New_York" }, "analytics": { "totalCreators": 5, "totalViews": 25000, "totalLikes": 1200, "totalComments": 80, "totalShares": 45 } }, "asOfTimestamp": "2026-03-03T12:00:00.000Z" } ``` > [!NOTE] > > `asOfTimestamp` indicates when media tracking metrics were last refreshed. It may be `null` if no media has been tracked yet. ### Common errors * `404`: campaign not found or does not belong to your agency ## PATCH /sdk/v1/campaigns/:campaignId Update a campaign. All fields are optional; only the fields you include are changed. ### Body ```json theme={null} { "campaignName": "Updated campaign name", "startDate": "2026-06-15", "endDate": "2026-09-30", "campaignDescription": "Revised description", "brandId": "brand_...", "timeZone": "Europe/Paris" } ``` **timeZone** `string | null` IANA timezone name for the campaign. Send `null` to clear the override and inherit the agency timezone. Use the [timezone catalog](/timezones) to get accepted names and display labels. Set `endDate`, `campaignDescription`, `brandId`, or `timeZone` to `null` to clear it. When an effective timezone changes, Grade realigns future calendar pay-cycle dates for campaign creators. ### Response ```json theme={null} { "success": true, "data": { "campaignId": "camp_...", "updated": true, "tiktokScrapeCountryCode": null, "timeZone": "Europe/Paris", "agencyTimeZone": "America/Los_Angeles", "effectiveTimeZone": "Europe/Paris" } } ``` ### Common errors * `400`: no updatable field was provided or `timeZone` is invalid * `404`: campaign not found or does not belong to your agency ## DELETE /sdk/v1/campaigns/:campaignId Soft-delete a campaign. ### Response ```json theme={null} { "success": true, "data": { "campaignId": "camp_...", "deleted": true } } ``` ### Common errors * `404`: campaign not found or does not belong to your agency * `409`: cannot delete because payouts already exist for this campaign *** ## Campaign creators Campaign creators are identified by email. You can manage membership explicitly with the endpoints below, but it is **optional** — calling media or contract upsert endpoints with an email automatically adds the creator to the campaign if they are not already a member. ## GET /sdk/v2/campaigns/:campaignId/creators List creators with the compact response recommended for new integrations. See [List campaign creators (v2)](/campaign-creators/list) for the complete field list, date-range behavior, pagination, and response examples. ### Query parameters * `search` or `query` (optional; searches creator name/email) * `includeHidden` (optional; `true` or `false`) * `fields` (optional; comma-separated response fields) * `startDate` and `endDate` (optional; `YYYY-MM-DD`, provided together) * `page` (default `1`) * `limit` (default `100`, maximum `500`) * `sortBy` (optional): `creatorName`, `totalViews`, `totalLikes`, `totalComments`, `totalShares` * `sortOrder` (`asc` or `desc`) ### Response ```json theme={null} { "success": true, "data": [ { "campaignId": "camp_...", "creatorEmail": "creator@example.com", "creatorProfileId": "cp_...", "campaignCreatorRecordId": "ccr_...", "pendingValue": 125, "currency": "USD", "totalViews": 50000 } ], "pagination": { "page": 1, "limit": 100, "total": 1, "totalPages": 1 }, "dateRange": null, "effectiveTimeZone": "America/New_York" } ``` ## GET /sdk/v1/campaigns/:campaignId/creators Returns the original, larger response for existing v1 clients. Its page limit remains `100`, it supports `cpmResultValue` sorting, and it does not use the v2 field projection. See [List campaign creators (v1 legacy)](/campaign-creators/list-v1) for its response fields and migration guidance. ## POST /sdk/v1/campaigns/:campaignId/creators Add one or more creators to a campaign by email. ### Body ```json theme={null} { "creatorEmail": "creator@example.com" } ``` Bulk add example: ```json theme={null} { "creatorEmails": [ "creator1@example.com", "creator2@example.com" ] } ``` Send either `creatorEmail` or `creatorEmails`, but not both. ### Response ```json theme={null} { "success": true, "data": { "campaignId": "camp_...", "creatorEmail": "creator@example.com", "creatorProfileId": "cp_...", "campaignCreatorRecordId": "ccr_..." } } ``` If you send `creatorEmails`, the response is batched: ```json theme={null} { "success": true, "successCount": 2, "failureCount": 0, "results": [ { "campaignId": "camp_...", "creatorEmail": "creator1@example.com", "creatorProfileId": "cp_...", "campaignCreatorRecordId": "ccr_...", "added": true } ] } ``` ### Common errors * `400`: missing or invalid `creatorEmail` * `400`: invalid `creatorEmails` payload > [!NOTE] > > The former bulk contract upsert is deprecated. Add creators first, then read > and write each creator's unified contract through the > `campaignCreatorRecordId` contract-history endpoints. Contract writes require > a complete contract and `basedOnVersionId`. ## Move a creator between campaigns Use [Move a creator between campaigns](/campaign-creators/move) to transfer an existing membership to another ongoing campaign in your agency. The move preserves the campaign creator record ID, media, contract history, and payouts. It requires the `campaigns:write` scope. ## DELETE /sdk/v1/campaigns/:campaignId/creators Remove a creator from a campaign. ### Query parameters * `email` (required) ### Response ```json theme={null} { "success": true, "data": { "campaignId": "camp_...", "creatorEmail": "creator@example.com", "campaignCreatorRecordId": "ccr_...", "removed": true } } ``` ### Common errors * `400`: missing `email` * `404`: creator not found in this campaign * `409`: cannot remove creator because payments exist ## Complete or reopen a campaign `POST /sdk/v1/campaigns/:campaignId/complete` and `POST /sdk/v1/campaigns/:campaignId/reopen` accept `{}` and require `campaigns:write`. They use the same lifecycle validation as the platform. Completed campaigns are read-only until reopened; reopening preserves existing media and payment history and may fail when the campaign is not eligible to resume. ## Enable or disable score calculation `PATCH /sdk/v1/campaigns/:campaignId/scoring` requires `campaigns:write` and a boolean body, such as `{ "enabled": false }`. Use `true` to re-enable. See [creator scoring and payment adjustments](/campaign-creators/payment-adjustments) for per-creator controls. # Content review Source: https://api-docs.usegrade.com/content-review Read the review queue and approve, reject, or reset posts. Content review must be enabled for the agency. A key cannot enable a feature by calling these endpoints: disabled agencies receive `403`. ## Read the queue `GET /sdk/v1/content-review` requires `campaigns:read`. Filters: `campaignId`, `campaignCreatorRecordId`, `creatorEmail`, `platform`, `reviewStatus` (`UNREVIEWED`, `APPROVED`, or `REJECTED`), `startDate`, `endDate`, `page`, `limit`, `sortBy`, and `sortOrder`. The default page is 1 and default limit is 25. ```bash theme={null} curl "$GRADE_API_BASE/sdk/v1/content-review?reviewStatus=UNREVIEWED&page=1&limit=25" \ -H "x-application-id: $GRADE_APPLICATION_ID" \ -H "x-api-key: $GRADE_API_KEY" ``` The response contains `success`, a `data` array, and `pagination`. `GET /sdk/v1/content-review/filters` returns the agency's available filter options and also requires `campaigns:read`. ## Review a post `PATCH /sdk/v1/campaign-media/:campaignCreatorMediaId/review-status` requires `campaigns:write`. ```json theme={null} { "status": "APPROVED" } ``` Use `REJECTED` to reject or `UNREVIEWED` to undo a decision. Resetting clears the review timestamp and reviewer. Only live post rows can be reviewed; accounts, deleted media, and retired media are ineligible. Completed campaigns return `409`. The response's `data` contains `campaignCreatorMediaId`, `campaignCreatorRecordId`, `campaignId`, `creatorProfileId`, `contentReviewStatus`, `contentReviewStatusLabel`, and `contentReviewedAt`. Payment eligibility and pending totals are recalculated using the platform's review rules. # Creators Source: https://api-docs.usegrade.com/creators Creator-specific receipts, totals, and payouts via /sdk/v1. All endpoints below require: * `X-Application-Id` * `X-Api-Key` All creator endpoints require an `email` query parameter. The creator must exist and be associated with the authenticated agency. ## GET /sdk/v1/creators/receipts List receipts for a creator. ### Query parameters * `email` (required) * `page` (default `1`) * `limit` (default `50`, max `100`) * `search` or `query` (optional; searches campaign name) * `sortBy` (optional): `campaignName`, `payoutDate`, `earningsValue`, `status` * `sortOrder` (optional): `asc` or `desc` ### Response ```json theme={null} { "success": true, "data": [ { "invoiceId": "inv_...", "status": "PAID", "payoutDate": "2026-02-19T00:00:00.000Z", "earningsValue": 150, "campaignName": "Spring campaign", "currency": "USD" } ], "pagination": { "page": 1, "limit": 50, "totalPages": 1, "totalItems": 1 } } ``` ### Common errors * `400`: missing/invalid `email` * `404`: creator not found for this agency ## GET /sdk/v1/creators/total-paid Get total paid to a creator, returning both USD and the agency preferred currency totals. ### Query parameters * `email` (required) ### Response ```json theme={null} { "success": true, "data": { "email": "creator@example.com", "spentAmountUSD": 100, "spentAmountPreferred": 141.32, "preferredCurrency": "CAD" } } ``` ## GET /sdk/v1/creators/payouts List payouts for a creator. ### Query parameters Same as `GET /sdk/v1/payouts`, plus: * `email` (required) ### Response ```json theme={null} { "success": true, "data": [{ "payoutId": "pay_...", "status": "claimed", "currency": "USD" }], "pagination": { "page": 1, "limit": 50, "totalPages": 1, "totalItems": 1 }, "meta": { "bufferBusinessDays": 1, "accelerated": false, "bankClosedDates": [] } } ``` ## Agency creator directory `GET /sdk/v1/creators` requires `payouts:read`, because directory results can contain financial summaries. Query parameters include `search` (or `query`), `page`, `limit`, `sortBy`, `sortOrder`, and `min` for the platform's compact representation. Results are restricted to creators connected to the API key's agency. `GET /sdk/v1/creators/:creatorProfileId` returns the agency-scoped creator profile and also requires `payouts:read`. The profile ID comes from directory or campaign-creator results. A profile outside the agency is not accessible. # Crosspost groups Source: https://api-docs.usegrade.com/crosspost-groups Inspect, create, and correct groups of tracked posts across platforms. Crosspost groups connect versions of the same content posted to different platforms by one campaign creator. These endpoints group existing tracked posts; they do not publish content to social networks. Use the `campaignCreatorRecordId` returned by the [campaign creator list](/campaign-creators/list). Every request requires `X-Application-Id` and `X-Api-Key`. The record, target group, and all supplied posts must belong to your agency and the same campaign creator. ## Automatic grouping and caption matching Automatic detection normally uses your agency's detection settings, such as the upload window and duration tolerance in `UPLOAD_WINDOW` mode. A contract's caption grouping rule changes how matching posts are grouped. Set `contract.crosspostRequirements.captionContains` when [creating a contract version](/campaign-creators/create-contract-version). In the [complete terms snapshot](/campaign-contracts), the equivalent field is `crosspost.captionFilter`. The contract version governing each post's upload business date supplies this rule. For example, `"captionContains": "#launch"` groups matching posts for the same campaign creator and the same configured filter by **local calendar day**. Grade determines that day from the post's upload timestamp using: 1. The campaign's `timeZone`, when set. 2. The agency's timezone, when the campaign has no override. 3. UTC, when neither is set. Set the campaign override through the [campaign endpoints](/campaigns). This is a midnight-to-midnight calendar day, including daylight-saving changes. It is not a rolling 24-hour window. For example, with `America/Los_Angeles`, uploads at `2026-09-17T23:30:00Z` and `2026-09-18T01:00:00Z` both belong to September 17 locally. Uploads on opposite sides of local midnight belong to different caption groups, even when they are only minutes apart. > [!WARNING] > > Caption grouping overrides the normal upload-window and duration-tolerance > checks for matching posts. With a six-hour window configured, two matching > posts 20 hours apart can still join the same group if they share the local > calendar day. This rule also allows multiple posts from the same platform. > Reusing a campaign-wide hashtag for several distinct videos in one day can > therefore combine those videos and affect payments configured per group. Matching is case-insensitive, and a leading `#` or `@` in a token is ignored. Comma-separated tokens match any listed token; they do not create separate groups for each token. Posts that do not match continue through normal automatic detection. Set `captionContains` to `null` to disable this override in a contract version. If you only want to choose which posts to track from an account, use [`media[].captionFilter`](/campaign-media) when adding that account. That tracking filter does not enable caption-based grouping. To correct an existing group, use the manual membership and split operations below. ## Reads The base path for the five endpoints below is: ```text theme={null} /sdk/v1/campaign-creators/:campaignCreatorRecordId/crosspost-groups ``` ### GET / List groups ordered by group ID. Query parameters are `page` (default `1`, maximum `1000000`) and `limit` (default `50`, maximum `100`). Both must be positive whole numbers. Unknown parameters are rejected. ```bash theme={null} curl -sS "$BASE_URL/sdk/v1/campaign-creators/CCR_123/crosspost-groups?limit=50" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" ``` ```json theme={null} { "success": true, "data": [ { "crosspostGroupId": "xpg_468b922199df4a3a97df1c72c9a75bce", "crosspostGroupName": "1-Sep-2026", "postsCount": 2, "platforms": ["INSTAGRAM", "TIKTOK"], "source": "MANUAL" } ], "pagination": { "page": 1, "limit": 50, "total": 1, "totalPages": 1 }, "membershipVersion": "b770693c6069476802f6c5b047937701047849a0b456354a9e328d93e12a0c62" } ``` `source` is `AUTO`, `MANUAL`, `MIXED`, or `null` for legacy groups without a recorded source. `MIXED` means members have different sources. Names are generated display labels; use the opaque group ID to reference a group. Automatic groups and names can change after detection runs. The existing [creator media endpoint](/campaign-media) still supports `includeGroups=true` and returns richer media/performance summaries. This direct list provides independent group pagination and a version for safe edits. ### GET /:crosspostGroupId/posts Read a group's members ordered by media ID, with the same `page` and `limit` parameters. Both directly tracked posts and posts discovered from tracked accounts are included. Account rows, deleted posts, and retired posts are excluded. ```bash theme={null} curl -sS "$BASE_URL/sdk/v1/campaign-creators/CCR_123/crosspost-groups/$GROUP_ID/posts" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" ``` Each item in `data` includes: | Field | Meaning | | - | - | | `campaignCreatorMediaId` | Tracked post ID used for membership writes | | `crosspostGroupId`, `crosspostGroupName` | Current group identity and display name | | `crosspostGroupSource` | This member's `AUTO` or `MANUAL` source; may be `null` | | `platform`, `mediaUrl`, `postId` | Social post identity | | `title`, `captionText`, `authorUsername`, `uploadDate` | Available post metadata | | `sourceCampaignCreatorMediaId` | Tracked account that discovered the post, or `null` | | `views`, `likes`, `comments` | Latest tracked metrics; zero when no metrics exist | | `metricsAsOfTimestamp` | Latest metric collection time, or `null` | The response also includes `pagination` and `membershipVersion`, as in the group list. Missing or out-of-scope groups return `404`. A valid group with an out-of-range page returns an empty `data` array. ## Writes and retries All three writes require `X-Idempotency-Key` (1–255 characters). Generate a key once for each logical operation and reuse it with the same body after a timeout or retryable error. Completed responses are retained for 24 hours, scoped to your application, agency, campaign creator, and operation. A replay returns the original status/body and `X-Idempotent-Replay: true`; a changed payload with the same key returns `409 IDEMPOTENCY_CONFLICT`. Optionally send `expectedMembershipVersion` from a read or the previous write. A stale version returns `409 MEMBERSHIP_CONFLICT` without changing any posts. Read again and submit your revised operation with a new key. The version covers the creator's active membership; it is separate from scrape freshness. Each batch is atomic. If any post or target group is invalid, no membership changes are committed. Writes reject account rows, deleted/retired posts, and completed campaigns. Each write supports creators with up to 5,000 active posts; create and membership batches accept at most 500 distinct media IDs. ### POST / Create a populated group from a non-empty `campaignCreatorMediaIds` array. A post may move from an existing group. A one-post manual group is allowed; its existence does not establish payout eligibility. ```bash theme={null} curl -sS "$BASE_URL/sdk/v1/campaign-creators/CCR_123/crosspost-groups" \ -X POST \ -H "Content-Type: application/json" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" \ -H "X-Idempotency-Key: $IDEMPOTENCY_KEY" \ -d '{"campaignCreatorMediaIds":["CCMEDIA_123","CCMEDIA_456"]}' ``` Returns `201` with a server-assigned group ID. Creation and all assignments happen together; no separate request is needed to attach the posts. ### PATCH /memberships Send a non-empty `assignments` array. Every media ID must appear once. Choose one of these states for each post: | State | Assignment fields | | - | - | | Manually assign or move a post | `mode: "MANUAL"` and an existing `crosspostGroupId` | | Keep a post ungrouped | `mode: "MANUAL"` and `crosspostGroupId: null` | | Return a post to automatic detection | `mode: "AUTO"`; omit `crosspostGroupId` | ```json theme={null} { "assignments": [ { "campaignCreatorMediaId": "CCMEDIA_123", "mode": "MANUAL", "crosspostGroupId": "xpg_468b922199df4a3a97df1c72c9a75bce" }, { "campaignCreatorMediaId": "CCMEDIA_456", "mode": "MANUAL", "crosspostGroupId": null }, { "campaignCreatorMediaId": "CCMEDIA_789", "mode": "AUTO" } ] } ``` Automatic detection runs after the assignments. A manual exclusion survives future recomputes. Resetting to `AUTO` removes that override and evaluates the post immediately; it may remain ungrouped if there is no match or insufficient metadata. An ungrouped automatic candidate can have a `null` source. To dissolve a group, manually ungroup all its members. This keeps the tracked content. To split a group, create a new group from the selected members. ### POST /recompute Rerun automatic grouping for this campaign creator. Send `{}` or an object containing `expectedMembershipVersion`. Uses the agency's current detection settings and applicable contract caption rules. Caption grouping uses the current campaign → agency → UTC timezone fallback described above, so changing the timezone can change automatic membership on the next recompute. Manual assignments and exclusions are preserved. This operation does not scrape fresh post metadata or reset manual overrides. ### Write response All writes complete membership changes before responding. Creation also includes `crosspostGroupId`; membership updates and recompute return `200`. ```json theme={null} { "success": true, "data": { "campaignCreatorRecordId": "CCR_123", "crosspostGroupId": "xpg_468b922199df4a3a97df1c72c9a75bce", "memberships": [ { "campaignCreatorMediaId": "CCMEDIA_123", "crosspostGroupId": "xpg_468b922199df4a3a97df1c72c9a75bce", "crosspostGroupName": "1-Sep-2026", "crosspostGroupSource": "MANUAL", "platform": "INSTAGRAM", "mediaUrl": "https://www.instagram.com/p/example" } ], "membershipVersion": "b770693c6069476802f6c5b047937701047849a0b456354a9e328d93e12a0c62", "recompute": { "updated": 0, "skippedManual": 1, "skippedMissing": 0 }, "status": "COMPLETED", "summaryRefresh": "QUEUED" } } ``` `memberships` contains the posts supplied to create/update, in media-ID order. For recompute it is empty: use the reads to fetch current groups and members. `recompute.updated` counts automatic changes, not the supplied manual assignments. The operation may also change other automatic groups in this creator record. Calculated dashboard summaries refresh through a durable background queue. For monetary results, use the existing [line items](/campaign-creators/line-items) or [payout preview](/campaign-creators/payout-preview) endpoints. Group membership changes preserve established payment ownership. A merge of posts with different established payment-group owners returns `409 PAYMENT_GROUP_CONFLICT` and rolls back. Safe splits and manual exclusions preserve their original payment history. Configure payment rules through [contract versions](/campaign-creators/create-contract-version). ## Error responses Errors use `{ "success": false, "code": "...", "message": "..." }`. Authentication failures use the standard SDK authentication response. | Status | Code | Action | | - | - | - | | `400` | `INVALID_REQUEST`, `INVALID_BATCH`, `DUPLICATE_MEDIA` | Correct fields, pagination, ID/key length, or duplicate media IDs | | `401` / `403` | Standard SDK auth error | Check credentials, API enablement, and origin | | `404` | `NOT_FOUND`, `MEDIA_NOT_FOUND`, `GROUP_NOT_FOUND` | Use a record, active post, and existing target group in your authorized scope | | `409` | `CAMPAIGN_COMPLETED` | Use an editable campaign | | `409` | `MEMBERSHIP_CONFLICT` | Read current membership and submit a revised operation with a new key | | `409` | `IDEMPOTENCY_CONFLICT` | Use the original request for a retry; use a new key for a different operation | | `409` | `PAYMENT_GROUP_CONFLICT` | Keep the established payment groups separate | | `409` | `RETRY_OPERATION` | Retry the same body and key after a short backoff | | `413` | `RECOMPUTE_LIMIT` | The creator exceeds the 5,000-active-post write limit | | `500` | `INTERNAL_ERROR` | Retry writes using the original key | # Payout disputes Source: https://api-docs.usegrade.com/disputes Read the disputes creators open on payouts, reply to them, and resolve or reject them. A creator who thinks a payout is wrong can open a dispute on it. Your brand answers in Grade or through these endpoints. Grant `disputes:read` to read disputes and download proof, and `disputes:write` to reply and resolve. Existing keys do not gain these permissions automatically, and `payouts:write` alone is not enough. Write does not imply read. > [!WARNING] > > Every dispute opens with at least one link to TikTok, Instagram, YouTube, Facebook or Snapchat. Grade checks that the link is on one of those sites, not that the post belongs to the creator or to the payout. The rest of the proof is whatever the creator chose to attach, such as screenshots of bank statements or messages, so it may hold personal data. Grant `disputes:read` only to integrations that are allowed to store it. ## How disputes work * **One dispute per payout.** A payout has at most one dispute, ever. Later messages go in the same thread. * **Disputes never move or block money.** Opening, resolving or rejecting a dispute does not cancel, refund, hold or send anything. If the outcome means paying more, send that payout separately. * **A dispute may have no campaign.** Disputes on `AGENCY_CREATOR_ROLE_PAYOUT` payouts have `campaignId: null`, and a `campaign` filter leaves them out. * **Reopen once.** A creator's reply to a rejected dispute reopens it. A second rejection is final, and so is `resolved`. `canReopen` says whether a reply can still reopen the dispute. ### Statuses | Status | Meaning | | - | - | | `open` | Waiting for an answer. `awaitingBrandSince` is set while the last word is the creator's. | | `resolved` | Your brand accepted the dispute. Final. | | `rejected` | Your brand rejected the dispute, with a reason sent to the creator. | ### Reasons `video_missing`, `crosspost_not_counted`, `wrong_amount`, `other`. ## List disputes ```bash theme={null} curl "$BASE_URL/sdk/v1/disputes?status=open&since=2026-10-01T00:00:00Z&page=1&limit=50" \ -H "X-Application-Id: $APPLICATION_ID" \ -H "X-Api-Key: $API_KEY" ``` `GET /sdk/v1/disputes` requires `disputes:read`. | Parameter | Description | | - | - | | `campaign` | Campaign ID. | | `status` | `open`, `resolved`, or `rejected`. | | `since` | ISO 8601 time with `Z` or an offset. Filters on the last update, inclusive: `updatedAt` at or after this time. URL-encode a `+` in an offset. | | `page` | Default `1`. | | `limit` | Default `50`, maximum `100`. | Open disputes come first, then oldest first. The response is `{ success: true, data: [...], pagination: { page, limit, total, totalPages } }`. ## Read a dispute `GET /sdk/v1/disputes/:id` requires `disputes:read` and adds `description` and `messages` to the list fields: ```json theme={null} { "success": true, "data": { "id": "00000000-0000-4000-8000-000000000001", "payoutId": "CCPAY_example", "payoutType": "CAMPAIGN_CREATOR_PAYOUT", "campaignId": "campaign_example", "campaignName": "Summer Launch", "creatorProfileId": "creator_example", "creatorName": "Casey", "agencyId": "agency_example", "agencyName": "Example Brand", "reason": "video_missing", "status": "open", "canReopen": false, "awaitingBrandSince": "2026-10-01T10:00:00.000Z", "brandRemindedAt": null, "escalatedAt": null, "createdAt": "2026-10-01T10:00:00.000Z", "updatedAt": "2026-10-01T10:00:00.000Z", "resolvedAt": null, "description": "My second video is not on this payout.", "messages": [ { "id": "00000000-0000-4000-8000-000000000002", "author": "creator", "event": "opened", "body": "My second video is not on this payout.", "attachments": [ { "id": "00000000-0000-4000-8000-000000000003", "kind": "link", "url": "https://example.com/video" }, { "id": "00000000-0000-4000-8000-000000000004", "kind": "file", "name": "proof.png", "contentType": "image/png", "sizeBytes": 20480 } ], "createdAt": "2026-10-01T10:00:00.000Z" } ] } } ``` `author` is `creator`, `brand`, or `grade`. `event` is `opened`, `message`, `reopened`, `resolved`, or `rejected`. `escalatedAt` is set when a dispute goes 14 days without an answer from your brand; Grade support sees those disputes. ## Download proof `GET /sdk/v1/disputes/:id/attachments/:attachmentId` requires `disputes:read` and returns a file attachment as a download: a JPEG, PNG, or WebP image of up to 10 MB. Link attachments already carry their `url` in the thread and have no file. ## Reply `POST /sdk/v1/disputes/:id/reply` requires `disputes:write` and `X-Idempotency-Key`. It emails the creator and leaves the dispute open. Replies carry text only. ```json theme={null} { "body": "We are checking this video with the campaign team." } ``` `body` is required, up to 5,000 characters. The response is `201` with the dispute as it is now. ## Resolve or reject `POST /sdk/v1/disputes/:id/resolve` requires `disputes:write` and `X-Idempotency-Key`. It closes an open dispute and emails the creator. ```json theme={null} { "outcome": "rejected", "message": "This video was uploaded after the payout period." } ``` `outcome` is `resolved` or `rejected`. `message` goes to the creator, up to 5,000 characters. It is optional for `resolved` and required for `rejected`. The response is `200` with the dispute as it is now. ## Retries `X-Idempotency-Key` is required on both writes, up to 128 characters, and is scoped to the dispute. Retrying with the same key and body returns the dispute as it is now, without adding a second message or emailing again. The same key with a different body answers `409` with `IDEMPOTENCY_PAYLOAD_MISMATCH`. ## Errors | Status | Code | Meaning | | - | - | - | | `400` | `INVALID_REQUEST`, `DISPUTE_INVALID` | Invalid parameters or body, such as a rejection without a `message`. | | `400` | `INVALID_IDEMPOTENCY_KEY` | `X-Idempotency-Key` is missing or too long. | | `403` | | The key is missing the required scope. | | `404` | `DISPUTE_NOT_FOUND`, `DISPUTE_ATTACHMENT_NOT_FOUND` | Not found in your agency. | | `404` | `DISPUTES_NOT_ENABLED` | Payout disputes are not available yet. | | `409` | `DISPUTE_CLOSED` | The dispute is already closed. | | `409` | `IDEMPOTENCY_PAYLOAD_MISMATCH` | The key was used with a different body. | | `503` | `DISPUTE_UNAVAILABLE` | Temporarily unavailable. Retry with the same key. | ## Stay up to date Poll `GET /sdk/v1/disputes` with `since`. A new dispute, a creator's message, a reopening, and your own answers all change `updatedAt`. 1. Note the current time before you start. 2. Read every page with `since` set to the time you noted on the previous run. The list is not in update order, so do not stop early. 3. Handle each dispute by `id`. The filter is inclusive, so you can see the same dispute twice. There is no webhook for SDK keys. If you need a push, `dispute.created` is available through your agency's chat integrations, using the generic webhook. Those webhooks are configured in the Grade dashboard and are unsigned, so treat the call as a hint and read the dispute through this API. # Grade SDK API Source: https://api-docs.usegrade.com/index External API reference for Grade SDK endpoints. ## Base path Most SDK endpoints are under: `/sdk/v1` The compact campaign creator list is versioned separately at: `GET /sdk/v2/campaigns/:campaignId/creators` ## Authentication (required on every request) Send these headers on **every** request: * `X-Application-Id`: Your SDK application ID. * `X-Api-Key`: Your SDK API key secret. If the application has an origin allowlist configured: * If the request includes an `Origin` header, it must match the allowlist. * If the request omits `Origin` (common server-to-server), allowlist checks are skipped. ## Scopes (what a key is allowed to do) Every API key carries a set of scopes, chosen when the key is created and editable afterwards from the developer portal. A scope is written `:`, where the action is `read` or `write`. | Domain | Covers | | - | - | | `analytics` | Tracked media, collections, and performance metrics. | | `campaigns` | Campaigns, campaign creators, contracts, campaign media, crosspost groups, and bonus templates. | | `payouts` | Wallet balance, transactions, invoices, payout history, and sending payouts. | | `approvals` | Read payout approval requests and approve, reject, or cancel them. | | `disputes` | Read payout disputes and their proof, reply to them, and resolve or reject them. | | `kyc` | Recipient onboarding and identity verification. | `write` does not imply `read`, so a domain has four possible states and the portal offers all of them: No access, Read only, Write only, and Read and write. A key that should both list and mutate a domain needs both scopes. A call whose key is missing the required scope answers `403` and names what is missing: ```json theme={null} { "success": false, "message": "This API key is missing the required scope: payouts:write" } ``` Two notes worth knowing before you design around this: * **The HTTP method is not the rule.** Several endpoints are `POST` but are pure reads, and they require `:read`, not `:write`. That includes `POST /payouts/status`, `POST /payouts/pending`, `POST /payouts/pending-bulk`, `POST /wallet/check-payout-balance[-bulk]`, and the two `POST /campaign-creators/.../query` endpoints. So a read-only key can still check a balance before a payout is approved elsewhere. * **Reference endpoints need no scope.** `GET /timezones` and `GET /settings` answer for any valid key. Keys that existed before scopes shipped were granted every scope, so nothing changed for them. Newly introduced domains such as `approvals` and `disputes` must be granted explicitly. Rotating a key preserves its scopes. ## Idempotency (required on payout, crosspost, and dispute writes) These endpoints require `X-Idempotency-Key`: * `POST /sdk/v1/payouts/trigger` * `POST /sdk/v1/payouts/trigger-bulk` * `POST /sdk/v1/payouts/confirm` * `POST /sdk/v1/payouts/confirm-bulk` * `POST /sdk/v1/payouts/cancel` * `POST /sdk/v1/campaign-creators/payouts/bulk` * `POST /sdk/v1/campaign-creators/:campaignCreatorRecordId/quick-pay` * `POST /sdk/v1/campaign-creators/:campaignCreatorRecordId/crosspost-groups` * `PATCH /sdk/v1/campaign-creators/:campaignCreatorRecordId/crosspost-groups/memberships` * `POST /sdk/v1/campaign-creators/:campaignCreatorRecordId/crosspost-groups/recompute` * `POST /sdk/v1/disputes/:id/reply` * `POST /sdk/v1/disputes/:id/resolve` Idempotency keys are scoped per application and operation. Re-using the same key returns the previously stored response. Dispute keys are scoped per dispute and return the dispute as it is now. See [Payout disputes](/disputes). Reading [Quick Pay approval status](/campaign-creators/quick-pay) or `GET /sdk/v1/payouts/approvals/:approvalId` (approval requests created by [Payouts](/payouts) when approval mode is on) requires `payouts:read` but does not require `X-Idempotency-Key`. ## Limits and validation * **Supported payout currencies**: `USD`, `CAD`, `GBP`, `EUR` * **Currency precision**: money amounts must be positive and have **max 2 decimals** * **Payout batches**: up to **100 items** per request * **Campaign creator v1 reads**: up to **100 creators** per page * **Campaign creator v2 reads**: up to **500 creators** per page or request * **Eligibility score batches**: up to **500 media items** per request * **Pending payout TTL**: **7 days** * **Exports**: require `from` and `to` and are capped at **10,000 rows** ## Response conventions * Most JSON endpoints return `{ success: boolean, ... }`. * Balance check endpoints return `{ sufficient: boolean }` (no `success` wrapper). * Export endpoints and invoice PDFs return file content (`text/csv` or `application/pdf`). ## Pages * [MCP server](/mcp-server) — connect an MCP-compatible AI client to your Grade account * [Payouts](/payouts) * [Campaign quick pay](/campaign-creators/quick-pay) — custom one-off payments attributed to a campaign * [Bonus templates](/bonus-templates) * [Wallet](/wallet) * [Transactions](/transactions) * [Creators](/creators) * [KYC](/kyc) * [Invoices](/invoices) * [Settings](/settings) * [Timezones](/timezones) — list accepted IANA names and display-friendly labels * [Standalone analytics](/analytics) — track accounts and posts outside campaigns, manage collections, and query performance ### Campaign management * [Campaigns](/campaigns) — create, list, update, delete campaigns and manage campaign creators * [Campaign creators (v2)](/campaign-creators/list) — use the compact response for new integrations * [Campaign creators (v1 legacy)](/campaign-creators/list-v1) — preserve the original response for existing clients * [Campaign creator visibility](/campaign-creators/visibility) — hide or unhide a creator within a campaign * [Move a creator](/campaign-creators/move) — move a creator and their history between campaigns in your agency * [Payout report data](/campaign-creators/payout-report-data) — read the rows and totals behind a creator's payout report as JSON * [Campaign contracts](/campaign-contracts) — manage creator contracts and payment terms (optional) * [Campaign media](/campaign-media) — track media, manage creator content, and read performance metrics * [Media eligibility](/campaign-media/eligibility-scores) — read and update eligibility scores for tracked posts * [Payment exclusions](/campaign-media/payment-exclusions) — exclude tracked posts or accounts from fixed-rate and performance payments, or undo those exclusions ## Minimal example (curl) ```bash theme={null} BASE_URL="https://" APP_ID="app_..." API_KEY="sk_..." curl -sS "$BASE_URL/sdk/v1/wallet/balance" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" ``` ## Platform workflows * [Campaign media management](/campaign-media/management): freeze/unfreeze performance, restore, restart account tracking, tracking settings, and manual analytics. * [Content review](/content-review): review queue, filters, decisions, and undo. * [Payment templates](/payment-templates): full template management and application. * [Payout approvals](/payout-approvals): queue and decisions with separate permissions. * [Payment adjustments and scoring](/campaign-creators/payment-adjustments): pending bonus, recurring-cycle waivers, and scoring controls. # Invoices Source: https://api-docs.usegrade.com/invoices Download invoice or receipt PDFs via /sdk/v1. All endpoints below require: * `X-Application-Id` * `X-Api-Key` ## GET /sdk/v1/invoice/pdf Download an invoice or receipt PDF. ### Query parameters * `invoiceId` (required) ### Response Returns `application/pdf` with `Content-Disposition: attachment; filename="invoice_.pdf"` or `receipt_.pdf`. ### Common errors * `400`: missing `invoiceId` * `403`: invoice exists but is not accessible to the authenticated agency * `404`: invoice not found # KYC Source: https://api-docs.usegrade.com/kyc Invite recipients to complete KYC verification, manage invites, and list recipients via /sdk/v1. All endpoints below require: * `X-Application-Id` * `X-Api-Key` ## KYC connection object Endpoints that return a connection use this shape: ```json theme={null} { "connectionId": "SDKKYC_...", "email": "recipient@example.com", "inviteStatus": "sent", "inviteExpiresAt": "2026-03-01T00:00:00.000Z", "inviteSentAt": "2026-02-22T00:00:00.000Z", "inviteAcceptedAt": null, "kycStatus": "invited", "kycCurrentStep": null, "kycCompletedSteps": [], "updatedAt": "2026-02-22T00:00:00.000Z" } ``` ### `inviteStatus` values | Value | Meaning | | - | - | | `none` | No invite sent yet | | `sent` | Invite email dispatched | | `canceled` | Invite was canceled before acceptance | | `accepted` | Recipient accepted the invite | | `expired` | Invite expired before acceptance | ### `kycStatus` values | Value | Meaning | | - | - | | `invited` | Waiting for the recipient to begin | | `email_verified` | Recipient verified their email | | `flow_started` | KYC flow initiated | | `in_progress` | Recipient is completing KYC steps, including while verification is under review or being resubmitted | | `complete` | KYC finished successfully (both steps are done) | | `canceled` | KYC was canceled | | `deleted` | Connection was deleted | | `error` | Verification was declined, or something went wrong during the flow | ### KYC steps `kycCurrentStep` and `kycCompletedSteps` use these step names: | Value | Meaning | | - | - | | `id-verification` | Identity verification | | `compliance` | Tax details | | `redirect` | Return to your app after verification (some accounts only) | The order of the steps can differ by account, so do not rely on it. `kycStatus` is `complete` once `id-verification` and `compliance` are done. ## POST /sdk/v1/kyc/invite Send a KYC invite to a recipient. If the recipient already has a pending invite, the invite is refreshed. The link in the invite email opens Grade's hosted verification. Depending on your account, that is Grade's KYC page or the Grade creator app. The API, fields, and statuses are the same either way. If the recipient already completed verification with Grade, the response can come back with `kycStatus` `complete` right away, and no email is sent. ### Body * `email` (required; valid email address) * `idempotencyKey` (optional; max 128 characters) ```json theme={null} { "email": "recipient@example.com", "idempotencyKey": "unique-key-123" } ``` ### Response ```json theme={null} { "success": true, "data": { "connectionId": "SDKKYC_...", "email": "recipient@example.com", "inviteStatus": "sent", "inviteExpiresAt": "2026-03-01T00:00:00.000Z", "inviteSentAt": "2026-02-22T00:00:00.000Z", "inviteAcceptedAt": null, "kycStatus": "invited", "kycCurrentStep": null, "kycCompletedSteps": [], "updatedAt": "2026-02-22T00:00:00.000Z" } } ``` ### Invite allowance Each agency has a lifetime allowance of new KYC invites, 10 by default, shared by all of its applications. * Each new recipient email uses one invite. * Resending an invite to an existing connection is free, including after you cancel it. * Deleting a connection does not give its invite back, so inviting the same email again later uses a new one. When the allowance is used up, inviting a new recipient email returns `429` with code `KYC_INVITE_ALLOWANCE_EXCEEDED` and no `Retry-After` header. Resending to existing connections keeps working. Contact [support@usegrade.com](mailto:support@usegrade.com) to raise the allowance. ### Common errors * `400`: missing or invalid `email` * `400`: `idempotencyKey` exceeds 128 characters * `401`: missing or invalid SDK headers * `409`: the connection for this email is already complete (`KYC_ALREADY_COMPLETE`) * `429`: invite cooldown active; check the `Retry-After` response header (`KYC_INVITE_COOLDOWN`) * `429`: invite allowance used up; there is no `Retry-After` header, see [Invite allowance](#invite-allowance) (`KYC_INVITE_ALLOWANCE_EXCEEDED`) Use the `code` field to tell the two `429` responses apart. Only `KYC_INVITE_COOLDOWN` can succeed by waiting and retrying. ## POST /sdk/v1/kyc/cancel Cancel a pending KYC invite. Provide either `connectionId` or `email` to identify the invite. Canceling stops tracking on the API side only. A recipient who already has the link may still finish verification with Grade, but the connection keeps reporting `canceled`. ### Body * `connectionId` (required if `email` is omitted) * `email` (required if `connectionId` is omitted) ```json theme={null} { "connectionId": "SDKKYC_..." } ``` ### Response ```json theme={null} { "success": true, "data": { "connectionId": "SDKKYC_...", "email": "recipient@example.com", "inviteStatus": "canceled", "inviteExpiresAt": "2026-03-01T00:00:00.000Z", "inviteSentAt": "2026-02-22T00:00:00.000Z", "inviteAcceptedAt": null, "kycStatus": "canceled", "kycCurrentStep": null, "kycCompletedSteps": [], "updatedAt": "2026-02-22T12:00:00.000Z" } } ``` ### Common errors * `400`: neither `connectionId` nor `email` provided * `401`: missing or invalid SDK headers * `409`: invite is not in a cancelable state (`KYC_INVITE_NOT_CANCELABLE`) ## GET /sdk/v1/kyc/recipients List KYC connections for your application. ### Query parameters * `page` (default `1`) * `limit` (default `50`) ### Response ```json theme={null} { "success": true, "data": [ { "connectionId": "SDKKYC_...", "email": "recipient@example.com", "inviteStatus": "accepted", "inviteExpiresAt": "2026-03-01T00:00:00.000Z", "inviteSentAt": "2026-02-22T00:00:00.000Z", "inviteAcceptedAt": "2026-02-23T10:00:00.000Z", "kycStatus": "complete", "kycCurrentStep": null, "kycCompletedSteps": ["id-verification", "compliance"], "updatedAt": "2026-02-23T11:00:00.000Z" } ], "pagination": { "page": 1, "limit": 50, "totalPages": 1, "totalItems": 1, "hasMore": false } } ``` ## DELETE /sdk/v1/kyc/recipients/:connectionId Permanently delete a KYC connection. Deleting stops tracking on the API side only. A recipient who already has the link may still finish verification with Grade, but the connection no longer appears in `GET /sdk/v1/kyc/recipients`. Deleting does not give the invite back to your [invite allowance](#invite-allowance). ### Path parameters * `connectionId` (required) ### Response ```json theme={null} { "success": true } ``` ### Common errors * `400`: missing `connectionId` * `401`: missing or invalid SDK headers # MCP server Source: https://api-docs.usegrade.com/mcp-server Connect an MCP-compatible AI client to your Grade SDK v1 account. The Grade MCP server lets an MCP-compatible AI client use your SDK v1 credentials to inspect payouts, wallet activity, creators, campaigns, KYC recipients, and analytics. It runs on your machine over stdio; your API key is supplied through the process environment and is not a tool argument. ## Prerequisites * Node.js 20 or newer * A Grade SDK application ID and API key > [!WARNING] > > Treat your API key like a password. Store it in the MCP client's environment configuration, not in chat messages or tool arguments. ## Connect your client **1. Open the MCP configuration** Open the JSON configuration used by your MCP-compatible client. **2. Add the Grade server** Add the following entry and replace the two placeholder values with the credentials supplied by Grade. ```json theme={null} { "mcpServers": { "grade": { "command": "npx", "args": ["-y", "@usegrade/mcp-server@latest"], "env": { "GRADE_APPLICATION_ID": "app_...", "GRADE_API_KEY": "sk_..." } } } } ``` **3. Restart the client** Restart the AI client so it starts the Grade MCP process. Ask it to get your Grade wallet balance to verify the connection. Read tools are enabled by default. They cover wallet balances, payouts, transaction and creator payment history, KYC status, campaigns, contracts, media, bonus templates, supported timezones, creator directories, payment templates, content review, payout approvals, and campaign or standalone analytics. ## Enable write tools Write tools are not registered unless you explicitly enable them. Add this environment variable to the same `env` object: ```json theme={null} { "GRADE_MCP_ENABLE_WRITES": "true" } ``` After restarting the client, it can create or change payouts, KYC invites, campaigns, contracts, media, bonus templates, and analytics collections. > [!WARNING] > > Enabling write tools lets the client make changes to your Grade account. Keep your client's tool-approval prompts enabled. Review the exact recipient, currency, amount, and fee settings before approving a payout. ### Safer payout flow 1. Trigger the payout with `requireConfirmation: true` and a unique `idempotencyKey`. 2. Review the returned payout preview, including the recipient, amount, currency, and platform fee. 3. Confirm the pending payout with a new idempotency key only after the preview is correct. The payout trigger, confirmation, bulk confirmation, and cancellation tools require an explicit idempotency key. Reuse the same key only when retrying the exact same business operation. ## Optional settings | Variable | Default | Description | | - | - | - | | `GRADE_API_BASE_URL` | `https://infra.usegrade.com/api/email` | Override the Grade API URL for a development or test environment. | | `GRADE_MCP_TIMEOUT_MS` | `15000` | Per-request timeout in milliseconds. | | `GRADE_MCP_MAX_RESPONSE_BYTES` | `1000000` | Maximum API response size passed into model context. Narrow the query before increasing it. | | `GRADE_MCP_ALLOW_INSECURE_HTTP` | `false` | Allow HTTP for a trusted non-local development host. Localhost HTTP works without this setting. | ## API coverage The MCP server exposes allowlisted JSON endpoints from the public SDK v1 API. It does not accept arbitrary paths or hosts from tool calls. CSV/PDF exports and invoice downloads are not MCP tools because binary files consume model context without giving the client a reliable place to save them. Use the [payout](/payouts), [transaction](/transactions), and [invoice](/invoices) SDK endpoints for those downloads. ## Troubleshooting * **Server does not start:** Check that both credential environment variables are present and Node.js is version 20 or newer. * **`401` response:** Verify the application ID and API key belong to the same active SDK application. * **`403` response:** If you configured an origin allowlist, confirm your integration policy permits server-to-server requests. * **Response too large:** Add narrower date, status, search, or pagination filters. Increase `GRADE_MCP_MAX_RESPONSE_BYTES` only when needed. * **Write tool is missing:** Set `GRADE_MCP_ENABLE_WRITES` to `true`, then restart the client. ## Platform workflow tools The MCP catalog includes media freeze/unfreeze, restore, restart-from-date, tracking settings, manual analytics, review decisions, scoring, campaign completion/reopening, template application, payment adjustments, approval decisions, and collection bulk membership/freezing. These write tools still require `GRADE_MCP_ENABLE_WRITES=true` and their SDK scopes. Approval tools require the separately granted `approvals` scopes; approving can execute a payout. The catalog does not expose campaign refresh/wake/pause controls or logo checks. # Payment templates Source: https://api-docs.usegrade.com/payment-templates Manage full contract and bonus templates and apply them to campaign creators. Reads require `campaigns:read`; create, edit, delete, and apply require `campaigns:write`. Every template and target must belong to the API key's agency. Responses contain JSON in `data`, not a JSON-encoded string. Template records retain their platform field names, including `template_id`, `template_kind`, `contract_terms`, and `rule_terms`. ## List, create, edit, and delete | Method and path | Purpose | | - | - | | `GET /sdk/v1/payment-templates` | List templates; accepts `templateKind`, `includeHidden`, and `includeDeleted` | | `POST /sdk/v1/payment-templates` | Create a template | | `PATCH /sdk/v1/payment-templates/:templateId` | Edit supplied fields (`PUT` is also supported) | | `DELETE /sdk/v1/payment-templates/:templateId` | Hide/remove a template according to platform rules, preserving existing usage | Kinds are `BONUS`, `CONTRACT`, and `SIMPLIFIED`. Simplified templates retain the agency feature gate. The existing [bonus-template API](/bonus-templates) remains available. Example full contract template: ```json theme={null} { "name": "Standard creator fee", "colorCode": "#2563EB", "templateKind": "CONTRACT", "contractTerms": { "schemaVersion": 1, "payoutType": "FIXED", "currency": "USD", "fixed": { "amount": 500, "paymentOption": "STANDARD", "rateScope": "CREATOR", "platforms": [] }, "performance": null, "payCycle": { "enabled": false, "timesPerPeriod": null, "period": null, "weekday": null, "startImmediately": true }, "bonus": null } } ``` Bonus templates use `components` and optional `tierScope`. Simplified templates use `ruleTerms`. Names and a valid `colorCode` are required for creation. Editing accepts `name`, `description`, `colorCode`, `components`, `isDefault`, `templateKind`, `contractTerms`, and `ruleTerms`, subject to the platform's template-kind and validation rules. Hidden/deleted templates cannot be applied to new creators. ## Apply to one creator `POST /sdk/v1/payment-templates/apply` ```json theme={null} { "templateId": "template-id", "campaignCreatorRecordId": "creator-record-id", "applicablePostsUploadedOnOrAfter": "2026-10-01" } ``` You may identify the target with `campaignId` plus `creatorProfileId` instead of a record ID. The date is optional where the existing contract history permits it; when a new effective boundary is required, the API returns the platform's validation error. Paid history, pending approvals, currency compatibility, and completed-campaign protections remain enforced. Simplified templates cannot be applied through the legacy apply workflow. ## Preview and apply a contract template in bulk `GET /sdk/v1/payment-templates/:templateId/apply-candidates` lists eligible and ineligible candidates. Query parameters: `campaignId`, `search`, `page`, and `pageSize`. `GET /sdk/v1/payment-templates/apply-candidates` provides the general candidate list. `POST /sdk/v1/payment-templates/:templateId/apply-bulk` ```json theme={null} { "campaignCreatorRecordIds": ["creator-record-1", "creator-record-2"], "applicablePostsUploadedOnOrAfter": "2026-10-01" } ``` Alternatively pass `campaignId` to target its creators. Bulk apply is for full contract templates. It validates each target and returns per-row results; inspect failures and skipped rows before treating the operation as complete. These operations reuse the platform's contract-history boundaries rather than overwriting past payments. # Payout approvals Source: https://api-docs.usegrade.com/payout-approvals Read pending approval requests and approve, reject, or cancel them. Approval authority is separate from payout submission. Grant `approvals:read` to read the queue and `approvals:write` to decide requests. Existing keys do not gain these permissions automatically; `payouts:write` alone is insufficient. Write does not imply read. > [!WARNING] > > Approving a request can execute a payout. Grant `approvals:write` only to integrations authorized to make that decision. ## Read requests | Method and path | Result | | - | - | | `GET /sdk/v1/payout-approvals` | Paginated queue/history | | `GET /sdk/v1/payout-approvals/:id` | One agency-owned approval | | `GET /sdk/v1/payout-approvals/pending-count` | `{ success: true, count }` | | `GET /sdk/v1/payout-approvals/selection-preview` | `{ success: true, selection }` for a filtered pending selection | All require `approvals:read`. List parameters include `page`, `pageSize` (maximum 100), `status` (comma-separated), `excludeStatuses`, `ids` (approval UUIDs), `search`, `sourceType`, `fromDate`, `toDate`, `campaignId`, `submittedBy=me`, `sortBy`, and `sortOrder`. `me` refers to the SDK application that submitted the request. Statuses are `PENDING`, `APPROVING`, `APPROVED`, `REJECTED`, and `CANCELLED`. ## Decide one request | Method and path | Body | | - | - | | `POST /sdk/v1/payout-approvals/:id/approve` | `{}` | | `POST /sdk/v1/payout-approvals/:id/reject` | `{ "rejectionNote": "Please correct the amount" }` | | `POST /sdk/v1/payout-approvals/:id/cancel` | `{}` | All require `approvals:write`. IDs are approval UUIDs. Decisions atomically claim a pending request; an already decided request returns `409`. Cross-agency IDs return `404`. Cancellation is limited to the application that originally submitted the request. Use rejection when the integration is deciding someone else's pending request. ## Bulk decisions `POST /sdk/v1/payout-approvals/bulk-approve`, `/bulk-reject`, and `/bulk-cancel` accept: ```json theme={null} { "approvalIds": ["00000000-0000-4000-8000-000000000001"] } ``` Bulk rejection also accepts `rejectionNote`. Inspect each row of the result: a successful HTTP response can contain individual failures. Bulk cancellation preserves the original-submitter restriction. For bulk approval, use a stable `x-idempotency-key` when retrying. To approve a filtered selection, first call `selection-preview`, then send the returned IDs with `selectionFingerprint` and `selectionFilters`; stale selections are rejected by the existing approval workflow. Read the queue after any uncertain outcome before submitting a fresh decision. # Payouts Source: https://api-docs.usegrade.com/payouts Trigger, confirm, list, export, and manage payouts via /sdk/v1. For a one-off payment attributed to an existing campaign creator, use [Campaign quick pay](/campaign-creators/quick-pay). The trigger endpoints below send standalone payouts without campaign attribution. All endpoints below require: * `X-Application-Id` * `X-Api-Key` ### Creator location restrictions A blocked creator cannot receive a new payout, including a pending payout confirmation. Single-payout requests return HTTP `409` with this response: ```json theme={null} { "success": false, "code": "CREATOR_RESTRICTED_COUNTRY", "message": "We can't pay this creator through Grade because of where they're located. Please pay them directly." } ``` Immediate bulk payouts return this code and message on the failed item. Bulk confirmations return it in the item's `response`, with `status: 409`; other items can still succeed. A bulk trigger requesting confirmation fails before saving pending payouts if any recipient is blocked. Retrying verification, changing the payout provider, or creating another agency connection does not remove the block. Previously completed idempotent requests continue to replay their saved response. ### Approval mode and high-value payouts Standalone payouts follow the same two agency settings as payments sent from the Grade app and [Campaign quick pay](/campaign-creators/quick-pay). They apply to every request that would send money: * `POST /payouts/trigger` and `POST /payouts/trigger-bulk` with `requireConfirmation: false` * `POST /payouts/confirm` and `POST /payouts/confirm-bulk` A trigger with `requireConfirmation: true` only creates a pending payout, so both settings are applied when you confirm it. [Campaign creator payouts](/campaign-creators/send-payouts) pay at once and cannot wait for approval: with approval mode on, that endpoint pays nothing and answers `409` `APPROVAL_REQUIRED`. **High-value threshold.** When the agency has a payout threshold, Grade compares the requested amount (`payoutAmount`, or the sum of `lineItems`) with it in the agency's preferred currency. Above the threshold, the request returns `400` and sends nothing: ```json theme={null} { "success": false, "code": "THRESHOLD_CONFIRMATION_REQUIRED", "message": "Confirm this high-value payout before sending it.", "requiresThresholdConfirmation": true, "thresholdAmount": 1000, "thresholdCurrency": "USD" } ``` Review the amount, then repeat the request with `confirmHighValuePayout: true`. On a trigger, set it on the payout (on each item in a bulk trigger). On a confirmation, set it in the confirm body; it is the only place it counts for a two-step payout, and it covers every ID in a bulk confirmation. A single trigger or confirmation that was refused for the threshold is not saved against its idempotency key, so you can retry with the same key. Bulk responses are saved with their per-item results, so retry the refused items with a new key. Confirming a high-value payout does not skip approval or balance checks. **Approval mode.** When the agency has approval mode on, Grade does not pay. It freezes the creator and agency invoices as `PENDING_APPROVAL` and adds an approval request to the Grade **Approvals** queue, where the submitter shows as **API application**. No wallet debit or payment transaction happens, and no funds are reserved. The request answers `202`: ```json theme={null} { "success": true, "status": "PENDING_APPROVAL", "approvalId": "cd098819-cb2c-442b-a44b-80bd1de6e0e3", "invoiceId": "inv_...", "agencyInvoiceId": "inv_...", "currency": "USD", "amount": 200, "email": "creator@example.com" } ``` * `status: "PENDING_APPROVAL"` and `approvalId` identify an approval request. A paid response has `payoutId` instead and no `status`. Both are successful responses; check for `approvalId` before you track a payout. * `currency` and `amount` are in the creator's wallet currency, as in a paid response. * `payout_link` is never returned for an approval request, even with `returnPayoutLink: true`, because nothing was paid. * Follow the request with `GET /sdk/v1/payouts/approvals/:approvalId`, described below. Once it is approved, the payout belongs to your application: use its `payoutId` with `POST /payouts/status`, breakdowns, and invoices as usual. The threshold is checked first, so a high-value payout under approval mode needs `confirmHighValuePayout: true` before it can be queued. Approving the request in Grade, or with an `approvals:write` key through [Payout approvals](/payout-approvals), executes the payout; rejecting or cancelling it pays nothing. Funds and wallet checks apply when it executes. ## POST /sdk/v1/payouts/trigger Create a single payout. Supports immediate execution or returning a pending confirmation token. > [!NOTE] > > This endpoint does not calculate campaign contract terms or tiered bonus templates. To configure reusable campaign bonuses, use `/sdk/v1/bonus-templates`, apply the returned `templateId` to a campaign contract, and let Grade calculate eligible bonus line items from tracked campaign media. ### Headers * `X-Idempotency-Key` (required) ### Body You must provide: * `payoutRecipientEmail` (required; must be a valid email) * `payoutCurrency` (required; one of `USD`, `CAD`, `GBP`, `EUR`) * exactly one of: * `payoutAmount` (positive; max 2 decimals) * `lineItems` (array; each item requires `quantity` and `perItemAmount`) * `requireConfirmation` (optional; defaults to `true`) * `returnPayoutLink` (optional boolean; when `true`, successful executed payout responses include `payout_link`) * `confirmHighValuePayout` (optional boolean; defaults to `false`; acknowledges a payout above the agency's [threshold](#approval-mode-and-high-value-payouts). Only read when `requireConfirmation` is `false`) * `platformFeePayerOverride` (optional; one of `INHERIT`, `CREATOR_PAYS_ALL`, `AGENCY_PAYS_ALL`, `CUSTOM_SPLIT`) * `platformFeeAgencySharePercent` (required when `platformFeePayerOverride` is `CUSTOM_SPLIT`; number between `0` and `100`) ```json theme={null} { "payoutRecipientEmail": "creator@example.com", "payoutCurrency": "USD", "requireConfirmation": true, "lineItems": [ { "lineItemDescription": "Instagram post", "quantity": 1, "perItemAmount": "150.00" }, { "lineItemDescription": "Story set", "quantity": 2, "perItemAmount": "25.00" } ] } ``` If you need to override who covers the platform fee for this payout only, send: ```json theme={null} { "payoutRecipientEmail": "creator@example.com", "payoutCurrency": "USD", "payoutAmount": "200.00", "platformFeePayerOverride": "CUSTOM_SPLIT", "platformFeeAgencySharePercent": 40 } ``` Omit `platformFeePayerOverride`, or set it to `INHERIT`, to use the agency default. The returned `preview.platformFee` values reflect the effective override. Set `returnPayoutLink` to `true` when you need the payout link in the execution response. Pending trigger responses do not include a link because the payout has not been executed yet; the confirmed payout response includes `payout_link` if the original trigger requested it. If the link cannot be resolved at response time after a successful payout, `payout_link` is `null`. ### Response * If `requireConfirmation: true`: `201` ```json theme={null} { "success": true, "pending_payout_id": "pnd_...", "preview": { "payoutRecipientEmail": "creator@example.com", "payoutCurrency": "USD", "payoutAmount": 200, "lineItems": [ { "lineItemDescription": "Instagram post", "quantity": 1, "perItemAmount": 150, "lineTotal": 150 }, { "lineItemDescription": "Story set", "quantity": 2, "perItemAmount": 25, "lineTotal": 50 } ], "creatorCurrency": "USD", "amountInCreatorCurrency": 200, "platformFee": { "displayCurrency": "USD", "feeTotalDisplayAmount": 0, "feePaidByCreatorDisplayAmount": 0, "feePaidByAgencyDisplayAmount": 0, "netDisplayAmount": 200 } }, "expiresAt": "2026-02-19T00:00:00.000Z" } ``` * If `requireConfirmation: false`: `200` (example includes `payout_link` when `returnPayoutLink` is `true`) ```json theme={null} { "success": true, "payoutId": "pay_...", "invoiceId": "inv_...", "currency": "USD", "amount": 200, "email": "creator@example.com", "payout_link": "https://payout.example/..." } ``` * If `requireConfirmation: false` and the agency has approval mode on: `202` with the [approval request](#approval-mode-and-high-value-payouts) instead of a payout. Replays return the same `202`. ### Common errors * `400`: invalid payload (missing fields, currency not supported, >2 decimals, etc.) * `400`: insufficient funds (includes `sufficient: false`, `requiredAmount`, `currency: "USD"`) * `400` `THRESHOLD_CONFIRMATION_REQUIRED`: above the agency threshold; resend with `confirmHighValuePayout: true` * `400` `CURRENCY_CONVERSION_FAILED`: the threshold could not be evaluated; nothing was sent * `400` `APPROVAL_SUBMISSION_FAILED`: approval mode is on and the approval request could not be created (for example, a frozen wallet); nothing was sent * `401`: missing/invalid SDK headers * `403`: origin not allowed (when allowlist is configured and `Origin` is present) ## POST /sdk/v1/payouts/trigger-bulk Create up to 100 payouts in one request. ### Headers * `X-Idempotency-Key` (required) ### Body `payouts` must be a non-empty array, max length 100. Each item is the same shape as `POST /payouts/trigger`. All items must share the same `requireConfirmation` value. Each item can set its own `platformFeePayerOverride` and `platformFeeAgencySharePercent`. ```json theme={null} { "payouts": [ { "payoutRecipientEmail": "creator1@example.com", "payoutCurrency": "USD", "requireConfirmation": true, "payoutAmount": "10.00" }, { "payoutRecipientEmail": "creator2@example.com", "payoutCurrency": "USD", "requireConfirmation": true, "payoutAmount": "15.00" } ] } ``` ### Response * If `requireConfirmation: true`: `201` ```json theme={null} { "success": true, "requireConfirmation": true, "results": [ { "index": 0, "pending_payout_id": "pnd_...", "preview": { "payoutRecipientEmail": "creator1@example.com", "payoutCurrency": "USD", "payoutAmount": 10 }, "expiresAt": "2026-02-19T00:00:00.000Z" } ] } ``` * If `requireConfirmation: false`: `200` (example includes `payout_link` when an item sets `returnPayoutLink` to `true`) ```json theme={null} { "success": true, "requireConfirmation": false, "results": [ { "index": 0, "success": true, "payoutId": "pay_...", "invoiceId": "inv_...", "currency": "USD", "amount": 10, "email": "creator1@example.com", "payout_link": "https://payout.example/..." } ] } ``` If any entry fails in immediate mode, the response `success` will be `false` and `results` will contain both successes and failures. In immediate mode each item meets the [threshold and approval mode](#approval-mode-and-high-value-payouts) on its own. An item above the threshold without its own `confirmHighValuePayout: true` fails with `code: "THRESHOLD_CONFIRMATION_REQUIRED"` while the other items continue. With approval mode on, each accepted item is an approval request rather than a payout: ```json theme={null} { "success": false, "requireConfirmation": false, "results": [ { "index": 0, "success": true, "status": "PENDING_APPROVAL", "approvalId": "cd098819-cb2c-442b-a44b-80bd1de6e0e3", "invoiceId": "inv_...", "agencyInvoiceId": "inv_...", "currency": "USD", "amount": 10, "email": "creator1@example.com" }, { "index": 1, "success": false, "code": "THRESHOLD_CONFIRMATION_REQUIRED", "message": "Confirm this high-value payout before sending it.", "requiresThresholdConfirmation": true, "thresholdAmount": 1000, "thresholdCurrency": "USD" } ] } ``` ## POST /sdk/v1/payouts/pending Fetch a single pending payout preview/status by `pending_payout_id`. Once confirmed, `result` holds the confirm response: a payout, or an approval request when approval mode was on. ### Body ```json theme={null} { "pending_payout_id": "pnd_..." } ``` ### Response ```json theme={null} { "success": true, "data": { "pending_payout_id": "pnd_...", "createdAt": "2026-02-19T00:00:00.000Z", "expiresAt": "2026-02-26T00:00:00.000Z", "confirmedAt": null, "expired": false, "preview": { "payoutRecipientEmail": "creator@example.com", "payoutCurrency": "USD", "payoutAmount": 10 }, "result": null } } ``` ## POST /sdk/v1/payouts/pending-bulk Fetch multiple pending payout previews/statuses. ### Body Accepts a string (comma-separated) or an array: ```json theme={null} { "pending_payout_ids": ["pnd_1", "pnd_2"] } ``` ### Response Returns found items plus `missing` IDs: ```json theme={null} { "success": true, "data": [{ "pending_payout_id": "pnd_1", "preview": { "payoutAmount": 10 } }], "missing": ["pnd_2"] } ``` ## GET /sdk/v1/payouts/pending List pending payouts for the application (table-friendly). ### Query parameters * `page` (default `1`) * `limit` (default `50`, max `100`) * `includeExpired` (`true|false`, default `false`) * `includeConfirmed` (`true|false`, default `false`) ### Response Each row includes `expiresInSeconds` and `expired`. ```json theme={null} { "success": true, "data": [ { "pending_payout_id": "pnd_...", "createdAt": "2026-02-19T00:00:00.000Z", "expiresAt": "2026-02-26T00:00:00.000Z", "confirmedAt": null, "expired": false, "expiresInSeconds": 604800, "preview": { "payoutRecipientEmail": "creator@example.com", "payoutCurrency": "USD", "payoutAmount": 10 }, "result": null } ], "pagination": { "page": 1, "limit": 50, "totalPages": 1, "totalItems": 1 } } ``` ## POST /sdk/v1/payouts/confirm Confirm and execute a pending payout, or submit it for approval when the agency has approval mode on. ### Headers * `X-Idempotency-Key` (required) ### Body ```json theme={null} { "pending_payout_id": "pnd_...", "confirmHighValuePayout": true } ``` * `pending_payout_id` (required) * `confirmHighValuePayout` (optional boolean; defaults to `false`; acknowledges a payout above the agency's [threshold](#approval-mode-and-high-value-payouts)) ### Response On success: `200` (example includes `payout_link` when the original trigger set `returnPayoutLink` to `true`) ```json theme={null} { "success": true, "payoutId": "pay_...", "invoiceId": "inv_...", "currency": "USD", "amount": 10, "email": "creator@example.com", "payout_link": "https://payout.example/..." } ``` With approval mode on: `202` with the [approval request](#approval-mode-and-high-value-payouts). The pending payout is then confirmed: confirming it again, with any idempotency key, returns the same `202` and never creates a second request, even after approval mode is turned off or the request is decided. If the pending payout is expired: `410 { "success": false, "message": "Pending payout has expired." }` Above the agency threshold without `confirmHighValuePayout: true`: `400` with `code: "THRESHOLD_CONFIRMATION_REQUIRED"`. If the approval request cannot be created: `400` with `code: "APPROVAL_SUBMISSION_FAILED"`. In both cases the pending payout stays unconfirmed. ## POST /sdk/v1/payouts/confirm-bulk Confirm and execute up to 100 pending payouts. ### Headers * `X-Idempotency-Key` (required) ### Body Accepts a string (comma-separated) or an array: ```json theme={null} { "pending_payout_ids": ["pnd_1", "pnd_2"], "confirmHighValuePayout": true } ``` `confirmHighValuePayout` (optional boolean) applies to every listed payout. ### Response `success` is `true` only if **all** confirmations returned `status: 200` or `202`. Each `response` is what `POST /payouts/confirm` would return for that ID, so `202` items are approval requests. ```json theme={null} { "success": false, "results": [ { "pending_payout_id": "pnd_1", "status": 200, "response": { "success": true, "payoutId": "pay_..." } }, { "pending_payout_id": "pnd_2", "status": 202, "response": { "success": true, "status": "PENDING_APPROVAL", "approvalId": "cd098819-cb2c-442b-a44b-80bd1de6e0e3" } }, { "pending_payout_id": "pnd_3", "status": 400, "response": { "success": false, "code": "THRESHOLD_CONFIRMATION_REQUIRED" } }, { "pending_payout_id": "pnd_4", "status": 410, "response": { "success": false, "message": "Pending payout has expired." } } ] } ``` ## GET /sdk/v1/payouts/approvals/:approvalId Read the current state of an approval request your application created, through these endpoints or [Campaign quick pay](/campaign-creators/quick-pay). Requires `payouts:read` and no idempotency key. Another application in the same agency gets `404`. ```json theme={null} { "success": true, "approvalId": "cd098819-cb2c-442b-a44b-80bd1de6e0e3", "status": "APPROVED", "invoiceId": "inv_...", "agencyInvoiceId": "inv_...", "payoutId": "CCPAY_...", "campaignId": null, "campaignCreatorRecordId": null, "rejectionNote": null, "createdAt": "2026-10-28T09:00:00.000Z", "decidedAt": "2026-10-28T10:00:00.000Z" } ``` | Status | Meaning | | - | - | | `PENDING` | Waiting for review; no debit. | | `APPROVING` | Execution is in progress; poll with backoff. | | `APPROVED` | Payment initiated. Use `payoutId` with `POST /payouts/status`. | | `REJECTED` | Review declined; `rejectionNote` holds the reason when supplied. | | `CANCELLED` | Request cancelled; nothing was paid. | `payoutId` and `decidedAt` are `null` until they apply. `campaignId` and `campaignCreatorRecordId` are set only for Campaign quick pay requests. ## POST /sdk/v1/payouts/status Fetch payout status records for specific payout IDs (up to 100). ### Body Accepts multiple aliases; preferred: ```json theme={null} { "payout_ids": ["pay_1", "pay_2"] } ``` ### Response Results preserve request order for found items and include `missing`. ```json theme={null} { "success": true, "data": [{ "payoutId": "pay_1", "status": "sent", "currency": "USD" }], "missing": ["pay_2"] } ``` ### Restricted-country refunds The payout keeps its original `payoutId` and authorization scope. This endpoint, the payout list, and creator payout reads include `creatorRestricted` and a nullable `refund` object. A refund does not mean the creator was paid. | Refund state | Meaning | | - | - | | `refund: null` | No restricted-country refund is reported for this payout. | | `refund.status: pending` | Grade is checking and returning eligible funds. No refund amount is confirmed yet. | | `refund.status: needs_review` | Support must review the return of funds. No refund amount is confirmed yet. | | `status: refunded`, `refund.status: completed` | The agency wallet credit has committed. `amountUsd` is the full original agency debit, including Grade fees. | Only completed refunds include `amountUsd` and `completedAt`. Use the safe `message` for display; the response does not include a country, region, provider error, or verification evidence. ```json theme={null} { "payoutId": "pay_1", "status": "refunded", "creatorRestricted": true, "refund": { "status": "completed", "reasonCode": "restricted_country", "message": "We can't pay this creator through Grade because of where they're located. The money is back in your wallet. Please pay them directly.", "amountUsd": "50.00", "completedAt": "2026-10-19T12:00:00.000Z" } } ``` Disable new payments and withdrawal-email resends when `creatorRestricted` is `true`. Grade also rejects new payments to a blocked creator with `409` and `code: CREATOR_RESTRICTED_COUNTRY`. An override does not reissue completed refunds. Poll the existing payout reads for updates; outbound payout status webhooks are not yet available. ## GET /sdk/v1/payouts/:payoutId/breakdown Fetch the saved line items and contract breakdown for a campaign or direct payout using its `CCPAY_...` ID. The payout must belong to the agency authenticated by your SDK credentials. This includes payouts created in the dashboard, as with `GET /sdk/v1/payouts`. ### Path parameters * `payoutId` (required): the `CCPAY_...` reference returned by the payout list or trigger endpoint. ```bash theme={null} curl "$GRADE_API_BASE_URL/sdk/v1/payouts/$PAYOUT_ID/breakdown" \ -H "X-Application-Id: $APPLICATION_ID" \ -H "X-Api-Key: $API_KEY" ``` ### Response ```json theme={null} { "success": true, "data": { "payoutId": "CCPAY_example_1776686400", "campaignId": "campaign_123", "campaignCreatorRecordId": "ccr_123", "lineItems": [ { "type": "FIXED_FULL", "description": "Fixed payment", "quantity": 1, "amount": 100, "amountCurrency": "EUR" } ], "lineItemsSource": "payout", "lineItemsCurrency": "EUR", "contractBreakdown": { "capturedAt": "2026-04-20T12:00:00.000Z", "terms": { "schemaVersion": 1, "payoutType": "FIXED", "currency": "EUR", "fixed": { "amount": 100, "paymentOption": "STANDARD", "proratedByUploads": false, "prorateByTime": false, "rateScope": "CREATOR", "platforms": [] }, "performance": null, "bonus": null, "payCycle": { "enabled": false, "timesPerPeriod": null, "period": null, "weekday": null, "startImmediately": true } }, "components": [], "tierScope": "CREATOR", "templateId": null, "snapshots": [] } } } ``` * `lineItems` preserves the stored item fields, including media IDs, view counts, and per-media breakdowns when available. Item fields vary by payout type and age. * `lineItemsSource` is `payout` when saved payout items exist, `invoice` when falling back to invoice items, or `none` when neither is available. Invoice items can include platform fee adjustments. * `lineItemsCurrency` is the shared output currency recorded on every saved payout item (`amountCurrency`/`amount_currency`, `outputCurrency`/`output_currency`, or governing-history segments' output currency). It is `null` if any item's output currency is unknown or the currencies differ. Contract, historical, and display currencies can describe amounts before conversion, so they are not used to label the payable amounts. For invoice items, this field is the invoice currency; `displayAmount` and `displayCurrency` describe the original amount separately. * `contractBreakdown` contains the captured contract `terms` (fixed, performance, bonus, and pay-cycle settings) and payment-term `components`. Current contract edits do not change this response. Older snapshots can contain `components` with `terms: null`. * `contractBreakdown.snapshots` preserves all captured contract versions for payouts spanning multiple historical contracts. Each snapshot includes `campaign_creator_contract_history_id`, `line_item_indexes` (zero-based indexes of the captured payout items), `terms_snapshot`, and `contract_terms`. `terms` is the primary contract projection; use `snapshots` for each governing version. Older payouts return an empty array. * Direct payouts have `campaignId: null` and `campaignCreatorRecordId: null`. Payouts without saved contract details return `contractBreakdown: null`; missing line items return `[]`. Historical breakdowns remain available for cancelled payouts and archived or deleted campaigns. A breakdown does not indicate that funds were delivered; use the payout status endpoint to check delivery. ### Common errors * `400`: invalid `CCPAY` ID (maximum 64 characters). * `401`: missing or invalid SDK credentials. * `404`: payout does not exist or belongs to another agency. ## POST /sdk/v1/payouts/cancel Cancel an in-flight payout. ### Headers * `X-Idempotency-Key` (required) ### Body Provide either `payoutId` or `payoutReferenceId`: ```json theme={null} { "payoutId": "pay_..." } ``` ### Response ```json theme={null} { "success": true, "data": { "refundedUsd": 10 } } ``` If the payout was already cancelled, the response may include: ```json theme={null} { "success": true, "data": { "refundedUsd": 10, "alreadyCancelled": true } } ``` ## GET /sdk/v1/payouts List agency payouts. ### Query parameters * `page` (default `1`) * `limit` (default `50`, max `100`) * `sortBy` (optional) * `sortOrder` (`asc|desc`, default `desc`) * `search` (optional) * `payoutType` (optional; currently supports `DIRECT`) * `statuses` (optional; comma-separated) * `from` and `to` (optional; ISO timestamps) If `from`/`to` is provided without a timezone offset, it is treated as UTC. Supported `statuses` values (invalid values are ignored): `processing`, `created`, `delivery_pending`, `delivery_failed`, `sent`, `delivered`, `claimed`, `reversed`, `canceled`, `expired`, `failed`, `pending`, `completed`, `refunded`, `flagged`, `delayed` ### Response ```json theme={null} { "success": true, "data": [{ "payoutId": "pay_...", "status": "claimed", "currency": "USD" }], "pagination": { "page": 1, "limit": 50, "totalPages": 1, "totalItems": 1 }, "meta": { "bufferBusinessDays": 1, "accelerated": false, "bankClosedDates": [] } } ``` ## GET /sdk/v1/payouts/export Export payouts as CSV or PDF. CSV exports include `refundStatus`, `refundReasonCode`, `refundMessage`, `refundAmountUsd`, and `refundCompletedAt`. Amount and completion time remain empty until the refund commits. PDF exports distinguish refunds from paid payouts and show the confirmed USD return amount. ### Query parameters * `format` (required): `csv` or `pdf` * `from` and `to` (required): ISO timestamps * All filters supported by `GET /sdk/v1/payouts` (`statuses`, `search`, `sortBy`, `sortOrder`, ...) * `timeZone` (optional; used for PDF rendering) ### Responses * `text/csv` with `Content-Disposition: attachment; filename="payout-transactions-YYYY-MM-DD.csv"` * `application/pdf` with `Content-Disposition: attachment; filename="payout-transactions-YYYY-MM-DD.pdf"` If the export would exceed 10,000 rows: `413` with a JSON error. # Settings Source: https://api-docs.usegrade.com/settings Read SDK-related agency settings via /sdk/v1. All endpoints below require: * `X-Application-Id` * `X-Api-Key` ## GET /sdk/v1/settings Get SDK-related agency settings. ### Response ```json theme={null} { "success": true, "data": { "preferredCurrency": "USD", "tiktokScrapeLocationEnabled": false, "tiktokScrapeCountryOptions": [] } } ``` When Grade enables campaign scraping locations for your agency, `tiktokScrapeLocationEnabled` is `true` and `tiktokScrapeCountryOptions` contains the supported countries as `{ "value": "VN", "label": "Vietnam" }` entries. Use these values for `tiktokScrapeCountryCode` when creating or updating a [campaign](/campaigns). The setting is read-only here; Grade controls agency access. # Contract versions Source: https://api-docs.usegrade.com/syncing/contracts Incrementally sync contract versions with complete records, removals, and durable cursors. ## GET /sdk/v1/campaigns/:campaignId/contracts/sync Sync contract history across an entire campaign without requesting each creator separately. Each version is a separate record, so large histories are paginated. Replace by `id`, which equals `campaignCreatorContractHistoryId`. Requires `X-Application-Id`, `X-Api-Key`, and `campaigns:read`. Follow the [shared syncing workflow](/syncing/overview) for pagination, cursor storage, retries and removals. Only `cursor` and `limit` are accepted. ```bash theme={null} curl --get "$BASE_URL/sdk/v1/campaigns/$CAMPAIGN_ID/contracts/sync" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" \ --data-urlencode "limit=100" ``` On subsequent requests, add `--data-urlencode "cursor=$SAVED_CURSOR"`. ## Record format Each item in `data` is a complete replacement with these fields: ```json theme={null} { "id": "CCCH_123", "campaignCreatorContractHistoryId": "CCCH_123", "campaignId": "CAMPAIGN_123", "campaignCreatorRecordId": "CCR_123", "creatorProfileId": "CP_123", "contractInstanceId": "CCI_123", "contractInstanceState": "OPEN", "isCurrentInstance": true, "effectiveFromUploadDate": "2027-01-01", "status": "ACTIVE", "schemaVersion": 2, "semanticHash": "75109c26d59db01613e34605d7f76299b7ef9942aa4f4cc655f42fc6f7eabd64", "termsSnapshot": { "schemaVersion": 2, "contractInstanceId": "CCI_123", "effectiveFromUploadDate": "2027-01-01", "payoutType": "NONE", "currency": "USD", "fixed": { "active": false, "amount": null, "paymentOption": null, "upfrontPercentage": null, "proratedByUploads": false, "prorationAssumedUploads": null, "minimumUploads": null, "prorateByTime": false, "rateScope": null, "platforms": [], "mediaPayoutMode": null }, "performance": { "active": false, "amount": null, "unitSize": null, "unit": null, "viewScope": null, "minViews": null, "maxViews": null, "excludeMinimumViews": false, "spendCaps": { "amount": null, "scope": "NONE", "period": "LIFETIME" }, "groupingMode": "NONE", "payoutTiming": null }, "crosspost": { "minDistinctPlatforms": 1, "requiredPlatforms": [], "captionFilter": null }, "bonus": { "active": false, "payoutTiming": null, "tierScope": null, "components": [], "templateProvenance": null }, "payCycle": { "active": false, "timesPerPeriod": null, "period": null, "weekday": null, "monthDay": null, "startImmediately": false, "firstDueAt": null, "timeZone": "UTC" }, "eligibility": { "uploadedOnOrAfter": null, "postTestPhaseUploadCutoff": null, "testPhaseCreator": false }, "provenance": { "source": "AUTHORED", "sourceIds": [] }, "compatibility": { "state": "COMPLETE", "missingEvidence": [] } }, "supersedesContractHistoryId": null, "createdAt": "2026-10-26T10:00:00.000Z", "retiredAt": null, "timeZone": "UTC" } ``` `termsSnapshot` contains the complete stored contractual terms, interpreted according to `schemaVersion`. The example above is a valid version with no active payment components. The [contract history](/campaign-creators/contract-history) endpoint presents these terms in its public display format. `semanticHash` describes those terms. This feed excludes internal author IDs, repair references, and audit reasons outside the terms snapshot. Versions include future effective dates, superseded/voided versions, and previous contract instances for available memberships. `isCurrentInstance` identifies the membership's current instance; it does **not** mean that the version governs every upload or is already effective. `contractInstanceState` is `OPEN` or `CLOSED`; version `status` is `ACTIVE`, `SUPERSEDED`, or `VOIDED`. Keep effective dates locally. A future version is delivered when created; merely reaching that date does not change the stored version or emit a new record. Contract terms are governed by upload dates and the returned campaign/agency `timeZone`, not just the polling date. Use the existing contract read and payout preview endpoints when you need Grade's current interpretation or payable value. Edits, retirement, replacement, instance closure, changes to the current instance, and timezone changes produce replacements. A superseded version stays in the feed with its status; physical deletion or an unavailable membership produces a removal. A membership without history contributes no version records. ## Stored terms schema `termsSnapshot` is the versioned stored contract, distinct from the display `contract` object on the contract-history list. Persist the entire object, including fields added in later schema versions. | Field | Contents | | - | - | | `schemaVersion`, `contractInstanceId`, `effectiveFromUploadDate` | Version and governing identity/date. | | `payoutType`, `currency` | Payment type and contract currency. | | `fixed` | Active flag, decimal amount, payment option, creator/media scope, supported platforms and proration settings. | | `performance` | Active flag, decimal rate, unit size, view thresholds, spend caps, grouping and payout timing. | | `crosspost` | Required platforms, minimum distinct platforms and caption filter. | | `bonus` | Active flag, timing, scope, tier components and template provenance. | | `payCycle` | Recurrence, first due date and timezone. | | `eligibility` | Upload cutoff and test-phase eligibility facts. | | `provenance`, `compatibility` | Origin references and whether historical evidence is complete. These are stored version facts, not payment authorization. | | `contentStart`, `paymentRules` | Present on rule-based contract versions; preserve the stored rule tree. | An inactive component has `active: false`; its other fields can be null. Contractual decimal values in the stored snapshot are strings. Do not derive payout totals by applying only part of the snapshot. Grade's payout preview accounts for the full rules, upload dates and settlement history. # Campaign creators Source: https://api-docs.usegrade.com/syncing/creators Incrementally sync campaign creators with complete records, removals, and durable cursors. ## GET /sdk/v1/campaigns/:campaignId/creators/sync Sync campaign membership and creator profiles, including hidden members. Replace records by `id`, which equals `campaignCreatorRecordId`. Removed or deleted memberships and unavailable creator profiles produce removals. Requires `X-Application-Id`, `X-Api-Key`, and `campaigns:read`. Follow the [shared syncing workflow](/syncing/overview) for pagination, cursor storage, retries and removals. Only `cursor` and `limit` are accepted. ```bash theme={null} curl --get "$BASE_URL/sdk/v1/campaigns/$CAMPAIGN_ID/creators/sync" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" \ --data-urlencode "limit=100" ``` On subsequent requests, add `--data-urlencode "cursor=$SAVED_CURSOR"`. ## Record format Each item in `data` is a complete replacement with these fields: ```json theme={null} { "id": "CCR_123", "campaignCreatorRecordId": "CCR_123", "campaignId": "CAMPAIGN_123", "creatorProfileId": "CP_123", "creatorName": "Jordan", "creatorEmail": "jordan@example.com", "profileImage": null, "isVerified": true, "hidden": false, "completed": false, "completedAt": null, "currentContractInstanceId": "CCI_123" } ``` `creatorName` uses your agency display-name override when present. Changes to names, email, profile images, verification, hidden/completed flags, and the current contract instance produce replacements. Hidden members remain in the feed with `hidden: true`; filter them in your local view if needed. Use `campaignCreatorRecordId` to join [contract versions](/syncing/contracts). The feed contains membership/profile fields shown above. Payable previews, spend, performance totals, and expanded payment-term projections remain on the [campaign creators list](/campaign-creators/list). # Media eligibility scores Source: https://api-docs.usegrade.com/syncing/eligibility Incrementally sync media eligibility scores with complete records, removals, and durable cursors. ## GET /sdk/v1/campaigns/:campaignId/media/eligibility/sync Sync scores for individual media posts in a campaign. Replace by `id`, which equals `campaignCreatorMediaId`. Requires `X-Application-Id`, `X-Api-Key`, and `campaigns:read`. Follow the [shared syncing workflow](/syncing/overview) for pagination, cursor storage, retries and removals. Only `cursor` and `limit` are accepted. ```bash theme={null} curl --get "$BASE_URL/sdk/v1/campaigns/$CAMPAIGN_ID/media/eligibility/sync" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" \ --data-urlencode "limit=100" ``` On subsequent requests, add `--data-urlencode "cursor=$SAVED_CURSOR"`. ## Record format Each item in `data` is a complete replacement with these fields: ```json theme={null} { "id": "CCMEDIA_123", "campaignCreatorMediaId": "CCMEDIA_123", "campaignCreatorRecordId": "CCR_123", "campaignId": "CAMPAIGN_123", "url": "https://www.tiktok.com/@jordan/video/7350000000000000000", "platform": "TIKTOK", "score": 0.85 } ``` The feed includes posts (`isAccount: false`) with a score or `score: null`. Accounts are excluded. It follows the [eligibility score list](/campaign-media/eligibility-scores): tracking retirement alone does not remove an otherwise available post. Score, URL, platform, membership and visibility changes produce replacements or removals as appropriate. A score is the stored eligibility score; this feed does not calculate payout eligibility, payment exclusions, or payout amounts. # Syncing Source: https://api-docs.usegrade.com/syncing/overview Keep local copies current by downloading changed records and removals with durable cursors. Sync endpoints let you maintain a local copy of Grade data. Start with a paginated copy, then poll with the saved cursor to receive changed records and removal IDs. An unchanged feed returns an empty page. You choose when to poll. | Feed | Scope | Record identity | | - | - | - | | [Campaign media](/campaign-media/sync) | `campaigns:read`, one campaign | `campaignCreatorMediaId` | | [Campaign creators](/syncing/creators) | `campaigns:read`, one campaign | `id` (campaign creator record) | | [Contract versions](/syncing/contracts) | `campaigns:read`, one campaign | `id` (contract history version) | | [Media eligibility scores](/syncing/eligibility) | `campaigns:read`, one campaign | `id` (campaign media record) | | [Payouts](/syncing/payouts) | `payouts:read`, your agency | `id` (stable payout sync identity) | | [Transactions](/syncing/transactions) | `payouts:read`, your agency | `id` (transaction) | | [Tracked media](/syncing/tracked-media) | `analytics:read`, your agency | `id` (tracked media record) | Every request requires `X-Application-Id` and `X-Api-Key`. Keep a separate local collection and cursor for each agency, endpoint, campaign, and supported filter set. Existing list endpoints keep their behavior. Each new feed has an explicit record format documented on its page; it is not a drop-in replacement for list responses containing previews, aggregates, or display conversions. ## Apply a page and save its cursor together 1. Start without `cursor`, using an empty local collection for this sync scope. 2. Replace or insert each `data` record using its identity from the table above. 3. Delete each `removedIds` entry. Unknown IDs are harmless. 4. Commit `nextCursor` in the **same local transaction** as those changes. 5. When `hasMore` is `true`, immediately request another page with that cursor. 6. When `hasMore` is `false`, keep the cursor for your next poll. Save the cursor from empty pages too. Continue through pages containing only removals. Use one worker at a time for each local copy; applying an older response after a newer one could overwrite newer state. > [!NOTE] > > Cursors do not expire by age. Pausing an integration, restarting it, changing the > page size, or rotating its API key does not require a full reload. A cursor stays > bound to its feed and agency/campaign scope, and every request still checks access. ## Shared request and response The six new feeds accept only `cursor` and `limit`. Campaign media additionally supports its documented initial filters. Unknown parameters are rejected so a misspelled filter cannot silently broaden a sync. | Parameter | Behavior | | - | - | | `cursor` | Opaque `nextCursor` returned by this feed. Omit only to create a new local copy. | | `limit` | Maximum IDs processed per page, including removals. 1–100, default 100. You can change it while resuming. | Pages target 1 MiB of record data. A single larger record is returned intact; page length can be smaller than `limit`. ```json theme={null} { "success": true, "data": [{ "id": "record_123", "otherFields": "complete record" }], "removedIds": ["record_456"], "hasMore": false, "nextCursor": "opaque-cursor" } ``` `data` contains **complete replacements**, not partial patches. `removedIds` means the record no longer belongs in this local view: for example, it was deleted, moved to another scope, or became unavailable. Restored records return as upserts. Campaign media also removes records that leave its saved filters. ## Concurrent changes and retries Each page reads a consistent current state. A multi-page run is not a frozen export: edits during paging appear in a later page or the next poll. Transactions that started before the checkpoint and committed later are included too. Delivery is at least once. Repeated records and removals are safe when applied idempotently. Multiple edits can become one replacement containing the latest state; these feeds are not audit logs of intermediate edits. On an API error or failed local transaction, retry the last committed cursor. Keep your local data. Do not automatically restart the sync on an error. * `400`: fix malformed parameters or a damaged/wrong-scope cursor. There is no routine cursor-expiry error. * `401` / `403`: restore valid credentials or the required scope, then resume. * `404`: the requested campaign is unavailable to your agency. Do not reuse its cursor for a different campaign. * `429` / `5xx`: back off and retry the same saved cursor; honor `Retry-After` when supplied. ## Client example The repository demo exports `sync` from `sdk-demo/backend/src/sdkClient.js`. Supply your own database adapter and transaction implementation: ```javascript theme={null} const { sync } = require('./src/sdkClient'); const cursor = await store.readCursor(syncScope); await sync.creators.run({ campaignId, cursor, limit: 100, applyPage: async ({ data, removedIds, nextCursor }) => { await store.transaction(async tx => { for (const record of data) await tx.replace(syncScope, record.id, record); for (const id of removedIds) await tx.remove(syncScope, id); await tx.saveCursor(syncScope, nextCursor); }); } }); ``` Use `sync.contracts`, `sync.eligibility`, `sync.payouts`, `sync.transactions`, or `sync.trackedMedia` for the other new feeds. Agency feeds omit `campaignId`. The deployed campaign media feed retains its existing `mediaSync` client and `campaignCreatorMediaId` identity; see its [client example](/campaign-media/sync#client-example). ## What syncing improves Later polls transfer and hydrate only records affected by changes. The initial copy still reads the full scope, in bounded pages. If every record changes, catching up still requires every record. Page size bounds individual requests; it does not guarantee less total work when downloading everything. For date-range charts, campaign totals, and payable previews, use the existing analytics and payment endpoints. Sync records provide durable facts for a local copy; they do not continually recompute financial or analytical aggregates. # Payouts Source: https://api-docs.usegrade.com/syncing/payouts Incrementally sync payouts with complete records, removals, and durable cursors. ## GET /sdk/v1/payouts/sync Sync agency payout settlement state, including provider status changes, withdrawal retries and completed restricted-country refunds. Replace by the stable `id`, not by `payoutId`, which can initially be null. Requires `X-Application-Id`, `X-Api-Key`, and `payouts:read`. Follow the [shared syncing workflow](/syncing/overview) for pagination, cursor storage, retries and removals. Only `cursor` and `limit` are accepted. ```bash theme={null} curl --get "$BASE_URL/sdk/v1/payouts/sync" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" \ --data-urlencode "limit=100" ``` On subsequent requests, add `--data-urlencode "cursor=$SAVED_CURSOR"`. ## Record format Each item in `data` is a complete replacement with these fields: ```json theme={null} { "id": "123", "transactionId": "TX_123", "payoutId": "PAYOUT_123", "campaignId": "CAMPAIGN_123", "creatorEmail": "jordan@example.com", "amount": "-120.50", "currency": "USD", "transactionStatus": "COMPLETED", "status": "completed", "datePaid": "2026-10-26T10:00:00.000Z", "recipientAmount": "118.00", "recipientCurrency": "USD", "fulfillmentMode": "CREATOR_WALLET_WITHDRAWALS", "creatorWithdrawalId": "WITHDRAWAL_123", "creatorWithdrawalState": "SUCCEEDED", "creatorWithdrawalProvider": "provider", "withdrawalCompletedAt": "2026-10-26T10:00:00.000Z", "refund": null } ``` `id` is an opaque stable sync identity for the payout transfer. Use `payoutId` for existing payout operations when present; do not pass the sync `id` to them. Campaign-linked and direct/role payouts are included. A completed payout remains in the feed, so later corrections can still update it. `status` uses the same settlement rules as the [payout list](/payouts). `transactionStatus` is the underlying ledger status; it can be completed while the recipient's external withdrawal is still pending. The latest associated withdrawal is returned, including a retry after a failure. `amount` is the signed sender ledger amount in `currency`. `recipientAmount` is the stored recipient display amount in `recipientCurrency`; either recipient field can be null. Monetary values are **decimal strings**. Neither field is a live currency conversion or an inferred final bank receipt. Payout previews, fee breakdowns and expected-landing estimates remain on existing endpoints. A completed restricted-country cancellation sets `status: "refunded"` and returns `refund: { reasonCode: "restricted_country", amountUsd, completedAt }`. The object describes that specific refund; other cancellation/reversal states are represented by the settlement and transaction status fields. Internal provider evidence and errors are excluded. Moves, deletion of required records, and transfers leaving the public payout view produce removals. New payout links and changes to existing links, ledger status, fulfillment mode, withdrawal associations, provider or refund state produce replacements. # Tracked media Source: https://api-docs.usegrade.com/syncing/tracked-media Incrementally sync tracked media with complete records, removals, and durable cursors. ## GET /sdk/v1/analytics/tracked-media/sync Sync the agency analytics tracking workspace: accounts, standalone posts, and posts discovered from tracked accounts. Replace by `id`, which equals `trackedMediaId`. Requires `X-Application-Id`, `X-Api-Key`, and `analytics:read`. Follow the [shared syncing workflow](/syncing/overview) for pagination, cursor storage, retries and removals. Only `cursor` and `limit` are accepted. ```bash theme={null} curl --get "$BASE_URL/sdk/v1/analytics/tracked-media/sync" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" \ --data-urlencode "limit=100" ``` On subsequent requests, add `--data-urlencode "cursor=$SAVED_CURSOR"`. ## Record format Each item in `data` is a complete replacement with these fields: ```json theme={null} { "id": "TRACKED_123", "trackedMediaId": "TRACKED_123", "sourceTrackedMediaId": "TRACKED_ACCOUNT_123", "platform": "TIKTOK", "mediaUrl": "https://www.tiktok.com/@jordan/video/7350000000000000000", "postId": "7350000000000000000", "isAccount": false, "authorUsername": "jordan", "authorDisplayName": "Jordan", "title": "Launch day", "captionText": "Our new campaign", "hashtags": [ "launch" ], "thumbnail": null, "uploadDate": "2026-10-25T10:00:00.000Z", "trackStartAt": "2026-10-25T00:00:00.000Z", "trackEndAt": "2027-10-25T00:00:00.000Z", "trackingTier": 1, "metricsCollectedAt": "2026-10-26T10:00:00.000Z", "views": "12500", "likes": "420", "comments": "38", "shares": "21", "bookmarks": "9" } ``` Counters are the latest stored observation for an individual post, serialized as **decimal integer strings** to preserve large values. Unavailable counters are null, including platform-unsupported metrics and posts without observations. `metricsCollectedAt` identifies that observation. Corrections and deletion of observations also produce replacements. Accounts have `isAccount: true` and null counters; their child posts carry `sourceTrackedMediaId`. Sum child post counters locally if you need account totals. Updates to a child emit that child's record. The feed does not duplicate post totals onto an account row or apply date-range calculations. This feed covers tracked workspace media only. [Campaign media](/campaign-media/sync) has its own feed. If you combine the two datasets, a social post may be present in both; deduplicate by canonical platform/post identity before calculating totals. Collections and combined analytics charts remain on the [analytics API](/analytics). Tracking-window boundaries are returned as stored dates. Merely crossing a boundary does not delete a record. Metadata, metrics, source-account rebinding, ownership changes and deletion produce replacements or removals. Routine scraper bookkeeping does not create a sync update. # Transactions Source: https://api-docs.usegrade.com/syncing/transactions Incrementally sync transactions with complete records, removals, and durable cursors. ## GET /sdk/v1/transactions/sync Sync the agency wallet ledger, including new entries and corrections to existing transaction status or amount. Replace by `id`, which equals `transactionId`. Requires `X-Application-Id`, `X-Api-Key`, and `payouts:read`. Follow the [shared syncing workflow](/syncing/overview) for pagination, cursor storage, retries and removals. Only `cursor` and `limit` are accepted. ```bash theme={null} curl --get "$BASE_URL/sdk/v1/transactions/sync" \ -H "X-Application-Id: $APP_ID" \ -H "X-Api-Key: $API_KEY" \ --data-urlencode "limit=100" ``` On subsequent requests, add `--data-urlencode "cursor=$SAVED_CURSOR"`. ## Record format Each item in `data` is a complete replacement with these fields: ```json theme={null} { "id": "TX_123", "transactionId": "TX_123", "transactionType": "WALLET_TO_WALLET", "transactionStatus": "COMPLETED", "amount": "-120.50", "currency": "USD", "invoiceId": "INV_123", "transactionTime": "2026-10-26T10:00:00.000Z" } ``` `amount` is the exact stored ledger amount in `currency`, serialized as a **decimal string**. Preserve its sign; debits are negative. Use decimal arithmetic. This is not a converted display total or the net bank/top-up amount shown by other views. `transactionStatus` retains the ledger's status enum. Internal admin adjustments and FX top-up fee revenue are excluded, consistently with the public transaction list. Processor payloads, payment credentials, internal metadata and source-of-funds details are never returned. Wallet ownership changes, removal, and records leaving this public ledger view produce removals. This feed covers stored ledger state; fulfillment and withdrawal state are available in the [payout feed](/syncing/payouts). # Timezones Source: https://api-docs.usegrade.com/timezones List the IANA timezone names accepted by campaign create and update endpoints. All endpoints below require: * `X-Application-Id` * `X-Api-Key` ## GET /sdk/v1/timezones List the IANA timezone names accepted in campaign `timeZone` fields. The response includes human-friendly names and labels so you can populate a timezone selector without maintaining a separate list. ### Response ```json theme={null} { "success": true, "data": [ { "name": "America/New_York", "displayName": "Eastern Time", "displayLabel": "Eastern Time — America/New_York" } ] } ``` **name** `string` The IANA timezone identifier. Send this exact value as `timeZone` when creating or updating a campaign. **displayName** `string` A human-friendly English timezone name. **displayLabel** `string` A ready-to-render label containing the friendly name and IANA identifier. > [!NOTE] > > Store and submit `name` as the campaign `timeZone`. `displayName` and > `displayLabel` are intended for customer-facing selectors. # Transactions Source: https://api-docs.usegrade.com/transactions List and export wallet transactions via /sdk/v1. All endpoints below require: * `X-Application-Id` * `X-Api-Key` ## GET /sdk/v1/transactions List agency wallet transactions. ### Query parameters * `page` (default `1`) * `limit` or `pageSize` (default `50`, max `100`) * `sortBy` (optional) * `sortOrder` (`asc|desc`, optional) * `transactionTypes` or `transactionType` (optional; comma-separated) * `transactionStatuses` or `transactionStatus` (optional; comma-separated) * `from` and `to` (optional; ISO timestamps) If `from`/`to` is provided without a timezone offset, it is treated as UTC. Supported `transactionTypes` values (invalid values are ignored): `TOP_UP`, `AGENCY_PAY_OUT`, `CREATOR_PAYMENT`, `TOP_UP_CREDIT` Supported `transactionStatuses` values (invalid values are ignored): `SUBMITTED`, `PENDING_VERIFICATION`, `PROCESSING`, `INSTANT_WALLET_TO_WALLET`, `PENDING_WALLET_TO_WALLET`, `DECLINED`, `COMPLETED` ### Response ```json theme={null} { "success": true, "data": [ { "transactionId": "txn_...", "transactionType": "TOP_UP", "transactionStatus": "COMPLETED", "transactionTime": "2026-02-19T00:00:00.000Z", "displayCurrency": "USD", "displayValue": 100, "feeDisplayValue": 0 } ], "pagination": { "page": 1, "pageSize": 50, "totalItems": 1, "totalPages": 1 } } ``` ## GET /sdk/v1/transactions/export Export wallet transactions as CSV or PDF. ### Query parameters * `format` (required): `csv` or `pdf` * `from` and `to` (required): ISO timestamps * All filters supported by `GET /sdk/v1/transactions` * `timeZone` (optional; used for PDF rendering) ### Responses * `text/csv` with `Content-Disposition: attachment; filename="wallet-transactions-YYYY-MM-DD.csv"` * `application/pdf` with `Content-Disposition: attachment; filename="wallet-transactions-YYYY-MM-DD.pdf"` If the export would exceed 10,000 rows: `413` with a JSON error. # Wallet Source: https://api-docs.usegrade.com/wallet Wallet balance and payout affordability checks via /sdk/v1. All endpoints below require: * `X-Application-Id` * `X-Api-Key` ## GET /sdk/v1/wallet/balance Get the agency wallet balance summary. ### Response ```json theme={null} { "success": true, "data": { "balanceValue": 1234.56, "spendValue": 789.01, "pendingValue": 50.0, "currency": "USD" } } ``` ## POST /sdk/v1/wallet/check-payout-balance Check whether the wallet can cover a payout (including platform fee and settlement rules). This endpoint returns a bare `{ sufficient: boolean }` object (no `success` wrapper). ### Body Uses the same payload rules as `POST /sdk/v1/payouts/trigger`, except `payoutRecipientEmail` is optional. If you include `platformFeePayerOverride` and, when needed, `platformFeeAgencySharePercent`, the affordability check uses that override when calculating the required wallet debit. ```json theme={null} { "payoutCurrency": "USD", "payoutAmount": "5.00", "platformFeePayerOverride": "AGENCY_PAYS_ALL" } ``` ### Response ```json theme={null} { "sufficient": true } ``` ### Common errors * `400`: invalid payload (currency not supported, >2 decimals, missing amount, etc.) * `401`: missing/invalid SDK headers * `403`: origin not allowed (when allowlist is configured and `Origin` is present) ## POST /sdk/v1/wallet/check-payout-balance-bulk Check whether the wallet can cover the total of up to 100 payouts. This endpoint returns a bare `{ sufficient: boolean }` object (no `success` wrapper). ### Body ```json theme={null} { "payouts": [ { "payoutCurrency": "USD", "payoutAmount": "5.00" }, { "payoutCurrency": "USD", "payoutAmount": "10.00", "platformFeePayerOverride": "CUSTOM_SPLIT", "platformFeeAgencySharePercent": 25 } ] } ``` ### Response ```json theme={null} { "sufficient": false } ```