# Glossary Source: https://docs.brew.new/analytics/glossary Plain definitions for the email marketing terms you'll meet across Brew, from authentication and deliverability to segments and suppression. Definitions for the terms you'll meet across Brew and email marketing generally. For the metrics themselves, with formulas and how each one is tracked, see [Key Metrics](/analytics/key-metrics-and-terms). > [accordion] Above the Fold > > The portion of your email that recipients can see without scrolling. Put your most important content and calls-to-action here, where they're visible right away. > [accordion] Automations > > Emails Brew sends in response to events: welcome flows, abandoned cart, re-engagement, and other marketing flows. Describe what you want and Brew builds the flow with the right timing and branching. [Learn about Automations](/create-emails/automations). > [accordion] Bounce Rate > > Defined with its formula and tracking detail in [Bounce Rate](/analytics/key-metrics-and-terms#bounce-rate). > [accordion] Call to Action (CTA) > > A button or link that prompts a specific action, such as "Download Now" or "Get Started." It's what turns a read into a conversion. Learn how Brew automatically optimizes CTAs in [Emails](/create-emails/emails). > [accordion] Campaigns > > One-time emails sent to many recipients at once, such as announcements, newsletters, promotions, and event invites. In Brew, you design the message in Emails, and sending it once is a campaign. [See how Emails, campaigns, and Automations fit together](/create-emails/emails-vs-automations). > [accordion] CAN-SPAM Act > > U.S. federal law that sets rules for commercial email, including requirements for unsubscribe links, sender identification, and truthful subject lines. Compliance is mandatory for U.S. senders. > > Brew adds the unsubscribe link and your mailing address to every marketing email. Consent and honest subject lines are still up to you. [Learn more about CAN-SPAM](https://www.ftc.gov/business-guidance/resources/can-spam-act-compliance-guide-business). > [accordion] Click-Through Rate (CTR) > > Most tools mean clicks divided by delivered emails, which Brew calls [click rate](/analytics/key-metrics-and-terms#click-rate). In Brew's automation analytics, `clickThroughRate` is clicks divided by opens: see [Click-to-Open Rate](/analytics/key-metrics-and-terms#click-to-open-rate). > [accordion] Complaint Rate > > Defined with its formula and tracking detail in [Complaint Rate](/analytics/key-metrics-and-terms#complaint-rate). > [accordion] Contact Properties > > Data fields associated with each contact in your audience, such as firstName, lastName, company, or custom fields. Used for personalization through [merge tags](#merge-tags) and audience segmentation in Brew. [Learn how to add and manage Contact Properties](/audience/manage-contacts#contact-properties). > [accordion] Conversion Rate > > Defined with its formula and tracking detail in [Conversion Rate](/analytics/key-metrics-and-terms#conversion-rate). > [accordion] Deliverability > > Your ability to successfully deliver emails to recipients' inboxes rather than spam folders. Affected by [sender reputation](#sender-reputation), content, and authentication. Brew optimizes deliverability through proper [domain verification](/get-started/verify-your-sending-domain). > > To protect it, keep your list clean. See [Audience hygiene](/audience/audience-hygiene). > [accordion] DKIM > > DomainKeys Identified Mail: an email authentication method that verifies your emails haven't been tampered with during transit. Helps improve deliverability. Set up DKIM through [domain verification](/get-started/verify-your-sending-domain). > [accordion] DMARC > > Domain-based Message Authentication, Reporting & Conformance: an email security protocol that prevents domain spoofing and improves deliverability when properly configured. Configure DMARC as part of [domain verification](/get-started/verify-your-sending-domain). > [accordion] Email Service Provider (ESP) > > The industry term for a platform that provides email marketing and delivery services, including analytics, automation, and deliverability optimization. Brew is the AI-native email platform for modern teams and AI agents. In these docs, "ESP" mostly means a platform you're exporting to or migrating from. > [accordion] Hard Bounce > > An email that permanently fails to deliver due to invalid email addresses, non-existent domains, or blocked recipients. These contacts are automatically suppressed by Brew to protect your sender reputation. > > **Common causes of hard bounces include:** > > * Email address contains a typo (for example, [example@gmial.com](mailto:example@gmial.com)) > * Email address doesn't exist (perhaps the person left the company) > * Email server has permanently blocked delivery > * Domain no longer exists > > When an email hard bounces, Brew marks the contact suppressed and unsubscribed (see [suppression list](#suppression-list)). That prevents future sending attempts and protects your deliverability. To see why an address bounced, open that bounce in **Events** in [analytics](/analytics/reading-analytics); the event detail shows the reason. > > **Tips to reduce hard bounces:** > > * Regularly clean your email list with [audience hygiene practices](/audience/audience-hygiene) > * Check for common typos in email domains (like gmail.com, outlook.com) > [accordion] List Hygiene > > The practice of removing inactive subscribers, invalid addresses, and unengaged contacts from > your list to protect deliverability and metrics. [Learn about audience hygiene best practices](/audience/audience-hygiene). > [accordion] List Segmentation > > Dividing your list into smaller, targeted groups based on demographics, behavior, or > preferences, so sends stay relevant. In Brew, create targeted [audiences](/audience/create-audiences) for precise segmentation. > [accordion] Merge Tags > > Variables that insert dynamic content like contact names, company names, or custom properties into your emails. Add them with the variable picker or ask for them in a prompt. They read [contact properties](/audience/manage-contacts#contact-properties) and trigger data; [Merge Tags](/create-emails/merge-tags) owns the syntax. > [accordion] Open Rate > > Defined with its formula and tracking detail in [Open Rate](/analytics/key-metrics-and-terms#open-rate). > [accordion] Personalization > > Customizing email content for individual recipients using data like names, locations, or past behavior. In Brew, you personalize with [merge tags](#merge-tags) that read [contact properties](/audience/manage-contacts#contact-properties). > [accordion] Preference Center > > A branded page where subscribers can manage their email preferences, including opting out of marketing emails. Brew doesn't have one. > > Each marketing domain keeps its own unsubscribe list instead. The unsubscribe link opts out of the sending domain's marketing, and **Unsubscribe from all** opts out of every marketing email from the brand. See [Unsubscribes](/brand/unsubscribe#two-ways-to-opt-out). > [accordion] Preview Text > > The snippet of text that appears after the subject line in most email clients. Often called "preheader text," it provides additional context to encourage opens. Brew automatically optimizes preview text for each email. > [accordion] Send > > A single delivery of an email design, the unit Brew measures and attributes analytics against. An [email](/create-emails/emails) produces one send scoped to the audience you picked; an [automation](/create-emails/automations) produces one send per recipient. Every delivery event (open, click, bounce) attaches to the send that produced it. > > Each metric traces back to the exact send and design a recipient received. Email and automation sends share the same [analytics view](/analytics/reading-analytics). > [accordion] Sender Reputation > > A score assigned by internet service providers based on your sending history, bounce rates, complaint rates, and engagement. It largely decides whether you reach the inbox. Maintain good reputation through proper [domain verification](/get-started/verify-your-sending-domain) and [audience hygiene](/audience/audience-hygiene). > [accordion] Skipped > > An event recorded when Brew decides not to send to a contact, most commonly because they unsubscribed or are [suppressed](#suppression-list). Skips are logged in the [analytics view](/analytics/reading-analytics) with the reason. You can > see exactly who was excluded from a send and why. > [accordion] SPF Record > > Sender Policy Framework: a DNS record that specifies which servers are authorized to send email on behalf of your domain. It's part of email authentication. Set up SPF records through [domain verification](/get-started/verify-your-sending-domain). > [accordion] Split Testing (A/B Testing) > > Testing versions of an email element (subject lines, content, CTAs) against different audience > segments to see what performs better. In a Brew automation, a Split step in percentage mode sends a set share of > contacts down each path. Compare the two versions in analytics. See [A/B Test Two Subject Lines](/recipes/ab-test-subject-lines). > [accordion] Subject Line > > The title of your email that appears in recipients' inboxes. One of the most important factors influencing whether your email gets opened. Brew automatically generates optimized subject lines for all [emails](/create-emails/emails) and [automations](/create-emails/automations). > [accordion] Suppression List > > Addresses blocked from receiving your emails, such as hard bounces. In Brew, suppression is a flag on the contact (`suppressed`, with a `suppressedReason`). Deleting the contact doesn't clear it: Brew keeps the restriction ([Manage Contacts](/audience/manage-contacts#deleting-contacts)). > > **Why Brew maintains a suppression list:** > > * **Protects your sender reputation**: Continuing to send to invalid addresses or complainants damages your domain reputation > * **Improves deliverability**: Email providers track how often you attempt to send to invalid addresses > > **Common reasons email addresses are suppressed:** > > * **Hard bounces**: The email address doesn't exist, contains a typo, or the server has permanently blocked delivery > * **Provider blocks**: The sending provider refused an address it had already blocked > > Unsubscribes are separate. An unsubscribed contact still gets transactional email, while a suppressed address gets nothing ([Unsubscribes](/brand/unsubscribe)). > > Brew automatically handles suppression list management, so you don't need to manually remove these addresses. You can view suppressed addresses in your Audience section and see the specific reason they were suppressed. > [accordion] Transactional Email > > Automated emails triggered by specific user actions containing essential information, such as password resets, order confirmations, or account notifications. They are sent regardless of subscription status. In Brew, a transactional email is an automation whose trigger you fire, sending from a transactional-purpose domain. [Learn more](/create-emails/transactional-email). > [accordion] Trigger > > The starting condition that determines when and how contacts enter an automation. Brew supports custom events (like `user_signup` or `order_placed`) that you create on the > **Triggers** page, under **Automations**. Built-in events come from connected sources like Stripe. Unsubscribe events are started by Brew itself when a contact unsubscribes. [Learn about Automation Triggers](/create-emails/automation-triggers). > [accordion] Unsubscribe Rate > > Defined with its formula and tracking detail in [Unsubscribe Rate](/analytics/key-metrics-and-terms#unsubscribe-rate). > [accordion] UTM Parameters > > Tags added to email links that help track traffic sources and campaign performance in analytics platforms like Google Analytics. Use UTM parameters to measure the business impact of your email campaigns beyond basic [open and click rate](/analytics/key-metrics-and-terms) metrics. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Brew Insights Source: https://docs.brew.new/analytics/insights Brew Insights checks your email and lists what needs attention and what to try next, most severe first, with the numbers behind each finding. Brew Insights checks your email for you and lists what it finds, most severe first. Each finding shows the numbers behind it, how Brew detected it, and what would resolve it. Many come with a button that fixes the problem or hands it to Brew. Insights covers deliverability problems, campaigns that did better or worse than usual, and timing, audience, and automation opportunities. It is scoped to your active brand. ## Open Insights Click a **Brew Insights** card on **Home**, or go to [brew.new/insights](https://brew.new/insights). The page, **What Brew noticed**, has three parts: * **Last 7 days.** Delivered, unique opens, unique clicks, and unsubscribes for the last 7 days against the 7 before. * **The counts.** How many findings are under **Needs attention** and how many under **Opportunities**. * **The findings.** The list itself, with **Open** and **All** tabs. Until the first analysis finishes, the page says it is waiting for one and the counts read zero. ### Reading the Last 7 Days The 7-day window ends at the start of today, so a day still in progress never skews it. An arrow up or down appears only when the change is statistically real. Small moves show as steady. With too few deliveries to compare rates, Brew shows the counts only. If engagement tracking is off, opens show as unknown. ## Turn On Automatic Checks Automatic checks are off by default, so Brew analyzes your account only when you ask. Turn them on to keep the page current. **1. Open the settings** On the Insights page, click the **Insight settings** gear. **2. Pick how often Brew checks** Choose a cadence under **Automatic checks**: | Option | When to use it | | - | - | | **Off** | Run analysis only when you ask. This is the default. | | **Once a day** | Active sending programs. | | **Every 3 days** | A quieter check-in. | | **Once a week** | Lower-volume programs. | Any cadence also turns on checks after important account events, such as a send finishing. **3. Choose who hears about changes** Turn on **Email org members** to send each member of your organization a private summary. It goes out only when findings materially change. **Next check** shows when the next automatic check is due. **Run now** checks right away, in a new Brew chat. Brew's assistant reads your past findings, runs a fresh check, and tells you what is new, changed, or recovered. It doesn't act on a suggestion unless you confirm. Running a check by hand uses credits. See [What a Run Costs](#what-a-run-costs). ## Read a Finding Each finding has a headline, a severity, and the numbers it was computed on. Those numbers are frozen when the finding runs, so they stay the same even as new data arrives. Quote them as they are. ### Severity The list is ranked by severity, then by score within each level: 1. **Critical** 2. **Warning** 3. **Opportunity** 4. **Info** For example, a send whose bounce rate is high enough for mailbox providers to act on shows as Critical. ### What Else a Finding Shows * **Evidence.** The facts behind it, with links where Brew has them. * **How it was detected.** What Brew looks for, how it measures it, and what it compares against, such as your own history or a fixed limit. * **What resolves it.** The condition that closes it, such as a later send of the same email staying under the limit. * **Confidence.** High, medium, or low. * **Type.** What happened, a change that passed a statistical test, or a recommended next step. * **History.** When Brew first and last saw it, and how often it has closed and come back. ## Act on a Finding Many findings carry a button. It does one of two things: * **Opens the page that fixes it.** For example, a bounce finding can open that email's analytics. * **Hands the job to Brew.** Brew's assistant starts on a request for you: review your domain health, validate contacts, create or repeat an email, or review a recommendation. Snooze a finding you plan to deal with later, or dismiss one you've handled or don't need. A snoozed finding comes back to **Open** when its snooze ends. ### Open and All **Open** lists active findings, including snoozes that have ended. **All** adds findings that are resolved, cleared, dismissed, or stale, and snoozes still in effect. A finding moves to **Resolved** on its own once the condition that raised it goes away. ## Deep Analysis, Reports, and Suggestions Click **Run deep analysis** for a deeper review. Like **Run now**, it opens a new Brew chat with the same assistant, but asks for more. Brew starts from the account memory and current findings, then looks at performance, trends, audiences, content, list health, and deliverability. It publishes an intelligence report: a set of observations about performance, audience, trends, risks, content, and setup, each with its likely impact. It doesn't act on any suggestion during the run. A report can propose **suggestions**: concrete next steps for an audience, an email, an automation, deliverability, or your schedule. Launching one opens a new Brew chat that asks Brew to do exactly what it describes. The request goes out right away and uses credits. Suggestions you launch are marked as launched. Brew keeps an **account memory** across runs, so each analysis builds on what it learned before. Open it from the settings with **View account memory**. ## What a Run Costs **Run now**, **Run deep analysis**, and launching a suggestion each start a Brew chat, and chat work uses AI credits. Like other agent work, each bills the tokens it uses, so there is no fixed price. **Run now** and **Run deep analysis** send no email, so they don't count toward your monthly email sends. Reading findings is free, in the app, over MCP, or through the API. For how credits are billed, see [API Credits](/api-reference/api/credits). ## How Current the Findings Are Brew keeps up to 200 findings in view, and each run records how current its data is. If the latest run failed, the findings may be out of date until the next one succeeds. Run one by hand with **Run now** or **Run deep analysis**; both use credits. ## From an Agent or Code Agents and code read the same findings. Over MCP, `list_insights` lists them as the page ranks them, and `list_insights` with an `insightId` from a row reads that one finding in full. `list_insights` can also return the weekly numbers, the latest report, its suggestions, and the account memory. From code, `GET /v1/insights` and `GET /v1/insights/{insightId}` do the same. Both reads are free. They never start a run; **Run now** in the app refreshes the findings and uses credits. [Read Brew Insights](/api-reference/guides/read-brew-insights) covers the API in full. ## Related * [Reading Analytics](/analytics/reading-analytics) for the numbers behind each send * [Key Metrics](/analytics/key-metrics-and-terms) for what each rate means * [Domains](/domains/domains) for your domain's deliverability score * [Audience Hygiene](/audience/audience-hygiene) for keeping bounce and complaint rates down * [Weekly Analytics Review](/recipes/weekly-analytics-review) for a weekly routine that starts on this page ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Key Metrics Source: https://docs.brew.new/analytics/key-metrics-and-terms Every metric in Brew analytics with its formula and how it's tracked, covering open, click, conversion, bounce, complaint, and unsubscribe rate. Every metric you'll see in [Reading analytics](/analytics/reading-analytics), with its formula and how Brew tracks it. For the wider vocabulary, see the [Glossary](/analytics/glossary). > [!NOTE] > > This page uses "campaign" in its general email-marketing sense, the way the metrics themselves are defined across the industry. In Brew, a campaign is one send of an Email to an audience. See [Where You'll See Campaign](/create-emails/emails-vs-automations#where-youll-see-campaign). ## Core Engagement Metrics ### Open Rate Open rate measures the percentage of delivered emails that recipients opened. $Open\ Rate = \frac{Number\ of\ emails\ opened}{Number\ of\ emails\ delivered} \times 100$ > [accordion] How open rates are tracked > > When you send an email through Brew, here's exactly how opens are measured: > > 1. **Tracking pixel insertion**: A 1×1 pixel transparent GIF image is automatically embedded in each email you send. This invisible pixel contains a unique identifier linked to both the specific email and the recipient. > 2. **Email delivery**: Your email is delivered to the recipient's inbox with this tracking pixel included. > 3. **Image loading**: When a recipient opens your email and their email client loads images, it requests this pixel from Brew's servers. > 4. **Open registration**: This server request registers as an "open" in Brew's analytics system, recording who opened the email and when it happened. > 5. **Data processing**: Brew counts each recipient once, and leaves out machine opens it can detect, such as Apple Mail Privacy Protection prefetches. Opened and clicked numbers are unique human recipients, the same in the app, over MCP, and on the API. > [accordion] Why open rate matters > > Open rate shows whether your subject line and preview text earn the click. It's also shaped by sender reputation and the recipient's past experience with your brand. > [accordion] Benchmarks > > Average open rates vary by industry, but generally: > > * 15% to 25% is considered average > * Above 25% is good > * Above 35% is excellent > [accordion] Limitations to consider > > **Open rates have become increasingly unreliable** due to privacy protections and technical limitations: > > * **Apple Mail Privacy Protection** (iOS 15+): Automatically pre-loads tracking pixels whether the email is read or not. Brew excludes the machine opens it can detect, but no filter catches every one. > * **Corporate email security**: Many companies use firewalls that cache or block tracking pixels. > * **Email client defaults**: Some clients block image loading by default, preventing open detection entirely. > > Focus more heavily on click rates and conversions as more reliable engagement indicators. ### Click Rate Click rate is the share of delivered emails that got at least one link click. The API returns it as `clickRate`. $Click\ Rate = \frac{Number\ of\ unique\ clicks}{Number\ of\ emails\ delivered} \times 100$ Click rate reflects how engaging and relevant your email content is, and how compelling your calls-to-action are. Strong CTAs with clear value propositions, appealing design, and strategic placement drive higher click rates. > [accordion] How clicks are tracked > > Brew tracks clicks through a process called link rewriting: > > 1. **Link modification**: When you create an email, Brew automatically rewrites all links to route through our tracking servers before redirecting to the final destination. > 2. **Unique identifiers**: Each rewritten link contains parameters that identify both the email campaign and the specific recipient. > 3. **Click registration**: When a recipient clicks any link, they first connect to Brew's tracking system, which records the click event along with relevant data (which link, which recipient, timestamp). > 4. **Instant redirect**: After registering the click, the recipient is immediately redirected to the intended destination URL. This happens so quickly that recipients don't notice any delay. > 5. **Reporting**: Brew aggregates this click data to calculate metrics like click rate and identifies which specific links received the most engagement. > [accordion] Why click rate matters > > Clicks represent the next level of engagement beyond opens. They indicate that your message was compelling enough for recipients to take action. > > Across industries, a 2% to 5% click rate is common for email campaigns, with around 2.3% being the average. ### Click-to-Open Rate Click-to-open rate is the share of opened emails that got a click. It shows how well the content worked for people who actually read it, separate from how many opened. $Click\text{-}to\text{-}Open\ Rate = \frac{Number\ of\ unique\ clicks}{Number\ of\ unique\ opens} \times 100$ In automation analytics, the API names this `clickThroughRate`. For example, 210 clicks from 690 opens is 30.4%, while the same 210 clicks over 1,150 delivered is an 18.3% click rate. ### Conversion Rate Conversion rate measures the percentage of recipients who completed your desired action after receiving your email. $Conversion\ Rate = \frac{Number\ of\ people\ who\ completed\ the\ desired\ action}{Number\ of\ emails\ delivered} \times 100$ > [!NOTE] > > Unlike opens and clicks, conversions are tracked in your own analytics platform, not in Brew. Set one up, like Google Analytics, to measure these outcomes. > [accordion] Why conversion rate matters > > Conversion rate matters because it measures the business impact of your email campaigns. While opens and clicks are important engagement metrics, conversions represent actual business outcomes. > [accordion] Tracking conversions > > To track conversions, you'll need to: > > 1. Define the specific action that constitutes a conversion for each campaign > 2. Add UTM parameters to your email links > 3. Connect your analytics platform (like Google Analytics) to track these actions > 4. Set up goals or events in your analytics platform to measure completion ## Deliverability Metrics ### Delivery Rate The delivery rate is the percentage of sent emails that the recipient's mail server accepted. $Delivery\ Rate = \frac{Number\ of\ emails\ delivered}{Number\ of\ emails\ sent} \times 100$ For example, 4,920 delivered out of 5,000 sent is a 98.4% delivery rate. Over the API, the analytics overview returns it as `deliveryRate`. ### Bounce Rate Bounce rate measures the percentage of emails that could not be delivered. $Bounce\ Rate = \frac{Number\ of\ bounced\ emails}{Number\ of\ emails\ sent} \times 100$ Sent includes mail the provider blocked before delivery, reported as `providerSuppressed`. That mail is neither bounced nor delivered, so it lowers the bounce rate. Bounce rate primarily reflects the quality and hygiene of your contact list. High bounce rates usually mean your list has outdated or bad addresses, not a problem with your content or sending practices. > [accordion] How bounces are tracked > > Brew tracks bounces through automated feedback from email servers: > > 1. **Delivery attempt**: When your email is sent, it goes through multiple servers before reaching its destination. > 2. **Bounce detection**: If a receiving mail server cannot deliver the message, it sends back an automated response (an SMTP error) with a specific reason code. > 3. **Recording**: The bounce is logged in your campaign metrics along with the specific reason for the failure. > 4. **Automated handling**: Brew suppresses the bounced address to prevent future sending attempts, protecting your sender reputation. > [!WARNING] > > A [gradual send](/create-emails/send-options#gradual-send) doesn't pause on its own when bounces rise, so pause it yourself if they climb. [What You Can Send](/get-started/what-you-can-send#what-brew-monitors) states the limits to stay under; [audience hygiene](/audience/audience-hygiene) is what keeps the rate down. ### Unsubscribe Rate Unsubscribe rate measures the percentage of recipients who opted out of future emails. $Unsubscribe\ Rate = \frac{Number\ of\ unsubscribes}{Number\ of\ emails\ delivered} \times 100$ > [accordion] Why unsubscribe rate matters > > Unsubscribe rate indicates whether your audience finds your content valuable and relevant to their needs. High unsubscribe rates suggest your content isn't matching what recipients expected when they signed up. > [accordion] Benchmarks > > Most email experts consider an unsubscribe rate below 0.5% to be normal. > [accordion] How unsubscribes are tracked > > Every marketing email carries a signed, per-recipient unsubscribe link. Clicking it lands on your branded unsubscribe page, or one-click unsubscribes from Gmail and Apple Mail. The address goes on the sending domain's unsubscribe list, and **Unsubscribe from all** suppresses it from every marketing send. [Unsubscribes](/brand/unsubscribe#how-it-works) owns the full path. > [!NOTE] > > Brew automatically handles the entire unsubscribe process for you. Unsubscribed contacts are skipped for Emails and Automations, in line with [CAN-SPAM regulations](https://www.ftc.gov/business-guidance/resources/can-spam-act-compliance-guide-business), which distinguish between marketing and transactional communications. [Transactional email](/create-emails/transactional-email), an automation sending from a transactional-purpose domain, still reaches unsubscribed contacts because it carries essential information. ### Complaint Rate The complaint rate is the percentage of delivered emails that recipients marked as "Spam" or "Junk". $Complaint\ Rate = \frac{Number\ of\ spam\ complaints}{Number\ of\ emails\ delivered} \times 100$ > [accordion] How complaints are tracked > > Complaints are tracked through a standardized system called Feedback Loops (FBLs): > > 1. **Recipient action**: A recipient clicks the "Mark as Spam" or "Report Spam" button in their email client. > 2. **ESP notification**: The receiving email service provider (like Gmail, Yahoo, or Outlook) captures this action and sends a standardized report through a Feedback Loop. > 3. **Complaint processing**: Brew receives these FBL reports and associates them with the specific email campaign and recipient. > 4. **Metric calculation**: Brew aggregates these complaints to calculate your complaint rate. > [!WARNING] > > A complaint is someone hitting "report spam" in a mailbox like Gmail. It's different from a bounce, an address that could not be delivered to at all. > > Brew tracks the rate on every send, and a domain's health read flags a high one. Keep it under Brew's ceiling, which sits below the 0.1% Gmail and Yahoo recommend ([What You Can Send](/get-started/what-you-can-send#what-brew-monitors) states it). Sending relevant content to engaged contacts keeps the rate low. ## Automation-Specific Metrics > [!NOTE] > > Runs, Completed, and Failed describe automation runs, not individual emails. They live with the automation itself rather than in the [analytics view](/analytics/reading-analytics). The analytics view logs the send and engagement events those runs produce. > [accordion] Runs > > * **What it means**: the number of contacts who entered the flow when the trigger fired > * **When it increments**: the moment a trigger event fires for a matching contact > [accordion] Completed > > * **What it means**: contacts who completed every step in the flow, including all Wait nodes > * **Why it lags Runs**: a flow with Wait nodes takes days or weeks to complete, so low Completed vs Runs is normal if the flow launched recently > * **Over the API**: `successRate` is Completed divided by Runs > [accordion] Failed > > * **What it means**: contacts whose run stopped mid-flow due to an error > * **Common causes**: hard bounce, missing required payload field, filter that couldn't evaluate > * **What to do**: open the automation's run history and click into the failed run to see the specific error, or click any of its events in analytics and use **View run** # Reading Analytics Source: https://docs.brew.new/analytics/reading-analytics Analytics opens as a list of your campaign sends and live Automations, with click-through detail pages and an Events log behind every number. Analytics has three layers, scoped to your active brand: 1. **The home page.** A list of everything you've sent, with its headline numbers. 2. **Detail pages.** Click any row for that item's own page. 3. **Events.** The log of every individual open, click, and bounce, behind every number on the other two layers. From an agent, `get_email_analytics` over [MCP](/api-reference/mcp/tools) reads the same numbers. Set `report.kind` to `overview` for totals, `sends` for each send and its lifetime stats, or `events` for the event log. `list_automations` or `get_automation` with `analytics: {}` covers Automation rows, and [`/v1/analytics`](/api-reference/api/api-introduction) serves the numbers to code. The API's default windows differ from the app's. The overview reads the last 7 days, and automation analytics the last 30. Pass `from` and `to` to match the range you see in the app. Overview totals also count mail Brew skipped before sending (`preSendSkipped`) and mail skipped at your plan's send limit (`quotaSkipped`). How the overview counts: * **Opened** counts each recipient once per send, dated by their first open. A later re-open adds nothing. * **Delivered** leaves out mail that bounced right after the provider accepted it. * **Sent** includes mail the provider blocked before delivery. See [Bounce Rate](/analytics/key-metrics-and-terms#bounce-rate). * **Automation performance** lists published automations only. The overview and its sources also count sends from unpublished and deleted automations, so their totals can be higher. ## Two Kinds of Rows Everything in analytics is one of two things. The names come from the tabs at the top of the page: | | **Campaign** | **Automation** | | - | - | - | | What it is | A one-time send to an audience you chose | A live flow that fires per contact when its trigger matches | | Covers | [Campaigns](/create-emails/emails-vs-automations) sent from Emails, and [manual-audience runs](/create-emails/automation-triggers#manual-audience) | Event-triggered [Automations](/create-emails/automations) | | Runs | Once, then it's complete | Continuously, while Live | | Stats shown | Lifetime | Last 14 days | In Brew, an Email is the design and [a campaign](/create-emails/emails-vs-automations) is one send of it. The tab covers both one-time shapes: a campaign and a manual-audience run each deliver once to a chosen audience. Their analytics read the same way. That also means a manual-audience automation appears under **Campaign**, not Automation, even though you built it in the automations builder. What you're looking at is its one-time run. ## The Analytics Home The top of the page is the year at a glance. Sent, opened, and clicked totals with their rates cover the last 365 days, above a calendar heatmap of daily activity. A summary line counts your campaign sends and live Automations. Below that, the list: | Every row shows | Campaign rows add | Automation rows add | | - | - | - | | A 14-day trend sparkline | The subject line and recipients | The flow and its trigger | | Who created it, and when | Dispatch and status | Live status | | Sent, opened, clicked | Lifetime totals | Last-14-days totals | A live Automation with no recent matches shows **Awaiting activity** instead of a trend. That's your quickest signal a trigger has gone quiet. Two controls narrow the list: * **All / Campaign / Automation.** The two kinds, or both together. * **The person filter.** Only rows created by one teammate, or over the API. ## Campaign Detail Click a Campaign row for its page: * **Sending identity.** Domain, from name and address, reply-to, and preview text. * **All time.** Delivered, opened, and clicked with rates, charted over time. * **The dispatch record.** How it went out (immediate, scheduled, or gradual), when it started, whether tracking was on, and its status. * **Recent events.** The latest opens and clicks inline, with **View all** jumping to the full log. * **The email itself.** Rendered alongside, so the numbers and the design that earned them share one screen. ## Automation Detail Click an Automation row for its page: * **The header.** Trigger and source, Live status, contacts active in the flow right now, and step count. * **Whole-flow stats.** Delivered, opened, and clicked across the automation, charted over time. * **Email steps.** Every email in the flow, in order, each with its own sent, opened, and clicked, plus unsubscribes where they happened. Select steps to focus the metrics. * **The flow diagram.** Alongside the numbers. Run history (entered, completed, failed mid-flow) lives with the automation itself. Email steps is the section to read closely. It's how you find the step where a sequence loses people. A welcome email opening at 44% followed by a step at 31% tells you exactly where to look. ## The Events Page The pulse icon in the header of any detail page opens **Events** filtered to that item. "Which specific people opened this?" is one click from any number. Events is also where every email event across the brand lands, one row per thing that happened. The top of the page shows a tile per event type: delivered, opened, clicked, bounced, unsubscribed, and skipped. A chart of event volume over time sits below, color-coded to match. Skipped events carry the reason, such as unsubscribed or suppressed. The window controls in the top right set the range for the whole page: * **Live.** Streams events as they happen. Use it to watch an in-progress send land. * **24h / 30d / 90d.** Fixed windows. * **Custom.** Pick any date range. For full metric definitions, see [Key Metrics and Terms](/analytics/key-metrics-and-terms). ## The Event Log | Column | What it means | | - | - | | **Time** | When the event occurred | | **Event** | The event type, plus a reason badge where it applies | | **Source** | What caused it: a one-off Email, an integration trigger, an API call, or a manual run | | **Recipient** | The contact the event belongs to | | **Email** | The email or Automation the event came from, with its audience | There are two ways to narrow the log: * **Filters.** The chip row above the log filters by Automations, Emails, Email address, and Audience. Active filters show as highlighted chips you can remove individually, or clear all at once with **Reset filters**. * **Ask Brew.** The search bar above the filters takes plain language. Describe what you're looking for, like *"welcome emails that bounced this week"*, and Brew translates it into the matching filters. ## Event Details Click any row for the full story of that event: * **The email itself.** A rendered preview of what the recipient received, with a link to open it. * **Where it came from.** The email or Automation that produced it, the From address, and a **View run** link that jumps to the automation run behind it. * **Filter by.** One-click chips for the recipient, event type, email, automation, or audience. Each one pivots the log to everything matching, so you can go from one bounce to every event for that contact in a click. * **Related events.** Sent, Delivered, Opened, and Clicked counts for that recipient and send, with a timeline underneath. Unique events are marked, and repeats are counted, so a recipient who clicked twice shows one unique click and two total. * **Details, metadata, and debug payload.** The recipient and From address with copy buttons, plus collapsible Metadata and Debug Payload sections. For trigger-driven sends, the payload is the actual event data the integration delivered, which makes this the fastest way to debug a trigger. ![The event detail panel: rendered email, filter-by chips, and related events with a timeline](https://0edx89zhjrasqnjf.public.blob.vercel-storage.com/docs/unified-analytics-event-detail.webp) ### Clicks Get Two Extras For click events, the detail panel also shows: * **Activity.** The exact link the recipient clicked. * **Location.** A map of where the click happened, down to city and country. Geographic data is available on click events only. ## Where the Numbers Come From Underneath both kinds of rows sits one record: the [send](/analytics/glossary), a single delivery of a design. * A **Campaign** row wraps one send covering its whole blast. * An **Automation** produces one send per recipient, each fired at its own moment. [One Design, Many Sends](/create-emails/emails-vs-automations#one-design-many-sends) explains why. * Each send accumulates **events** as it moves through the pipeline (sent → delivered → opened → clicked, plus bounces, complaints, and unsubscribes). Every event attaches to the send that produced it, so an open always traces back to the exact send and design the recipient received. * Totals roll up from those events: lifetime on Campaign rows, the last 14 days on Automation rows, and whatever window you pick on Events. This is why the two kinds read the same way. They're the same underlying records, tagged by what created them. ## Asking Brew for Analysis Beyond the search bar, you can ask Brew about your analytics from chat. *"Which email had the highest CTR last month?"* / *"Show me everyone who clicked but didn't open in the welcome flow."* Brew has access to your analytics data and can return summaries, comparisons, or contact-level details. Brew also looks on its own. [Brew Insights](/analytics/insights) ranks what it finds, most severe first: deliverability problems, campaigns that did better or worse than usual, and timing, audience, and automation opportunities. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # API Catalog Source: https://docs.brew.new/api-reference/api/api-catalog Run any of Brew's eleven API capabilities live against your brand from the dashboard, then copy the exact request as code or as a prompt for your agent. ## Overview The **API** tab in the Brew dashboard is a live catalog of the capabilities you can call from your own product. Open it at [brew.new/api](https://brew.new/api). Each entry runs against your real brand with a real API key, so what you see in the catalog is exactly what your code will get back. Once a call does what you want, copy it out in the shape you need: a raw request, a snippet in your language, or a prompt you paste into an AI agent. Use it to: * Try a capability before writing any code, with your brand's own designs and contacts. * Get a working request with your parameters already filled in. * Hand an agent (Claude, Cursor, whatever you use) a briefed prompt with the endpoint, auth pattern, request fields, and docs link. ## What's in the Catalog The catalog covers the eleven capabilities that make sense to run interactively: generation, media, and pre-send checks. It is not the whole API. Sending, automations, triggers, analytics, and contact and audience management are all on the v1 surface but not in the catalog, since a one-click run of a live send is not something you want in a browser tab. For those, see the [API Introduction](/api-reference/api/api-introduction). Eleven APIs across three groups. The cost shown on each row is the same metering the API applies: **usage-based** ops charge actual model usage, **fixed** ops charge a flat published cost, and free ops charge nothing. See [Credits](/api-reference/api/credits) for how metering works. ### Create Generate and edit on-brand email designs. | API | What it does | Endpoint | Cost | | - | - | - | - | | Generate Email | Create a new on-brand email design from a plain-language prompt. | `POST /v1/emails` | Usage-based | | Edit Email | Revise an existing email design with a plain-language instruction. | `PATCH /v1/emails/{emailId}` | Usage-based | | Figma to Email | Turn a Figma frame into a pixel-faithful, sendable email design. | `POST /v1/emails/figma` | Free | ### Media Production-ready email imagery: render, animate, compress, resize. | API | What it does | Endpoint | Cost | | - | - | - | - | | HTML to PNG | Render any HTML string to a hosted PNG image. | `POST /v1/content/html-to-png` | 1 credit | | Image to GIF | Animate a still image into a looping GIF. | `POST /v1/content/gif` | 20 from a prompt, 10 from an image or video | | Optimize Image | Compress a hosted image for email without changing its size. | `POST /v1/content/transform` (`operation: "optimize"`) | 1 credit | | Resize Image | Resize a hosted image to exact pixel dimensions. | `POST /v1/content/transform` (`operation: "resize"`) | 2 credits | ### Quality Pre-send checks for content, recipients, rendering, and placement. | API | What it does | Endpoint | Cost | | - | - | - | - | | Validate Contacts | Check which email addresses are safe to send to. | `POST /v1/contacts/validate` | 2 credits per address | | Email Audit | Check HTML, React Email JSX, or a saved design: links, images, loaded size, compliance, client support, accessibility, subject, and preview text. | `POST /v1/emails/audit` | 5 credits when complete, free when partial | | Email Inbox Preview | Screenshot your email in real clients: Gmail, Outlook, Apple Mail. | `POST /v1/emails/{emailId}/client-previews` | 10 credits | | Inbox Placement | Find out where your email actually lands: inbox, promotions, or spam. | `POST /v1/emails/{emailId}/inbox-placement-tests` | 10 credits | > [!NOTE] > > The costs above are what the catalog displays today. The authoritative > number for any given call is the `X-Credit-Cost` response header, and > the full machine-readable table is at `GET /v1/help` → > `credits.operations`. ## Running an API Click any row to open its detail view. The layout is the same for every API: ![The Generate Email detail view: prompt field and run button on the left, Parameters rail on the right, API request snippet and implementation prompt below](https://0edx89zhjrasqnjf.public.blob.vercel-storage.com/docs/api_catalog_generate_email.webp) **1. Fill in the required input** The main input sits at the top, marked with a red asterisk. On **Generate Email** that's the prompt: *"A product-launch email for our new espresso grinder, lead with the hero shot, two feature blocks, one CTA to pre-order."* **2. Adjust the optional parameters** The **Parameters** rail on the right holds everything optional. Each field maps one-to-one to a field in the request body, and editing one rewrites the request snippet below in real time. **3. Run it** Hit the run button. The result appears under the input, and the **Latest** / **History** tabs let you flip between this run and previous ones. **4. Copy the call out** Take the **API request** snippet in your language of choice, or the **Implementation prompt** if you want an agent to write the integration. A run from the catalog is a real API call. It charges credits and, for write operations, saves to your brand exactly as a call from your backend would. ### Parameters The Parameters rail is per-API. On **Generate Email** it holds three: | Parameter | Request field | What it does | | - | - | - | | Category | `category` | Tailors the design treatment. One of 30 values; pick the closest match, such as welcome, onboarding, newsletter, product-launch, promotional, re-engagement, company-news, or a transactional one such as receipt or password-reset. The spec on `POST /v1/emails` lists them all. | | Content URLs | `contentUrls` | Up to 8 page URLs to ground the copy in real content: product pages, blog posts, docs. | | Reference design | `referenceEmailId` | Reuse the look and feel of an existing design. | **Reference design** opens a picker of every email in your account, with search and a full preview of the highlighted design, plus a **Start from scratch** option that seeds a blank design from the default template. It's the same reference-email mechanic as [the editor](/create-emails/emails), so you can point at a design you already like instead of describing it. ![The Reference design picker: a searchable list of every email in the account with a full preview of the highlighted design](https://0edx89zhjrasqnjf.public.blob.vercel-storage.com/docs/api_catalog_reference_design.webp) ### The API Request Snippet The snippet updates as you change parameters, and the language dropdown switches it between four shapes: | Option | What you get | | - | - | | cURL | A raw HTTP request you can paste into a terminal. | | TypeScript (SDK) | A call through [`@brew.new/sdk`](/sdks/overview), typed, with retries and idempotency handled. | | TypeScript | `fetch` against the endpoint directly, no dependency. | | Python | A plain HTTP request. | Below the snippet is the key picker. It selects which of your brand's API keys the in-app run authenticates with, and **Manage keys** jumps to [brew.new/settings/api](https://brew.new/settings/api). The key you pick applies to the run only: copied snippets always carry the `brew_your_api_key` placeholder, so nothing you paste into a doc, a ticket, or a chat window leaks a live credential. > [!WARNING] > > Keep API keys on your server. Substitute the placeholder from an > environment variable, never a hardcoded string in browser code. See > [Authentication](/api-reference/api/authentication). ## The Implementation Prompt Under the request snippet, every API carries a copyable **Implementation prompt**: a briefing written for a coding agent. It contains the goal, the endpoint, the docs link, the cost, the auth pattern (read the key from `BREW_API_KEY`, keys are brand-scoped), the TypeScript SDK equivalent, the [MCP](/api-reference/mcp/overview) tool that does the same job, every request field with its type and constraints, an example request body, and a closing instruction to ask you about SDK versus raw HTTP before writing code. Copy it into Claude Code, Cursor, or any agent with repo access and you get a working integration without the agent guessing at the surface. The header buttons cover the same ground in fewer clicks: * **Docs** opens the endpoint reference for that API. * **Try in Chat** hands the capability to the Brew chat agent. * **Open in Claude** sends the implementation prompt straight to Claude, with a dropdown for the other agents you can target. For the fuller agent story, including connecting Brew over MCP so an agent can call these capabilities directly instead of writing HTTP, see [Use Brew with AI Agents](/integrations/ai-agents/use-brew-with-ai-agents). ## What to Read Next > [card] [API Introduction](/api-reference/api/api-introduction) > > How the whole surface fits together: auth, brand scoping, sends, > analytics, automations. > [card] [MCP Server](/api-reference/mcp/overview) > > Let an agent call Brew directly, no integration code required. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # API Introduction Source: https://docs.brew.new/api-reference/api/api-introduction Use Brew Public API v1 to create email designs, send and monitor delivery, manage contacts, and run automations from your backend. The Brew Public API v1 lets your backend create email designs, send them, manage contacts, and run automations. For a terminal, Node application, or assistant, [choose an interface](/api-reference/overview) first. ## Base URL ```text theme={null} https://brew.new/api ``` Every public endpoint starts with `/v1`. For example, `GET /v1/brand` means `https://brew.new/api/v1/brand`. The OpenAPI document also lists `http://localhost:3000/api` for local development. ## Authentication Create a key at [**Settings → API**](https://brew.new/settings/api). Send it in either header: ```text theme={null} Authorization: Bearer brew_your_api_key X-API-Key: brew_your_api_key ``` A brand key resolves its own brand. An organization key selects one with `X-Brand-Id`. Brand-scoped endpoints reject `brandId` in a body or query string. [Authentication](/api-reference/api/authentication) owns permission scopes and key lifecycle; [Organization and Brand Scope](/api-reference/api/organization-and-brand-scope) owns the credential and access rules. ## Quick Start [Send Your First Email from Code](/api-reference/guides/send-your-first-email-from-code) checks brand readiness, creates a design, and sends a test with curl. No audience or verified domain is required for a test using Brew's default sender. ## How the API Fits Together | Task | Operation | Result | | - | - | - | | Generate a design | `POST /v1/emails` | Saved `emailId` and `emailVersionId`, or an explanatory `response`. Creating a design sends nothing. | | Test the design | `POST /v1/sends` with `test: true` | Completed status and recipient; no production send row. | | Deliver to subscribers | `POST /v1/sends` with a target and verified marketing domain | Accepted job with `sendId`. Acceptance is separate from delivery. | | Monitor delivery | `GET /v1/sends/{sendId}?include=events` | The send row, lifetime `stats`, and a bounded event page. | | Read brand reports | `GET /v1/analytics/{overview,automations,events}` | Totals, automation performance, or the unified event feed. | | Start event-driven delivery | `POST /v1/automations/triggers/{triggerEventId}/fire` | Trigger instance and started automation run IDs. Requires a published automation. | For automations, create the trigger and graph, then publish with `PATCH /v1/automations/{automationId}` and `{ "published": true }`. Event-driven transactional email uses a transactional-purpose domain on the automation. [Emails and Automations](/create-emails/emails-vs-automations) explains the delivery modes. One-off production send rows retain the API identifier `kind: campaign`; automation rows use `kind: automation`. The [Data Model](/api-reference/api/data-model) maps designs, sends, triggers, runs, and events. ## Current Public v1 Surface The [generated endpoint reference](/api-reference/public-v1/contacts/get-contacts) owns every request and response shape. Use its sidebar to find contacts, audiences, emails, sends, automations, domains, brand assets, media, and account operations. The [API Catalog](/api-reference/api/api-catalog) lets you try supported capabilities in Brew and copy their requests. Every operation on the surface, with the scope it needs and whether it costs credits, is in the table below. It is generated from the spec. > [accordion] Every v1 operation > > | Method | Path | Summary | Scope | Credits | operationId | > | - | - | - | - | - | - | > | `GET` | `/v1/analytics/automations` | Automation performance | `automations` | no | `getAutomationAnalytics` | > | `GET` | `/v1/analytics/events` | Unified events feed | `emails` | no | `getEventsAnalytics` | > | `GET` | `/v1/analytics/overview` | Brand overview (totals, rates, timeseries) | `emails` | no | `getAnalyticsOverview` | > | `GET` | `/v1/api-keys` | List API keys | any key | no | `listApiKeys` | > | `POST` | `/v1/api-keys` | Create an API key | any key | no | `createApiKey` | > | `DELETE` | `/v1/api-keys/{keyId}` | Revoke an API key | any key | no | `revokeApiKey` | > | `GET` | `/v1/audiences` | List audiences | `audiences` | no | `listAudiences` | > | `POST` | `/v1/audiences` | Create an audience | `audiences` | no | `createAudience` | > | `DELETE` | `/v1/audiences/{audienceId}` | Delete an audience | `audiences` | no | `deleteAudience` | > | `GET` | `/v1/audiences/{audienceId}` | Get an audience | `audiences` | no | `getAudience` | > | `PATCH` | `/v1/audiences/{audienceId}` | Update an audience | `audiences` | no | `updateAudience` | > | `POST` | `/v1/audiences/{audienceId}/duplicate` | Duplicate an audience | `audiences` | no | `duplicateAudience` | > | `POST` | `/v1/audiences/from-events` | Create an audience from analytics events | `contacts` | no | `createAudienceFromEvents` | > | `GET` | `/v1/automations` | List automations | `automations` | no | `listAutomations` | > | `POST` | `/v1/automations` | Create an automation | `automations` | no | `createAutomation` | > | `DELETE` | `/v1/automations/{automationId}` | Delete an automation | `automations` | no | `deleteAutomation` | > | `GET` | `/v1/automations/{automationId}` | Get an automation | `automations` | no | `getAutomation` | > | `PATCH` | `/v1/automations/{automationId}` | Update or publish an automation | `automations` | no | `updateAutomation` | > | `POST` | `/v1/automations/{automationId}/run` | Run a manual-audience automation | `automations` | no | `runAutomation` | > | `POST` | `/v1/automations/{automationId}/test` | Test an automation | `automations` | no | `testAutomation` | > | `GET` | `/v1/automations/audience-runs` | List manual-audience runs | `automations` | no | `listAudienceRuns` | > | `GET` | `/v1/automations/audience-runs/{audienceRunId}` | Get a manual-audience run | `automations` | no | `getAudienceRun` | > | `POST` | `/v1/automations/audience-runs/{audienceRunId}/cancel` | Cancel a manual-audience run | `automations` | no | `cancelAudienceRun` | > | `POST` | `/v1/automations/audience-runs/{audienceRunId}/pause` | Pause a manual-audience run | `automations` | no | `pauseAudienceRun` | > | `POST` | `/v1/automations/audience-runs/{audienceRunId}/resume` | Resume a manual-audience run | `automations` | no | `resumeAudienceRun` | > | `GET` | `/v1/automations/runs` | List automation runs | `automations` | no | `listAutomationRuns` | > | `GET` | `/v1/automations/runs/{automationRunId}` | Get an automation run | `automations` | no | `getAutomationRun` | > | `POST` | `/v1/automations/runs/{automationRunId}/cancel` | Cancel an automation run | `automations` | no | `cancelAutomationRun` | > | `GET` | `/v1/automations/trigger-instances` | List trigger instances | `automations` | no | `listTriggerInstances` | > | `GET` | `/v1/automations/trigger-instances/{triggerInstanceId}` | Get a trigger instance | `automations` | no | `getTriggerInstance` | > | `GET` | `/v1/automations/triggers` | List triggers | `automations` | no | `listTriggers` | > | `POST` | `/v1/automations/triggers` | Create a trigger | `automations` | no | `createTrigger` | > | `DELETE` | `/v1/automations/triggers/{triggerEventId}` | Delete a trigger | `automations` | no | `deleteTrigger` | > | `GET` | `/v1/automations/triggers/{triggerEventId}` | Get a trigger | `automations` | no | `getTrigger` | > | `PATCH` | `/v1/automations/triggers/{triggerEventId}` | Update a trigger | `automations` | no | `updateTrigger` | > | `GET` | `/v1/automations/triggers/{triggerEventId}/contract` | Get a trigger payload contract | `automations` | no | `getTriggerContract` | > | `PUT` | `/v1/automations/triggers/{triggerEventId}/contract` | Declare a trigger payload contract | `automations` | no | `setTriggerContract` | > | `POST` | `/v1/automations/triggers/{triggerEventId}/contract/validate` | Validate a trigger payload | `automations` | no | `validateTriggerPayload` | > | `POST` | `/v1/automations/triggers/{triggerEventId}/fire` | Fire a trigger | `automations` | no | `fireTrigger` | > | `GET` | `/v1/automations/triggers/{triggerEventId}/readiness` | Check a trigger is ready to fire | `automations` | no | `checkTriggerReady` | > | `POST` | `/v1/automations/triggers/brew-events` | Get or create an unsubscribe trigger | `automations` | no | `ensureBrewEventTrigger` | > | `GET` | `/v1/brand` | Get the brand bound to this API key | any key | no | `getBrand` | > | `PATCH` | `/v1/brand` | Update brand identity + design system | `emails` | no | `updateBrand` | > | `GET` | `/v1/brand/images` | Get brand images | `emails` | no | `getBrandImages` | > | `DELETE` | `/v1/brand/images/{assetId}` | Delete a brand image | `emails` | no | `deleteBrandImage` | > | `GET` | `/v1/brands` | List the brands this credential can reach | any key | no | `listBrands` | > | `POST` | `/v1/brands` | Create a brand and start its extraction | `brands` | no | `createBrand` | > | `GET` | `/v1/brands/{brandId}` | Get one brand’s lifecycle state | any key | no | `getBrandById` | > | `POST` | `/v1/canvas/sessions` | Create an authenticated email canvas embed session | `emails` | no | `createCanvasSession` | > | `DELETE` | `/v1/canvas/sessions/{sessionId}` | Revoke a canvas session | `emails` | no | `revokeCanvasSession` | > | `POST` | `/v1/canvas/sessions/{sessionId}/refresh` | Refresh a canvas session | `emails` | no | `refreshCanvasSession` | > | `GET` | `/v1/chats` | List chats | `emails` | no | `listChats` | > | `GET` | `/v1/chats/{chatId}` | Get chat context | `emails` | no | `getChatContext` | > | `GET` | `/v1/contacts` | List contacts | `contacts` | no | `listContacts` | > | `POST` | `/v1/contacts` | Create or update contacts | `contacts` | yes | `upsertContacts` | > | `DELETE` | `/v1/contacts/{email}` | Delete a contact | `contacts` | no | `deleteContact` | > | `GET` | `/v1/contacts/{email}` | Get a contact | `contacts` | no | `getContact` | > | `PATCH` | `/v1/contacts/{email}` | Update a contact | `contacts` | no | `updateContact` | > | `POST` | `/v1/contacts/batch-delete` | Batch-delete contacts | `contacts` | no | `batchDeleteContacts` | > | `POST` | `/v1/contacts/import` | Bulk-import contacts from JSON | `contacts` | yes | `importContacts` | > | `POST` | `/v1/contacts/import-csv` | Bulk-import contacts from CSV | `contacts` | yes | `importContactsCsv` | > | `POST` | `/v1/contacts/search` | Get contacts | `contacts` | no | `searchContacts` | > | `POST` | `/v1/contacts/validate` | Validate email deliverability | `contacts` | yes | `validateContacts` | > | `POST` | `/v1/content/add-image` | Add image | `emails` | no | `addImage` | > | `POST` | `/v1/content/generate-image` | Generate an image | `emails` | yes | `generateImage` | > | `POST` | `/v1/content/gif` | Generate a GIF | `emails` | yes | `createGif` | > | `POST` | `/v1/content/html-to-png` | Render HTML to a PNG | `emails` | yes | `htmlToPng` | > | `POST` | `/v1/content/image-uploads` | Create an image upload | `emails` | no | `createImageUpload` | > | `POST` | `/v1/content/transform` | Transform an image | `emails` | yes | `transformImage` | > | `GET` | `/v1/domains` | List domains | `domains` | no | `listDomains` | > | `POST` | `/v1/domains` | Add a domain | `domains` | no | `addDomain` | > | `DELETE` | `/v1/domains/{domainId}` | Delete a domain | `domains` | no | `deleteDomain` | > | `GET` | `/v1/domains/{domainId}` | Get a domain | `domains` | no | `getDomain` | > | `PATCH` | `/v1/domains/{domainId}` | Update domain settings | `domains` | no | `updateDomain` | > | `GET` | `/v1/domains/{domainId}/health` | Get domain health | `domains` | no | `getDomainHealth` | > | `GET` | `/v1/domains/{domainId}/unsubscribes` | List a domain's unsubscribes | `domains` | no | `listDomainUnsubscribes` | > | `POST` | `/v1/domains/{domainId}/unsubscribes` | Add addresses to a domain's unsubscribe list | `domains` | no | `addDomainUnsubscribes` | > | `DELETE` | `/v1/domains/{domainId}/unsubscribes/{email}` | Remove an address from a domain's unsubscribe list | `domains` | no | `removeDomainUnsubscribe` | > | `GET` | `/v1/domains/{domainId}/unsubscribes/export` | Export a domain's unsubscribe list | `domains` | no | `exportDomainUnsubscribes` | > | `POST` | `/v1/domains/{domainId}/unsubscribes/import` | Import a CSV into a domain's unsubscribe list | `domains` | no | `importDomainUnsubscribes` | > | `POST` | `/v1/domains/{domainId}/verify` | Verify a domain | `domains` | no | `verifyDomain` | > | `GET` | `/v1/email-groups` | List email groups | `emails` | no | `listEmailGroups` | > | `POST` | `/v1/email-groups` | Create an email group | `emails` | no | `createEmailGroup` | > | `DELETE` | `/v1/email-groups/{groupId}` | Delete an email group | `emails` | no | `deleteEmailGroup` | > | `GET` | `/v1/email-groups/{groupId}` | Get an email group | `emails` | no | `getEmailGroup` | > | `PATCH` | `/v1/email-groups/{groupId}` | Update an email group | `emails` | no | `updateEmailGroup` | > | `GET` | `/v1/emails` | List email designs | `emails` | no | `listEmails` | > | `POST` | `/v1/emails` | Generate an email design | `emails` | yes | `generateEmail` | > | `DELETE` | `/v1/emails/{emailId}` | Delete an email design | `emails` | no | `deleteEmail` | > | `GET` | `/v1/emails/{emailId}` | Get an email design | `emails` | no | `getEmail` | > | `PATCH` | `/v1/emails/{emailId}` | Edit an email design | `emails` | yes | `editEmail` | > | `POST` | `/v1/emails/{emailId}/client-previews` | Preview across clients & devices | `emails` | yes | `previewEmailAcrossClients` | > | `POST` | `/v1/emails/{emailId}/clone` | Clone an email design | `emails` | no | `cloneEmail` | > | `GET` | `/v1/emails/{emailId}/comments` | List email comments | `emails` | no | `listEmailComments` | > | `POST` | `/v1/emails/{emailId}/export` | Export a design to an ESP | `emails` | no | `exportEmailDesign` | > | `GET` | `/v1/emails/{emailId}/inbox-placement-tests` | List inbox placement tests | `emails` | no | `listInboxPlacementTests` | > | `POST` | `/v1/emails/{emailId}/inbox-placement-tests` | Run an inbox placement test | `emails` | yes | `createInboxPlacementTest` | > | `GET` | `/v1/emails/{emailId}/inbox-placement-tests/{testId}` | Get inbox placement test results | `emails` | no | `getInboxPlacementTest` | > | `POST` | `/v1/emails/{emailId}/restore` | Restore a historical version | `emails` | no | `restoreEmailVersion` | > | `POST` | `/v1/emails/audit` | Audit an email | `emails` | yes | `auditEmail` | > | `GET` | `/v1/emails/audits/{auditId}` | Read a saved email audit | `emails` | no | `getEmailAudit` | > | `GET` | `/v1/emails/client-previews/{previewId}` | Read email rendering progress | `emails` | no | `getEmailRendering` | > | `POST` | `/v1/emails/figma` | Import a Figma frame | `emails` | no | `importFigmaDesign` | > | `POST` | `/v1/emails/import` | Import an email | `emails` | no | `importEmail` | > | `GET` | `/v1/fields` | List contact fields | `contacts` | no | `listContactFields` | > | `POST` | `/v1/fields` | Create a contact field | `contacts` | no | `createContactField` | > | `DELETE` | `/v1/fields/{fieldName}` | Delete a contact field | `contacts` | no | `deleteContactField` | > | `GET` | `/v1/fields/{fieldName}` | Get a contact field | `contacts` | no | `getContactField` | > | `GET` | `/v1/flows` | List flows | any key | no | `listFlows` | > | `GET` | `/v1/flows/{slug}` | Get a flow | any key | no | `getFlow` | > | `GET` | `/v1/health` | Liveness probe | none (no auth) | no | `getHealth` | > | `GET` | `/v1/help` | Machine-readable API catalog | none (no auth) | no | `getHelp` | > | `GET` | `/v1/insights` | List insights | `emails` | no | `listInsights` | > | `GET` | `/v1/insights/{insightId}` | Get an insight | `emails` | no | `getInsight` | > | `GET` | `/v1/integrations` | List integrations | any key | no | `listIntegrations` | > | `GET` | `/v1/notifications` | List notifications | any key | no | `listNotifications` | > | `POST` | `/v1/payload-contracts/infer` | Infer a payload contract from an example | any key | no | `inferPayloadContract` | > | `GET` | `/v1/sends` | List sends | `sends` | no | `listSends` | > | `POST` | `/v1/sends` | Send an email | `sends` | no | `createSend` | > | `GET` | `/v1/sends/{sendId}` | Get a send | `sends` | no | `getSend` | > | `POST` | `/v1/sends/{sendId}/cancel` | Cancel a send | `sends` | no | `cancelSend` | > | `POST` | `/v1/sends/{sendId}/pause` | Pause a gradual send | `sends` | no | `pauseSend` | > | `POST` | `/v1/sends/{sendId}/resume` | Resume a paused send | `sends` | no | `resumeSend` | > | `GET` | `/v1/templates` | List templates | any key | no | `listTemplates` | > | `GET` | `/v1/templates/{templateId}` | Get a public template | any key | no | `getTemplate` | > | `GET` | `/v1/usage` | Get usage | any key | no | `getUsage` | > | `GET` | `/v1/webhooks` | List webhooks | `emails` | no | `listWebhooks` | > | `POST` | `/v1/webhooks` | Create webhook | `emails` | no | `createWebhook` | > | `DELETE` | `/v1/webhooks/{webhookId}` | Delete webhook | `emails` | no | `deleteWebhook` | > | `GET` | `/v1/webhooks/{webhookId}` | Get webhook | `emails` | no | `getWebhook` | > | `PATCH` | `/v1/webhooks/{webhookId}` | Update webhook | `emails` | no | `updateWebhook` | > | `GET` | `/v1/webhooks/{webhookId}/events` | List webhook events | `emails` | no | `listWebhookEvents` | > | `GET` | `/v1/webhooks/{webhookId}/events/{eventId}/attempts` | List webhook attempts | `emails` | no | `listWebhookAttempts` | > | `POST` | `/v1/webhooks/{webhookId}/events/{eventId}/replay` | Replay webhook event | `emails` | no | `replayWebhookEvent` | > | `POST` | `/v1/webhooks/{webhookId}/rotate-secret` | Rotate webhook secret | `emails` | no | `rotateWebhookSecret` | > | `POST` | `/v1/webhooks/{webhookId}/test` | Test webhook | `emails` | no | `testWebhook` | ## Discover the API Programmatically These endpoints work without a key: | Endpoint | Returns | | - | - | | `GET /v1/help` | Authentication, scopes, limits, credit costs, errors, and the endpoint catalog. | | `GET /v1/llms.txt` | The API surface as prose for agents. | | `GET /v1/health` | Liveness `status` and `version`. | The canonical OpenAPI document is [public-api-v1.yaml](https://brew.new/openapi/public-api-v1.yaml). It's also served as JSON at [brew.new/openapi.json](https://brew.new/openapi.json). ## Cross-Cutting Rules Each shared contract has one owner: * [Authentication](/api-reference/api/authentication) and [Organization and Brand Scope](/api-reference/api/organization-and-brand-scope): permissions and credential scope. * [Errors](/api-reference/api/errors): error envelope, codes, and recovery. * [Idempotency](/api-reference/api/idempotency): retry keys, replay windows, and conflicts. * [Pagination](/api-reference/api/pagination) and [Batch Operations](/api-reference/api/batch-operations): cursors and bulk work. * [Async Jobs](/api-reference/api/async-jobs): follow accepted work through completion. * [Rate Limits](/api-reference/api/rate-limits), [Credits](/api-reference/api/credits), and [Response Headers](/api-reference/api/response-headers): limits, costs, and diagnostics. * [v1 Migration](/api-reference/api/v1-migration): replace older routes and response shapes. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Async Jobs and Polling Source: https://docs.brew.new/api-reference/api/async-jobs Find the job identifiers, status reads, terminal states, and polling rules for Brew email sends, automation runs, previews, and placement tests. An accepted job has not necessarily finished or delivered an email. Keep its identifier and read its status until it reaches a terminal state. ## Async Operations | Start work | Response identifier | Status read | | - | - | - | | `POST /v1/automations/triggers/{triggerEventId}/fire` | `triggerInstanceId`, `automationRunIds[]` | `GET /v1/automations/trigger-instances/{triggerInstanceId}` and `GET /v1/automations/runs/{automationRunId}?include=logs` | | `POST /v1/automations/{automationId}/test` | `automationRunIds[]` | `GET /v1/automations/runs/{automationRunId}?include=logs` | | `POST /v1/automations/{automationId}/run` | `audienceRunId` | `GET /v1/automations/audience-runs/{audienceRunId}` | | `POST /v1/sends` (production) | `sendId` | `GET /v1/sends/{sendId}` | | `POST /v1/emails/{emailId}/client-previews` | `previewId` | `GET /v1/emails/client-previews/{previewId}` | | `POST /v1/emails/{emailId}/inbox-placement-tests` | `testId` | `GET /v1/emails/{emailId}/inbox-placement-tests/{testId}` | | `POST /v1/audiences/from-events` | `audienceId`, `build.jobId` | `GET /v1/audiences/{audienceId}?include=build` | An automation dry run (`dryRun: true`) returns a synchronous preview instead of starting an audience run. An automation test omitting `testRecipient` sends no email; setting it delivers test copies to that address. `POST /v1/sends` with `test: true` returns `200 { status: "completed", recipient }` without a production send row. Production sends return `202` with `queued`, `scheduled`, or `pending_approval`; approval is required before a held send starts. ## Fire a Trigger, Then Poll the Run One trigger fire can start several published automations. Inspect every returned run ID. `notStarted[]` explains failed starts, and `counts.skipped` counts recipients covered by a suppression. If no bound automation is published, the fire returns `422 NO_PUBLISHED_AUTOMATION` and there are no runs to poll. Inspect the trigger instance to understand an accepted fire that returned no run IDs. For a returned run ID: ```bash theme={null} export BREW_API_KEY="brew_your_api_key" export AUTOMATION_RUN_ID="YOUR_RETURNED_RUN_ID" curl --fail-with-body \ "https://brew.new/api/v1/automations/runs/$AUTOMATION_RUN_ID?include=logs" \ -H "Authorization: Bearer $BREW_API_KEY" ``` The response is the bare run, with `status` and `logs` at the top level. Organization keys also need `X-Brand-Id`; see [Authentication](/api-reference/api/authentication). ### Recommended Polling Cadence For a short run, start with one read every two seconds and bound the wait to your application's deadline. For flows with long `wait` nodes, read when you need an update. Avoid keeping a loop open for days. Client previews provide `nextPollAfterMs`; honor it while work is pending. On `429`, honor `Retry-After`. Budget all concurrent polls against the [Rate Limits](/api-reference/api/rate-limits). If your polling deadline expires, retain the job ID to inspect later. ## Terminal States | Job | Finished states | | - | - | | Automation execution or manual-audience run | `completed`, `failed`, `canceled` | | Production send | `completed`, `partially_completed`, `failed`, `canceled` | | Client preview, inbox placement test, or audience build | `completed`, `partially_completed`, `failed` | `scheduled`, `queued`, `running`, and `paused` are not terminal. `partially_completed` means some work failed; inspect the result rather than treating it as full success. ## Queue a Send, Then Verify Read `GET /v1/sends/{sendId}` for delivery progress and aggregate `stats`. Add `?include=events` for per-recipient events. Sending is complete before all later opens or clicks have occurred. [Monitor Email Sends](/api-reference/guides/monitor-campaign-sends) owns the detailed monitoring workflow. Use [Preview in Real Inboxes](/create-emails/preview-in-real-inboxes) for rendering checks and the generated endpoint reference for placement-test schemas. ## Idempotency on Async Retries Once you have a job ID, poll it instead of submitting new work. If the starting request's outcome is unknown, replay the same inputs with the same retry key. [Idempotency](/api-reference/api/idempotency) owns the replay contract. Raw HTTP and SDK email generation waits for the saved design or an explanatory response. MCP generation can return while the design is still generating; poll `get_email` with the returned IDs. ## Cancel Instead of Waiting | Stop or control work | Route | | - | - | | One automation execution | `POST /v1/automations/runs/{automationRunId}/cancel` | | A manual-audience run | `POST /v1/automations/audience-runs/{audienceRunId}/{pause,resume,cancel}` | | A production send | `POST /v1/sends/{sendId}/{pause,resume,cancel}` | These actions cannot recall emails already delivered. Use the generated endpoint reference for action preconditions and response schemas. ## Job Completion and Email Events Use [email webhooks](/api-reference/api/events-and-webhooks#outbound-email-webhooks) for delivery and engagement events. Poll the job resource to follow automation, generation, and import completion. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Authentication and Security Source: https://docs.brew.new/api-reference/api/authentication Brew Public API v1 authentication: brand and organization keys, permission scopes, key lifecycle, and production security best practices. Brew uses **API key authentication**. Each key is scoped to one brand or to your whole organization at creation time, carries a permission scope set, and ships over HTTPS as either an `Authorization: Bearer` header or the convenience `X-API-Key` header. ## Quickstart ```bash theme={null} curl -H "Authorization: Bearer brew_your_api_key" \ https://brew.new/api/v1/domains ``` ```ts theme={null} import { createBrewClient } from '@brew.new/sdk' const brew = createBrewClient({ apiKey: process.env.BREW_API_KEY! }) const { data: domains } = await brew.domains.list() ``` Get a key at [brew.new/settings/api](https://brew.new/settings/api). ## Headers (Use ONE) | Header | Format | Notes | | - | - | - | | `Authorization` | `Bearer brew_…` | Recommended. Plays nicely with most HTTP clients + observability tooling. | | `X-API-Key` | `brew_…` | Convenience header. Same behavior as the bearer form. | Send one of the two. Sending neither returns `401 AUTHENTICATION_REQUIRED`. Malformed keys return `401 INVALID_API_KEY`; revoked keys return `401 API_KEY_REVOKED`. ## Brand vs Organization Keys Every key is scoped when you create it, and the scope can't change later. It covers either one brand or your whole organization. | | Brand key | Organization key | | - | - | - | | Reaches | The one brand it was created for | Every brand in the organization | | Naming the brand | Nothing to send. The key resolves its brand. | Send `X-Brand-Id: ` on every brand-scoped request | | Brand left out | Works | `400 BRAND_ID_REQUIRED`. There is no default brand. | | A different brand named | `403 BRAND_SCOPE_MISMATCH` | Works for any brand in the organization | | Create a brand (`POST /v1/brands`) | `403 ORG_SCOPE_REQUIRED` | Works with the `brands` scope | An organization key names its brand on each request: ```bash theme={null} curl -H "Authorization: Bearer brew_your_org_key" \ -H "X-Brand-Id: kx7b3s7fapqz8mjm12ekz1kxdx87yceg" \ https://brew.new/api/v1/domains ``` Find brand ids with `GET /v1/brands`. An organization key sees every brand there. A brand key sees only its own, so the same call tells any key which brand it can reach. These rules hold for both kinds: * `X-Brand-Id` is a header, and it is the only way to name a brand. No endpoint accepts a `brandId` field in a body or query string. Sending one returns `400 INVALID_REQUEST` with `param: "brandId"`. * Reads return only the resolved brand's data, and writes change only that brand. An identifier from another brand returns `404` (not `403`), so the API never confirms that a resource exists elsewhere. An `X-Brand-Id` naming a brand outside your organization returns `404 BRAND_NOT_FOUND` for the same reason. * Organization-level endpoints (brands, templates, flows, usage) take no `X-Brand-Id`. [Organization operations](/api-reference/api/organization-and-brand-scope#organization-operations) owns the full list. Every other authenticated endpoint is brand-scoped. Use a brand key when an integration only ever touches one brand. If it leaks, the damage stays inside that brand. Use an organization key for tooling that works across brands, like a script that creates brands. A brand can have any number of keys (dev, staging, production, per-service, per-teammate). [Organization and brand credentials](/api-reference/api/organization-and-brand-scope) owns this contract in full: which operations are organization-level, when you get `400 BRAND_ID_REQUIRED`, `403 BRAND_SCOPE_MISMATCH`, or `403 ORG_SCOPE_REQUIRED`, and how that differs from `403 INSUFFICIENT_ROLE`. ## Permission Scopes Each key carries one or more permission scopes. Routes require either the route's scope or `all`. Missing permission returns `403 INSUFFICIENT_PERMISSIONS` with `error.param` pointing at the missing scope name. ### Scope Implication (Coarse Scopes Satisfy Granular Ones) Brew supports both **coarse** scopes (`contacts`, `emails`, `automations`) and **granular** least-privilege scopes (`audiences`, `domains`, `sends`). A coarse scope automatically satisfies the granular scopes it implies, so existing keys keep working. You only reach for the granular scopes when you want to lock a key down further. | Granted scope | Satisfies | | - | - | | `contacts` | `contacts`, `audiences` | | `emails` | `emails`, `domains`, `sends` | | `automations` | `automations` | | `all` | everything | | each granular scope (`audiences`, `domains`, `sends`) | itself only (least privilege) | | `brands` | itself only. No other scope implies it, so an existing key never gains the right to create brands. | The complete set of valid scope values accepted when a key is created is `contacts`, `emails`, `automations`, `audiences`, `domains`, `sends`, `brands`, `transactional`, and `all`. ### Per-Route Required Scope A trailing `*` covers every method and nested route under that path prefix. | Route | Required scope (or an implier) | | - | - | | `/v1/contacts*`, `/v1/fields*`, `POST /v1/audiences/from-events` | `contacts` | | `include=openProfile` on `GET /v1/contacts/{email}` and `POST /v1/contacts/search` | `contacts` and `emails` | | `/v1/audiences*` (other than `from-events`) | `audiences` (or `contacts`) | | `/v1/domains*` | `domains` (or `emails`) | | `/v1/emails*`, `/v1/email-groups*` | `emails` | | `/v1/canvas/sessions*` | `emails` (create, refresh, and revoke server-authorized canvas access) | | `/v1/sends*` (including `{ test: true }`) | `sends` (or `emails`) | | `PATCH /v1/brand` | `emails` | | `/v1/usage` | none, but only an organization-scoped credential (a brand key gets `403 ORG_SCOPE_REQUIRED`) | | `/v1/analytics/overview`, `/v1/analytics/events`, `/v1/insights*` | `emails` | | `/v1/analytics/automations` | `automations` | | `/v1/automations` (incl. `/triggers*`, `/runs*`, `/audience-runs*`, `/trigger-instances*`) | `automations` | | `/v1/content/*`, `/v1/chats*` | `emails` | | `POST /v1/brands` | `brands`, on an organization key | | `GET /v1/brands*`, `GET /v1/integrations`, `GET /v1/brand`, `GET /v1/templates*`, `GET /v1/flows*`, `POST /v1/payload-contracts/infer` | any scope | | `GET /v1/notifications` | any scope, with each row filtered by type (below) | | `/v1/api-keys*` | none: a signed-in dashboard session only (see [Key Lifecycle](#key-lifecycle)) | | `/v1/health`, `/v1/help` | none: no authentication | `transactional` is a reserved scope with no route today. `GET /v1/notifications` admits any credential, then shows each row only when the credential may read what it describes. A row it can't see is left out, so an empty page can mean nothing happened or that this credential can't see that kind of row, and a `type` filter it can't see is an empty page, not an error. | Notification `type` | Who sees it | | - | - | | `chat_stream`, `preview_email` | `emails` | | `email_sent`, `email_scheduled`, `email_send_failed`, `gradual_send_paused`, `gradual_send_completed`, `send_review_rejected` | `sends` (or `emails`) | | `domain_status`, `domain_score_run` | `domains` (or `emails`) | | `import_job`, `validation_job` | `contacts` | | `automation_pause_window_closed` | `automations` | | `brand_extracted`, `brand_image_import` | every credential on the brand | | `api_key_created` | `all` | | `send_limit_reached` | organization admins only: an admin's organization-wide connection, or an organization-wide key holding `all`. Never a brand key. | | `comment_mention`, `comment_reply` (`isPersonal: true`) | only the person addressed, on a personal (OAuth) connection. Never an API key. | **Principle of least privilege.** For a back-end that only fires triggers, issue a key with `automations` only: even if it leaks, it can't list contacts. For a service that only inspects send health, issue `emails` because the analytics reads require that scope; the key still cannot manage contacts or automations. The dashboard surfaces each key's scope set so you can audit + rotate. ## Key Lifecycle | Action | Where | | - | - | | **Create** | [**Settings → API**](https://brew.new/settings/api). Choose one brand or the whole organization, then a scope set; the secret is shown ONCE, store it in your secret manager. | | **List** | Dashboard. The list shows the key id, prefix, scope, brand binding, and last-used timestamp. The full secret is never re-exposed. | | **Rotate** | Dashboard. Open the key's **•••** menu, choose **Rotate key**, then **Create replacement**. Brew creates a new key with the same scope. The old key stays active until you switch your apps to the new one and revoke it. | | **Revoke** | Dashboard. Open the key's **•••** menu and choose **Revoke key**. Revoked keys immediately return `401 API_KEY_REVOKED` on every request. | | **Audit** | Dashboard surfaces the last-used timestamp per key. Pair with your platform's request logs (for example Vercel) for full attribution via `x-request-id`. | Key CRUD is **not part of the programmatic surface**. The three `/v1/api-keys` operations you see in the API reference back the dashboard's own API page: they accept only a signed-in Clerk session whose active organization role is exactly `org:admin`. An API key, an OAuth connection, the MCP server, and the CLI all receive `403` on them, so a compromised key can never mint or revoke another. If you need programmatic key management for a SOC2 / SAST pipeline, contact us. ## Production Security Checklist | Practice | Why | | - | - | | **Keys live in environment variables on the server only.** Never in client JS, mobile binaries, or git. | A key in the browser can be exfiltrated and used against your brand. | | **Use short-lived deploys' env vars + a secret manager.** Vercel + Vault / Doppler / 1Password / AWS Secrets Manager all work. | Centralised rotation, audit trail. | | **One key per environment.** Separate dev / staging / prod keys. | Blast radius: revoke staging without touching prod. | | **One key per service** when feasible. Webhook receiver gets a key; cron worker gets a different key. | Granular audit + rotation. | | **Set `Idempotency-Key`** on every retried `POST` so a replayed key burst doesn't double-fire. | See [Idempotency](/api-reference/api/idempotency). | | **Honor `Retry-After`** on `429`. | See [Rate limits](/api-reference/api/rate-limits). | | **Log every API call's `x-request-id`** from the response. | Support diagnostics; correlate end-to-end through Brew's pipeline. | | **Pin to the official TypeScript SDK** when possible (`@brew.new/sdk@latest`). | Auto-retries, auto-idempotency keys, typed error envelope. | | **Verify webhook signatures** before accepting email events. | See [Verify Requests](/api-reference/api/events-and-webhooks#verify-requests). | ## What We Do NOT Support Today For transparency: * **OAuth for the REST API.** The Public API is server-to-server and takes API keys only. If you want per-user authorization on top of the API, build it in your app and hold the Brew key on your server. OAuth 2.1 exists for the [MCP server](/api-reference/mcp/authentication-and-scoping#authentication) and for [Vercel Connect](/integrations/ai-agents/vercel-connect), not for direct HTTP calls. * **PATCH request idempotency.** See [Idempotency](/api-reference/api/idempotency) for the supported methods and replay contract. * **Public key-management API.** The `/v1/api-keys` operations require an `org:admin` dashboard session, so keys are minted, rotated, and revoked from the dashboard, never by another key. These are roadmap items where there's customer pull; tell us at the link below if your integration needs any of them. ## Errors Authentication failures and permission errors use the standard envelope and codes documented in [Errors](/api-reference/api/errors). ## Related * [API introduction](/api-reference/api/api-introduction): the overview that links every reference page. * [Idempotency](/api-reference/api/idempotency): set `Idempotency-Key` on every retried `POST`. * [Rate limits](/api-reference/api/rate-limits): per-route policies + the `429` cookbook. * [SDK authentication](/sdks/authentication): TypeScript SDK auth specifics. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Batch Operations Source: https://docs.brew.new/api-reference/api/batch-operations Batch contact upsert, import, and delete on the Brew Public API v1: payload limits, partial-success contract, per-row error reporting. Brew accepts batch writes on the contacts routes so agents and back-end importers can upsert / delete many rows in a single request without burning the per-request rate-limit budget. Batches are **partial-success-safe**: one bad row doesn't fail the whole call. ## Where It Applies | Endpoint | Batch shape | Max rows | Rate-limit policy | | - | - | - | - | | `POST /v1/contacts` | `{ contacts: [...] }` | 1000 | `contacts.write_batch` (10 / min) | | `POST /v1/contacts/batch-delete` | `{ emails: [...] }` | 1000 | `contacts.write_batch` (10 / min) | Single-row upserts use `POST /v1/contacts` with a different body shape and the higher-rate `contacts.write_single` policy (100 / min). Single-row deletes use `DELETE /v1/contacts/{email}`. Choose the shape that matches your workload: `100/min × 1 row` = 100 contacts/min; `10/min × 1000 rows` = 10,000 contacts/min. ## Partial-Success Contract When **any** rows fail, including when every row fails, the batch upsert returns `207` instead of `200`. Failures are surfaced in `errors[]` so callers can fix and re-submit the rejected rows. ```json theme={null} { "summary": { "inserted": 8, "updated": 2, "failed": 1 }, "fieldsCreated": ["plan", "creditBalance"], "errors": [ { "email": "bad@", "row": 11, "code": "INVALID_EMAIL", "message": "'bad@' is not a valid email address." } ], "warnings": [ { "code": "FIELD_NAME_NORMALIZED", "row": 1, "field": "creditBalance", "original": "credit_balance", "normalized": "creditBalance", "message": "Field name normalized to 'creditBalance'." } ] } ``` | Field | Meaning | | - | - | | `summary.inserted` | Rows inserted by this request's atomic contact writes. | | `summary.updated` | Rows matched by this request's atomic contact writes, including writes that leave stored values unchanged. | | `summary.failed` | Rejected input rows, including every row in a duplicate-address group. | | `fieldsCreated` | Custom field definitions auto-created on the brand by this request (snake_case / kebab-case → camelCase normalized). When two requests create the same new field at the same moment, only the one whose definition was stored lists it. | | `errors[]` | Per-row failures keyed on `email`. Each carries a stable `code` (for example `MISSING_EMAIL`, `INVALID_EMAIL`). | | `warnings[]` | Non-fatal observations, such as field normalization and coercion. A value converted to its field's type (the number `5` stored as `"5"` in a `string` field) carries a `FIELD_TYPE_COERCED` warning with `field`, `from` and `to`. | For a completed JSON batch upsert response, `inserted + updated + failed` equals the number of input rows. Two duplicate rows contribute `failed: 2`. Use `summary.failed` to count rejected rows. ## `POST /v1/contacts`: Batch Upsert Up to 1000 rows per request. `email` is the merge key; missing or malformed emails land in `errors[]`. Custom fields auto-create field definitions on the brand on first sight, typed from the batch. If another request creates the same new field at the same moment, the first definition wins, and this request's values are converted to its type or refused with `FIELD_TYPE_MISMATCH`, exactly as if this request had been sent second. Create the field first with `POST /v1/fields` to pin its type. See [Pagination](/api-reference/api/pagination) for reading them back. The addresses below are synthetic fixtures. Replace them with test contacts you control. ```bash theme={null} curl -X POST https://brew.new/api/v1/contacts \ -H "Authorization: Bearer $BREW_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: contacts-import-2026-04-08" \ -d '{ "contacts": [ { "email": "jane@brewmail.dev", "firstName": "Jane", "customFields": { "plan": "pro" } }, { "email": "john@brewmail.dev", "firstName": "John", "customFields": { "plan": "free" } }, { "email": "bad@", "firstName": "Bad" } ] }' ``` Assume John exists, Jane is new, and the brand has no `plan` field definition. The response is `207` because `bad@` fails validation: ```json theme={null} { "summary": { "inserted": 1, "updated": 1, "failed": 1 }, "fieldsCreated": ["plan"], "errors": [ { "email": "bad@", "row": 3, "code": "INVALID_EMAIL", "message": "'bad@' is not a valid email address." } ], "warnings": [] } ``` ### TypeScript SDK ```ts theme={null} const result = await brew.contacts.upsert({ contacts: [ { email: 'jane@brewmail.dev', firstName: 'Jane', customFields: { plan: 'pro' } }, { email: 'john@brewmail.dev', firstName: 'John', customFields: { plan: 'free' } }, ], }) console.log(result.summary) // { inserted, updated, failed } console.log(result.fieldsCreated) // ['plan'] on first sight for (const err of result.errors) { console.error(`row ${err.email} failed: ${err.code}, ${err.message}`) } ``` ## `POST /v1/contacts/batch-delete`: Batch Delete Up to 1000 emails per request. The endpoint is idempotent: deleting a non-existent email surfaces in `notFound[]`, not as an error. ```bash theme={null} curl -X POST https://brew.new/api/v1/contacts/batch-delete \ -H "Authorization: Bearer $BREW_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "emails": [ "jane@brewmail.dev", "missing@brewmail.dev" ] }' ``` Assuming Jane exists and `missing@brewmail.dev` does not, the response is `200`: ```json theme={null} { "deletedCount": 1, "notFound": ["missing@brewmail.dev"] } ``` ## Contact Imports `POST /v1/contacts/import` (JSON rows) and `POST /v1/contacts/import-csv` (CSV text) follow the same partial-success contract. Each also records an [Import History](/audience/add-contacts#import-history) batch and returns its `importId`. [Add Contacts](/audience/add-contacts#api) covers when to use each, consent, and the preview and skip modes. * **Counts.** `summary.total` counts the submitted JSON contacts or parsed CSV data rows. It equals `inserted + updated + failed + skipped`. * **Partial results.** Inspect `errors` and `warnings` before retrying. Each failed row has its own error with a 1-based `row`: `contacts[row - 1]` for JSON, or the CSV data row, counting neither the header nor blank lines. Fix and retry only failed rows; successful writes have already landed. * **Skipped rows.** With `onConflict: "skip"`, each existing contact counts as skipped. In a CSV, missing or invalid addresses and earlier duplicates are counted as skipped too. `CSV_ROW_SKIPPED` warnings name the first 100 skipped rows; one additional warning counts the rest. Column-wide and aggregate warnings have no row index. * **Duplicates.** A CSV processes the last row for each repeated address; inspect its result before assuming it was saved. A JSON batch fails every row of a repeated address, so send each contact once. * **Managed columns.** A column Brew manages, such as `Created At` or `Validation Status`, isn't imported. The response names it in a `CSV_COLUMN_IGNORED` warning. * **Field names.** Brew stores each custom field under its [folded camelCase name](/audience/manage-contacts#property-names). A JSON key sent in another spelling, such as `team_size`, is stored as `teamSize` with a `FIELD_NAME_NORMALIZED` warning that carries `original` and `normalized`. * **Two spellings of one field.** Keys that fold to one field, such as `plan` and `Plan`, would lose a value, so Brew refuses them with `FIELD_NAME_COLLISION`: * A single `POST /v1/contacts` answers `422` and writes nothing. `param` names the second key, and `details` carries `field` and `keys`. * A batch `POST /v1/contacts` or `POST /v1/contacts/import` fails that row with an `errors[]` entry (`code: FIELD_NAME_COLLISION`, `field: customFields.`). The other rows are written. * `PATCH /v1/contacts/{email}` and MCP `update_contact` answer `422` and write nothing. * `POST /v1/contacts/import-csv` and MCP `import_contacts_csv` answer `422` with `param: mapping` when two columns land on one custom field, before any row is read, `dryRun` included. Remap one column in `mapping`, or leave it out with `""`. This CSV import answers `207`: row 3 has a value its field rejects, and row 2 has no email. ```json theme={null} { "summary": { "inserted": 2, "updated": 0, "failed": 1, "skipped": 1, "total": 4 }, "importId": "imp_8f2k3j", "fieldsCreated": [], "errors": [ { "row": 3, "email": "grace@acme.com", "code": "FIELD_TYPE_MISMATCH", "field": "customFields.plan", "message": "Field 'customFields.plan' is type 'number' but received string '$49'." } ], "warnings": [ { "row": 2, "code": "CSV_ROW_SKIPPED", "message": "Row 2 has no email address, so it was skipped." } ] } ``` ## Common Per-Row Error Codes | Code | When | | - | - | | `MISSING_EMAIL` | Row in `contacts[]` omitted `email`. | | `INVALID_EMAIL` | The address fails validation, such as malformed syntax, a reserved domain, or a likely domain typo. | | `DUPLICATE_EMAILS_IN_BATCH` | Two or more rows in the same batch share an email. The address lands in `errors[]` and none of its rows is applied, so send one row per email. | | `FIELD_TYPE_MISMATCH` | A custom-field value didn't match the existing field definition's type. Re-emit with a coerced value OR delete the field. | Email matching trims surrounding whitespace and ignores case. Deduplicate those normalized addresses before retrying. To unsubscribe a contact, submit one unambiguous row with the address and top-level `subscribed: false` to `POST /v1/contacts`. A rejected duplicate group applies no subscription changes. Foundational codes from [Errors](/api-reference/api/errors) (for example `RATE_LIMITED`, `INVALID_REQUEST`) only ever apply to the whole request, never to individual rows. ## Auto-Created Field Definitions When a batch upsert references a custom field the brand doesn't have yet, Brew creates the field definition before the write. The new column shows up immediately in: * the contacts page (filterable / sortable / searchable), * the audience builder, * `GET /v1/fields`, * `POST /v1/contacts/search` with `{ "logic": "and", "filters": [{ "field": "plan", "operator": "equals", "value": "pro" }] }`. Field names are normalized to one camelCase field. `Plan` and `PLAN` are `plan`, and `team_size` and `Team Size` are `teamSize`. [Property Names](/audience/manage-contacts#property-names) has the full rule. A key stored under its normalized name adds a `FIELD_NAME_NORMALIZED` warning with `original` and `normalized`. Two keys in one row that normalize to one field, such as `plan` and `Plan`, would lose a value. That row fails with `FIELD_NAME_COLLISION` (`field: customFields.`), and the other rows are still written. Send one of the keys, or rename one so it names a different field. ## Partial Success Design Batch writes report aggregate counts and failed rows so invalid data does not block valid contacts. The contract and response shape are above; see [API design notes](/api-reference/api/design-notes#why-batch-writes-allow-partial-success) for the rationale. If your workflow requires all-or-nothing, validate and stage the input before calling the endpoint. Do not infer which successful rows were newly inserted from aggregate counts and delete them, because a batch can also update existing contacts. ## Related * [Idempotency](/api-reference/api/idempotency): set `Idempotency-Key` on the batch so a retry doesn't replay 1000 rows. * [Rate limits](/api-reference/api/rate-limits): `contacts.write_batch` is 10/min (vs single at 100/min); plan accordingly. * [Pagination](/api-reference/api/pagination): for reading back the imported rows. * [Errors](/api-reference/api/errors): full error catalog for the foundational request-level codes. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # API Credits Source: https://docs.brew.new/api-reference/api/credits How credits work on the Brew Public API v1: usage-metered AI generation, fixed media costs, credit headers, and checking your balance with GET /v1/usage. Some operations consume **credits**. Each credit is worth \$0.01 of underlying spend. Every credit-metered operation charges only on success. AI generation and edits bill the tokens used, even when the agent answers in text instead of producing a design. There are **two metering modes**: * **Usage-metered**: email generation, AI email edits, and image generation charge the **actual model usage** (token input/output for the email agent; image-gateway cost for image generation). The cost scales with the work, so there is **no fixed number** and **no `X-Credit-Cost` header**. The call still gates: an empty balance is rejected up front. * **Fixed**: audits, validation, and media or rendering operations charge a **flat, published per-operation cost**, reported via the `X-Credit-Cost` response header. ## Which Operations Cost Credits | Operation | Route | Metering | | - | - | - | | Generate an email | `POST /v1/emails` | Usage (tokens) | | Import an email (HTML, MJML, EML, or React Email → editable design) | `POST /v1/emails/import` | Free | | Edit an email (AI prompt edit) | `PATCH /v1/emails/{emailId}` | Usage (tokens) | | Rename an email, set its subject line or language, or move it to a group | `PATCH /v1/emails/{emailId}` with `title`, `subjectLine`, `lang`, or `groupId` and no `prompt` | Free | | Generate an image (saves to the brand's generated images) | `POST /v1/content/generate-image` | Usage (image) | | Preview an email across real inboxes/devices | `POST /v1/emails/{emailId}/client-previews` | Fixed | | Run an inbox placement test (seed send) | `POST /v1/emails/{emailId}/inbox-placement-tests` | Fixed | | Audit an email (HTML, React Email JSX, or a saved design) for production readiness | `POST /v1/emails/audit` | Fixed: 5 when complete, 0 when partial | | Validate contact deliverability | `POST /v1/contacts/validate` | Fixed (per address) | | Validate on ingestion (opt-in) | `POST /v1/contacts` / `POST /v1/contacts/import` / `POST /v1/contacts/import-csv` with `validate: true` | Fixed (per address) | | Semantic brand-image search | `GET /v1/brand/images?q=…` | Free | | Generate / animate a GIF | `POST /v1/content/gif` (`from: "prompt" \| "image" \| "video"`) | Fixed | | Optimize / resize an image | `POST /v1/content/transform` (`operation: "optimize" \| "resize"`) | Fixed | | Render HTML to a PNG | `POST /v1/content/html-to-png` | Fixed | | Add an image to the brand image library, from a URL or a local file | `POST /v1/content/add-image`, `POST /v1/content/image-uploads` | Free | | Run Brew Insights (**Run now** or **Run deep analysis**) | None: app only | Usage (tokens) | | Read Brew Insights findings | `GET /v1/insights`, `GET /v1/insights/{insightId}` | Free | Everything else is **free**: all reads (including `GET /v1/brand/images`, with or without `q`) and deleting a brand image (`DELETE /v1/brand/images/{assetId}`). A [Brew Insights](/analytics/insights#what-a-run-costs) run in the app bills the same way. It opens a Brew chat, which bills the tokens it uses. The API has no route that starts a run. Sending email costs no credits, and that includes test emails. Every delivered email, tests included, counts toward your plan's monthly email sends (`emailSends`) instead. ### How the Cost Is Set For **fixed** operations the cost is published and does not vary with output size. The authoritative number for a call is its `X-Credit-Cost` response header. For **usage-metered** operations the charge equals the real token/image cost the work incurred (no header). The full per-operation metering table is available machine-readably at **`GET /v1/help`** → `credits.operations`. > [!NOTE] > > Fixed-cost calls are **value-aligned**. You are never charged for an empty result. The client-preview render bills only when at least one client produces a screenshot, and contact validation bills only when at least one address is checked. If those operations produce nothing, the call returns a retryable `503 SERVICE_UNAVAILABLE` and is not billed. > > Email audits return `200` for both outcomes. A complete audit charges 5 credits and returns `X-Credit-Cost: 5`. A partial audit preserves the checks that finished, returns `completion.score: null` and `X-Credit-Cost: 0`, and can be retried with the same idempotency key. ### Per-Address Metering Contact validation is metered **per address**: the `X-Credit-Cost` for a call is the per-address cost times the number of addresses you submit (for example validating 100 addresses charges 100× the unit cost). See `GET /v1/help` → `credits.operations` for the current per-address unit. The same rate applies to the opt-in `validate: true` flag on `POST /v1/contacts`, `POST /v1/contacts/import` and `POST /v1/contacts/import-csv`. Inline validation supports up to 100 submitted contacts or CSV data rows. It meters each submitted JSON contact or CSV data row, including skipped CSV rows and repeated addresses. Larger submissions save contacts first, with no request-level validation charge; their background validation meters per address as it runs. ### Running These from the Dashboard Most of these operations are also runnable from the [API catalog](/api-reference/api/api-catalog), where the cost sits on the row before you run it. A catalog run is a real call: it charges the same as one from your backend. The catalog is a subset, so the ingestion-time `validate: true` flag, email import, semantic brand-image search, image generation, and add-image are API-only. ## Check Your Balance: `GET /v1/usage` There is no dry-run cost preview. Credit-metered calls just charge on success; if you want to know what you can afford before you call, read your balance from the billing surface: ```bash theme={null} curl "https://brew.new/api/v1/usage" \ -H "Authorization: Bearer brew_…" ``` ```jsonc theme={null} { "plan": { "key": "pro", "name": "Pro" }, "credits": { "limit": 500, "used": 260, "remaining": 240 }, "emailSends": { "limit": 50000, "used": 1200, "remaining": 48800 }, "period": { "start": "2026-06-01T00:00:00.000Z", "end": "2026-07-01T00:00:00.000Z" } } ``` A `null` `limit` / `remaining` means **unlimited**. `credits` is the AI/media balance; `emailSends` is your monthly delivery allowance. Both reset at the `period.end` boundary. Billing belongs to the organization, so `GET /v1/usage` needs an organization-scoped key or connection. A key bound to one brand gets `403 ORG_SCOPE_REQUIRED`, whatever its permission scopes. See [Organization and Brand Scope](/api-reference/api/organization-and-brand-scope). `credits.remaining` is the plan credits left this period plus any bonus credits on the organization, minus credits held by in-flight audits. `credits.limit` is what the organization was granted for the period: the plan allowance plus your bonus credits, counting bonus already spent once the plan ran out, so `limit - used` is `remaining` (plus any held credits). If a plan was overdrawn with no bonus behind it, `used` exceeds `limit` and `remaining` is `0`. ## What a Real (Charged) Call Reports A successful **fixed**-cost call charges the published cost **exactly once** and returns two headers: | Header | Meaning | | - | - | | `X-Credit-Cost` | Credits charged for this call. | | `X-Credits-Remaining` | Balance after the charge: the same number as `credits.remaining` on `GET /v1/usage`. | **Usage-metered** calls (email generate/edit, image generation) bill the actual model usage to your account and do **not** return these headers. Read your balance from `GET /v1/usage` before and after to see the delta. Charging follows the API's replay contract: a retry with the same `Idempotency-Key` is not charged again. See [Idempotency](/api-reference/api/idempotency). ## Errors Credit failures use the standard envelope. See [Errors](/api-reference/api/errors) for `INSUFFICIENT_CREDITS`, `SERVICE_UNAVAILABLE`, and the recovery fields. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Data Model Source: https://docs.brew.new/api-reference/api/data-model The entities behind Brew's Public API v1, how they link, and what every identifier looks like, for builders joining sends, runs, and events. Every v1 resource hangs off an organization or one of its brands, and every row that one resource writes about another carries that other resource's id. This page is the map: which entities exist, which id each one answers to, and how a fire, a run, a send, and its events join up. Per-endpoint request and response shapes live in the generated OpenAPI reference. ## The Entity Map ```mermaid theme={null} erDiagram Organization ||--o{ Brand : owns Organization ||--o{ ApiKey : mints Organization ||--o{ Template : shares Brand ||--o{ Domain : sends_from Brand ||--o{ Contact : holds Brand ||--o{ Field : defines Brand ||--o{ Audience : segments Brand ||--o{ Email : designs Brand ||--o{ Trigger : listens Brand ||--o{ Automation : runs Brand ||--o{ Send : delivers Brand ||--o{ Integration : connects Brand ||--o{ Chat : records Brand ||--o{ Insight : surfaces Contact }o--o{ Field : customFields Audience ||--o{ AudienceRun : launches Email ||--o{ EmailVersion : versions Email }o--o| EmailGroup : grouped_in Trigger ||--o| PayloadContract : declares Trigger ||--o{ TriggerInstance : fires TriggerInstance ||--o{ AutomationRun : starts Automation ||--o{ AutomationVersion : versions Automation ||--o{ AutomationRun : executes AutomationVersion }o--o{ EmailVersion : sendEmail_nodes AutomationVersion }o--o{ Domain : sends_from Send }o--|| Email : of Send }o--o| Domain : via Send }o--o| Audience : targets Send ||--o{ SendEvent : produces AutomationRun ||--o{ Send : delivers AutomationRun ||--o{ SendEvent : produces SendEvent }o--o| Automation : attributed_to Organization { string usage "GET /v1/usage" } Brand { string brandId } Send { string sendId string kind "campaign | automation" string automationRunId "automation rows: the run that delivered it" string triggerInstanceId "automation rows: the fire behind the run" } Contact { string email string consent "source, capturedAt, policyVersion?, evidence?" } AutomationRun { string automationRunId string automationVersionId "the version it executed; a valid publish pin" string definitionHash "sha256 graph fingerprint" string triggerInstanceId } TriggerInstance { string triggerInstanceId "tin_" } ``` Two entities are organization-wide: templates (a shared design, addressed by `emailId`) and usage. Everything else belongs to one brand. A brand-scoped API key names its brand implicitly; an organization-scoped key names it per call with `X-Brand-Id`. See [Organization and brand scope](/api-reference/api/organization-and-brand-scope). ## What Each Entity Holds * **Brand** (`brandId`): the tenant every other row belongs to. It holds domains, contacts, audiences, designs, triggers, automations, and sends. * **Domain** (`domainId`): a verified sending domain. A send and every `sendEmail` node name the domain they deliver from. * **Contact** (`email`): one recipient with its core columns, `customFields` keyed by field name, and an optional `consent` record (`source`, `capturedAt`, `policyVersion`, `evidence`). * **Field** (`fieldName`): the definition behind a custom field, typed once per brand. * **Audience** (`audienceId`, or the literal `all` on a send for every subscribed contact): a saved filter over contacts. Launching a manual-audience automation against one produces an **audience run** (`audienceRunId`). * **Email** (`emailId`): a design and its versions (`emailVersionId`), filed under a group (`groupId`, or `ungrouped`). Teammates' open comment threads on it (`commentId`) hold messages (`messageId`). * **Trigger** (`triggerEventId`): a named event your systems fire. Its payload contract (`contractHash`, `version`, `enforcement`) validates each fire, and each fire is recorded as a **trigger instance** (`triggerInstanceId`) that lists the runs it started. * **Automation** (`automationId`): the graph, versioned (`automationVersionId`; `liveAutomationVersionId` is the version that runs). Each `sendEmail` node (`nodeId`) pins an `emailId`, an `emailVersionId`, and a `domainId`. * **Automation run** (`automationRunId`): one execution of one automation for one recipient. It carries the version it ran, its `definitionHash`, the `triggerInstanceId` that started it, and per-node `logs`. * **Send** (`sendId`): the unit of delivery. `kind: campaign` rows carry `emailId`, `emailVersionId`, `domainId`, and the audience or inline recipients. `kind: automation` rows add `automationId`, `nodeId`, and `automationRunId`, plus `triggerInstanceId` when a fire started the run or `audienceRunId` when a manual-audience launch did. * **Event**: one delivery or engagement event, stamped with the send, design, automation, node, run, fire, and audience run it belongs to. * **Insight** (`insightId`): one finding Brew Insights keeps about the brand's email, with the frozen metrics behind it and the `subject` it is about, such as one send. See [Read Brew Insights](/api-reference/guides/read-brew-insights). ## Identifiers | Identifier | Shape | Notes | | - | - | - | | emailId, emailVersionId | opaque, 21 chars (older designs: 36-char UUID) | The design and one persisted version of it. Returned by every generate, import, edit and restore. | | automationId, automationVersionId | opaque, 21 chars | Stable across versions; `liveAutomationVersionId` is the version publish serves. | | automationRunId | opaque, 32 lowercase alphanumerics | One per run of one automation for one recipient. | | sendId | campaign: opaque 21 chars; automation per-recipient: `as_` prefix; audience-run node: `arn_` prefix | The analytics join key. `kind` on the row says which. | | audienceRunId | `arun_` prefix | One manual-audience launch of an automation. | | triggerInstanceId | `tin_` prefix, 4 to 64 chars | One inbound fire; `GET /v1/automations/trigger-instances/{triggerInstanceId}` reads it, and `GET /v1/automations/runs?triggerInstanceId=` lists the runs it started. | | triggerEventId | caller-supplied, up to 256 chars (a 21-char opaque id when omitted); integration triggers are composite `provider:...` | URL-encode composite ids in paths. | | groupId | `grp_` prefix, or the literal `ungrouped` | Email folders. | | brandId, domainId, audienceId, keyId | opaque, 32 lowercase alphanumerics | `audienceId` also accepts the literal `all` on `POST /v1/sends` (every contact in the brand). | | chatId | opaque, 21 chars | A Brew chat, for `GET /v1/chats/{chatId}`. | | insightId | opaque, 32 lowercase alphanumerics | One finding of the insight engine, for `GET /v1/insights/{insightId}`; the app opens it at `/insights/`. | | commentId, messageId | `cmt_` / `cmm_` prefix, then 21 chars | A comment thread on a design and one message in it (`GET /v1/emails/{emailId}/comments`); the app opens a thread with `?commentId=`. | | notificationId | `ntf_` + 20 lowercase hex chars | A notification (`GET /v1/notifications`): a one-way hash, stable for the row’s life. Response only. | | uploadId | `imgup_` + 21 chars | A local-file image upload from `POST /v1/content/image-uploads`, finished by `POST /v1/content/add-image`; expires after 15 minutes. | | assetId | 8 lowercase hex chars, derived from the asset URL | A logo or image of the brand library (`GET /v1/brand/images`); the app opens it at `/assets?image=`. | | email, fieldName | caller-defined | Contacts are keyed by address and custom fields by name; URL-encode in paths (`jane%40example.com`). | | Idempotency-Key | caller-defined, up to 100 chars | Namespaced per organization server-side; 24-hour window. | Treat every identifier as opaque. Prefixes such as `as_`, `arn_`, `arun_`, `tin_`, and `grp_` are stable, but they are not a contract to parse: the `kind` field on a send row says what kind of send it is. ## From a Fire to an Inbox The join keys above let you follow one event end to end: 1. `POST /v1/automations/triggers/{triggerEventId}/fire` answers with a `triggerInstanceId` and the `automationRunIds` it started. 2. `GET /v1/automations/trigger-instances/{triggerInstanceId}` shows the fire's `state` and the same run ids; `GET /v1/automations/runs/{automationRunId}?include=logs` shows one run node by node. 3. `GET /v1/sends?automationRunId={automationRunId}` lists that run's per-recipient sends (`kind: automation`), each with its `nodeId` and `triggerInstanceId`. 4. `GET /v1/sends/{sendId}?include=events` reads one send with its recipient events, and `GET /v1/analytics/events?automationRunId={automationRunId}` reads every event the run produced. For a one-off campaign the chain is shorter: `POST /v1/sends` returns the `sendId`, `GET /v1/sends?emailId={emailId}` lists the sends of one design, and the same `include=events` read applies. ## Related * [Pagination](/api-reference/api/pagination) for the list envelope every collection shares. * [Errors](/api-reference/api/errors) for the `*_NOT_FOUND` code each identifier answers with. * [Migrate to the new v1 surface](/api-reference/api/v1-migration) if you knew the pre-cleanup spellings. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # API Design Notes Source: https://docs.brew.new/api-reference/api/design-notes Why Brew's API uses idempotency, partial-success batches, and polling alongside email webhooks, with context for builders. Reference pages define the Brew API contract. These notes explain the choices behind a few cross-cutting behaviors so you can make better decisions when building around that contract. ## Why Every Retry Needs Idempotency A network timeout does not tell a caller whether the server finished a `POST`. Repeating the request can therefore create a second workflow run, send a second email, or charge for the same generation twice. A stable key lets Brew recognize the retry and replay the original result without doing the work again. A changed body must use a new key so a genuine new operation is not hidden as a retry. This is why idempotency matters most at boundaries where another system may redeliver an event or where a long-running request can outlive its connection: trigger fires, sends, email generation, and batch contact writes. See the [Idempotency](/api-reference/api/idempotency) reference for the exact window, conflict response, and key patterns. ## Why Batch Writes Allow Partial Success Rows in an import are independent. Rejecting a 1,000-row request because three addresses are malformed would make callers resend valid work and would hide the rows that need fixing. Brew validates each row, writes the valid rows, and reports the failures beside them so a caller can correct and retry only the bad rows. This keeps the batch endpoint useful for imports while leaving transaction semantics with the caller. If an application needs all-or-nothing behavior, validate and stage the input before calling the endpoint, or use a separate compensating workflow that knows which records it owns. The response does not identify which successful rows were newly inserted, so deleting every address from the input could remove pre-existing contacts. See [Batch operations](/api-reference/api/batch-operations) for the response shape and limits. ## Why Webhooks Complement Polling [Email webhooks](/api-reference/api/events-and-webhooks#outbound-email-webhooks) push delivery and engagement events to your receiver. Status reads still expose the durable send or run state for reconciliation and recovery if your receiver misses a notification. Automation run completion and other asynchronous jobs use polling. Keep the identifier returned by the accepted operation and follow [Async jobs & polling](/api-reference/api/async-jobs). ## Related * [Authentication](/api-reference/api/authentication): key lifecycle, scopes, and brand binding. * [Rate limits](/api-reference/api/rate-limits): per-route policies and `429` recovery. * [Errors](/api-reference/api/errors): the standard error envelope and code catalog. * [Credits](/api-reference/api/credits): credit costs and metering. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # API Errors Source: https://docs.brew.new/api-reference/api/errors The standard error envelope, the full Brew Public API v1 error code catalog, and recovery guidance for every code you can receive. Every non-2xx response from the Brew Public API v1 returns the standard JSON `error` envelope, including the trigger-fire endpoint, which now reports a bad payload as `400 INVALID_PAYLOAD` in that same envelope. Branch on the stable `code`, never on a human-readable message that can change. ## The Error Envelope ```json theme={null} { "error": { "code": "AUTOMATION_GRAPH_INVALID", "type": "invalid_request", "message": "\"Welcome\" references emailVersionId '4UoY9gMklcHCfqpTdHn58' which does not exist in this brand. (and 1 more graph issue)", "param": "nodes[0].config.emailVersionId", "suggestion": "Fix every issue reported in `details.issues` then resubmit.", "docs": "https://docs.brew.new/api-reference/api/errors", "retryAfter": 12, "details": { "issues": [/* ... */] } } } ``` | Field | Type | When set | | - | - | - | | `code` | string | Always. Stable identifier: branch SDK logic on this. | | `type` | enum | Always. One of `authentication_error \| authorization_error \| invalid_request \| not_found \| conflict \| rate_limit \| payment_required \| service_unavailable \| not_implemented \| internal_error`. | | `message` | string | Always. Human-readable summary. Can change. | | `param` | string? | When the failing field is known (for example `payloadSchema.fields`, `nodes[0].config.emailVersionId`). | | `suggestion` | string | Always. Concrete recovery hint. | | `docs` | string | Always. Deep-link to canonical reference. | | `retryAfter` | int? | On retryable `429` or `503` responses. Mirrors the `Retry-After` header (seconds). | | `details` | object? | Machine-readable extras (for example `details.blockers[]`, `details.issues[]`). | Every code on this page has a stable anchor at `#`, so `INSUFFICIENT_CREDITS` is addressable as [`/api-reference/api/errors#insufficient-credits`](/api-reference/api/errors#insufficient-credits). Link those anchors from support threads, runbooks, and agent prompts. Today the envelope's `docs` value is the page URL; appending the per-code fragment on the API side is an open question tracked in the repo notes. ### `details` Shape: `PUBLISH_VALIDATION_FAILED` (422) When `PATCH /v1/automations/{automationId}` with `{ published: true }` is blocked, `details.blockers[]` enumerates every node-level reason so callers can render a fix-it list. ```json theme={null} { "error": { "code": "PUBLISH_VALIDATION_FAILED", "type": "invalid_request", "message": "Add at least one Send Email action", "details": { "blockers": [ { "nodeId": "send_1", "nodeLabel": "Welcome", "severity": "error", "message": "\"Welcome\" is missing an inbox preview" } ] } } } ``` ### `details` Shape: `AUTOMATION_GRAPH_INVALID` (400) Before `POST /v1/automations` or `PATCH /v1/automations/{automationId}` writes a graph, the server checks the node ids and edges, refuses a graph the executor cannot walk, and verifies every referenced design and domain is brand-owned and ready. A failure answers `400 AUTOMATION_GRAPH_INVALID`: `message` and `param` name the first problem, and `details.issues[]` lists every problem the first failing check found. Each issue is `{ kind, code?, nodeId?, nodeLabel?, message }`, with `code` on a `structure` issue only. Branch on `kind`: ```json theme={null} { "error": { "code": "AUTOMATION_GRAPH_INVALID", "type": "invalid_request", "message": "Step \"Wait 1 day\" is not reachable from the trigger. (and 1 more graph issue)", "details": { "issues": [ { "kind": "structure", "code": "unreachable_node", "nodeId": "wait-1", "message": "Step \"Wait 1 day\" is not reachable from the trigger." }, { "kind": "structure", "code": "unreachable_node", "nodeId": "send-2", "message": "Step \"Follow-up\" is not reachable from the trigger." } ] } } } ``` | `kind` | Cause | | - | - | | `duplicate_node_id` | Two nodes share the same `id`. | | `connection_unknown_from` | `connection.from` points to a node that does not exist. | | `connection_unknown_to` | `connection.to` points to a node that does not exist. | | `connection_targets_trigger` | A connection targets the trigger node (triggers are entry-only). | | `connection_self_loop` | `connection.from === connection.to`. | | `email_not_found` | `emailVersionId` doesn't exist in this brand. | | `email_version_mismatch` | `emailVersionId` exists but belongs to a different `emailId`. | | `domain_not_found` | `domainId` doesn't exist in this brand. | | `domain_not_ready` | The domain is not verified for sending. | | `domain_purpose_not_allowed` | The domain's sending purpose does not allow automation email. | | `structure` | A topology fault the save refuses; `code` names it (`missing_trigger`, `multiple_triggers`, `duplicate_connection`, `edge_to_trigger`, `ambiguous_branch`, `invalid_branch`, `cycle`, `unreachable_node`). | ### `details` Shape: `INVALID_REQUEST` (400) When a request body or query fails validation with more than one problem, `details.issues[]` lists each one as `{ param?, message }`, at most 20. `param` is a dot path such as `nodes.0.config.emailVersionId`, and is left out for a problem at the top level. The error's own `param` and `message` still name the first problem. On a field that takes one of several shapes, such as a `mode` or `type` union, the problems reported come from the shape whose `mode` or `type` matched. With a single problem, `details` is absent. ```json theme={null} { "error": { "code": "INVALID_REQUEST", "type": "invalid_request", "message": "Invalid input: expected string, received undefined", "param": "name", "details": { "issues": [ { "param": "name", "message": "Invalid input: expected string, received undefined" }, { "param": "nodes.0.config.emailVersionId", "message": "Invalid input: expected string, received undefined" } ] } } } ``` ## Error Code Catalog Generated from the OpenAPI specification, so it lists every code the API can return and nothing it cannot. "Every operation" holds the codes any endpoint may answer with; the rest are grouped by the resource that raises them. Each code keeps its stable `#` anchor. ### Every operation | Code | HTTP | Type | Retry | What it means | What to do | | - | - | - | - | - | - | | `ACCOUNT_SUSPENDED` | 403 | `authorization_error` | never | The organization behind the credential is suspended. | The organization behind this credential is suspended. Contact [support@brew.new](mailto:support@brew.new); do not retry. | | `API_KEY_REVOKED` | 401 | `authentication_error` | after fixing the request or resource | The API key was revoked. | Create a new active API key and retry. | | `AUTHENTICATION_REQUIRED` | 401 | `authentication_error` | after fixing the request or resource | No API key or session accompanied the request. | Provide a valid API key or sign in with an organization session. | | `BRAND_ID_REQUIRED` | 400 | `invalid_request` | after fixing the request or resource | An organization-scoped credential called a brand-scoped operation without naming the brand. | List brands with GET /v1/brands, then name one with the X-Brand-Id header. There is no default brand. | | `BRAND_SCOPE_MISMATCH` | 403 | `authorization_error` | after fixing the request or resource | A brand-scoped credential named a brand other than the one it is bound to. | Omit the brand to use the one this credential is bound to, or use an organization-scoped credential to reach other brands. | | `IDEMPOTENCY_CONFLICT` | 409 | `conflict` | after fixing the request or resource | The same Idempotency-Key was reused with a different request body. | Reuse the original payload or send a new idempotency key. | | `IDEMPOTENCY_IN_PROGRESS` | 409 | `conflict` | later (transient) | A request with this Idempotency-Key is still executing. | Wait for the original request to finish, then retry the same key to replay its response. | | `INSUFFICIENT_CREDITS` | 402 | `payment_required` | after fixing the request or resource | The credit balance is below what this operation requires; `details.cost` is the amount needed. | Upgrade your plan or wait for the next billing period to reset. Check your balance up front with GET /v1/usage. | | `INSUFFICIENT_PERMISSIONS` | 403 | `authorization_error` | after fixing the request or resource | The credential lacks the permission scope the operation needs. | Use an API key or session with the required permission. | | `INSUFFICIENT_ROLE` | 403 | `authorization_error` | after fixing the request or resource | The caller lacks the access the operation needs: `param` names `member` (access to the brand) or `org_admin` (the organization role). | Ask an organization admin to run this, to add you to the brand, or to make you an admin. | | `INTERNAL_ERROR` | 500 | `internal_error` | later (transient) | An unexpected failure; the x-request-id header identifies it. | Retry the request. If it keeps failing, contact support with the x-request-id header. | | `INVALID_API_KEY` | 401 | `authentication_error` | after fixing the request or resource | The API key is malformed or unknown. | Check the API key format and retry with a valid active key. | | `INVALID_REQUEST` | 400 | `invalid_request` | after fixing the request or resource | The body or query failed validation: an unknown key, a wrong type, or a missing required field. `param` names the first offender; with more than one problem, `details.issues[]` lists each one (`{ param?, message }`, at most 20). | Fix the field reported in `param`, and every entry in `details.issues[]` when present, then retry. | | `METHOD_NOT_ALLOWED` | 405 | `invalid_request` | after fixing the request or resource | The path exists but not for this HTTP method; the Allow header lists the methods that do. | Use one of the methods named in the Allow header. | | `NO_ACTIVE_PLAN` | 402 | `payment_required` | after fixing the request or resource | Nothing entitles the organization because the trial ended, the plan was cancelled, or the last charge failed; `details.reason` is `NO_PLAN` or `PAYMENT_BLOCKED`, and no top up fixes it. | An organization admin must choose a plan, or update the payment method, at [https://brew.new/plan](https://brew.new/plan). Check the current state up front with GET /v1/usage. | | `NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | No v1 resource lives at this path. | Check the request path and HTTP method against the API reference. | | `NOT_IMPLEMENTED` | 501 | `not_implemented` | never | The operation is documented but not available yet. | Watch the changelog; do not retry. | | `ORG_SCOPE_REQUIRED` | 403 | `authorization_error` | after fixing the request or resource | The operation acts on the organization, so a brand-scoped credential cannot call it. | Create an organization-scoped API key in Settings, API, or reconnect MCP at the organization level. | | `PAYLOAD_TOO_LARGE` | 413 | `invalid_request` | after fixing the request or resource | The request body exceeds the route cap. | Reduce the payload size and retry. | | `RATE_LIMITED` | 429 | `rate_limit` | after `Retry-After` | The credential exhausted the rolling window for this route policy; Retry-After is when the oldest recorded request leaves, and the refused request does not take a slot. | Wait the Retry-After time, then retry the same request. | | `SERVICE_UNAVAILABLE` | 503 | `service_unavailable` | after `Retry-After` | A dependency the operation must consult (billing, the idempotency store) is temporarily unavailable, so the request was refused rather than run unmetered. | Retry the request after a short delay. | | `WRITE_CONFLICT` | 503 | `service_unavailable` | after `Retry-After` | Other writes to the same records kept conflicting with this one, so nothing was saved. | Wait the Retry-After time (a few seconds), then retry the same request. Spread out bursts of parallel writes to one brand. | ### Audiences | Code | HTTP | Type | Retry | What it means | What to do | | - | - | - | - | - | - | | `AUDIENCE_BUILD_ACTIVE` | 409 | `conflict` | later (transient) | The audience is being built, so neither it nor the hidden field its build stamps can be changed, copied, or deleted yet. | Wait for the build to finish (poll GET /v1/audiences/\{audienceId}?include=build), then retry. | | `AUDIENCE_BUILD_ALREADY_ACTIVE` | 409 | `conflict` | later (transient) | Too many audience builds are already in progress for the workspace. | Wait for the in-flight builds to finish (poll GET /v1/audiences/\{audienceId}?include=build), then retry. | | `AUDIENCE_EDIT_CONFLICT` | 409 | `conflict` | after fixing the request or resource | The audience changed since it was read; the update was not applied. | Reload the latest audience filters and retry. | | `AUDIENCE_MEMBERSHIP_NOT_EXPRESSIBLE` | 409 | `conflict` | after fixing the request or resource | The audience’s filters cannot add or remove these contacts exactly (for example, AND-combined conditions, or an OR branch that would still match). | Rewrite the audience with `filters` instead, or create a separate audience for these contacts. | | `AUDIENCE_NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | No audience with that id exists in the brand. | Use GET /v1/audiences to choose a saved audience, or send to explicit addresses. | ### Automations | Code | HTTP | Type | Retry | What it means | What to do | | - | - | - | - | - | - | | `AUTOMATION_GRAPH_INVALID` | 400 | `invalid_request` | after fixing the request or resource | The nodes and connections do not form a valid graph; `details.issues[]` lists each problem with its `nodeId` and `kind`. | Fix every issue reported in `details.issues` then resubmit. | | `AUTOMATION_IN_PROGRESS` | 409 | `conflict` | later (transient) | The automation is still being generated, so it cannot be deleted, tested or run yet. | Wait for the agent to finish generating the automation, or stop it in the app, then retry. | | `AUTOMATION_NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | No automation with that id exists in the brand. | List automations with GET /v1/automations. | | `AUTOMATION_NOT_PAUSABLE` | 422 | `invalid_request` | after fixing the request or resource | The automation runs against a manual audience, so it is paused through its runs, not the automation. | Use the audience-run control operations to pause or cancel an in-flight run. | | `AUTOMATION_NOT_PUBLISHED` | 422 | `invalid_request` | after fixing the request or resource | The automation is not live, so there is nothing to unpublish; with `stopInFlight: true` it also has no contacts in flight to stop. | Check the live state with GET /v1/automations/\{automationId}. | | `AUTOMATION_NOT_READY` | 422 | `invalid_request` | after fixing the request or resource | The saved automation cannot run as it is: generation failed, a step is incomplete or invalid, or a send step’s sender or the bound audience cannot be used; the message names the problem. | Fix what the message names, then retry: edit the automation with PATCH /v1/automations/\{automationId}, or verify a sending domain that lost verification with POST /v1/domains/\{domainId}/verify. | | `AUTOMATION_NOT_RUNNABLE` | 422 | `invalid_request` | after fixing the request or resource | The automation is triggered by an event, so it runs when its trigger fires and cannot be run against an audience. | Set its trigger to a manual audience with PATCH /v1/automations/\{automationId} to run it, or try the flow with POST /v1/automations/\{automationId}/test. | | `AUTOMATION_VERSION_CONFLICT` | 409 | `conflict` | after fixing the request or resource | The automation changed since the version you edited was read. | Read the latest automation version, reapply the intended changes, and retry the update. | | `AUTOMATION_VERSION_NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | The automation has no version with that id. | List versions with GET /v1/automations/\{automationId}?include=versions. | | `PUBLISH_VALIDATION_FAILED` | 422 | `invalid_request` | after fixing the request or resource | The saved graph cannot go live; `details.blockers[]` lists what publish requires. | Fix every blocker reported in `details.blockers` then PATCH again with \{ published: true }. | ### Brands | Code | HTTP | Type | Retry | What it means | What to do | | - | - | - | - | - | - | | `BRAND_DOMAIN_CONFLICT` | 409 | `conflict` | after fixing the request or resource | The organization already has a brand for that domain. | Find the existing brand with GET /v1/brands. | | `BRAND_LIMIT_REACHED` | 402 | `payment_required` | after fixing the request or resource | The plan allows no more brands. | Delete an unused brand, or upgrade the plan to add more brands. | | `BRAND_NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | The named or bound brand does not exist in this organization (unknown, deleting, or another organization). | List the brands this credential can reach with GET /v1/brands. | | `BRAND_NOT_READY` | 422 | `invalid_request` | later (transient) | The brand is still extracting and cannot generate email yet. | Poll GET /v1/brands/\{brandId} until it reports status: completed, then retry. | ### Chats | Code | HTTP | Type | Retry | What it means | What to do | | - | - | - | - | - | - | | `CHAT_NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | No chat with that id is visible to this credential’s brand. | Check the chatId, and that your key or connector is bound to that chat’s brand. | ### Contacts | Code | HTTP | Type | Retry | What it means | What to do | | - | - | - | - | - | - | | `BATCH_TOO_LARGE` | 422 | `invalid_request` | after fixing the request or resource | A batch write exceeds the per-request row cap. | Split the request into smaller batches and retry. | | `CONTACT_NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | No contact with that email exists in the brand. | Create the contact first with POST /v1/contacts. | | `INVALID_EMAIL` | 422 | `invalid_request` | after fixing the request or resource | A contact email is not a deliverable address shape. | Fix the address named in `param` and retry. | | `MISSING_EMAIL` | 422 | `invalid_request` | after fixing the request or resource | A contact row has no `email`, the primary key. | Provide an email address for every contact in the request body. | | `RESUBSCRIBE_NOT_ALLOWED` | 422 | `invalid_request` | after fixing the request or resource | The write set `subscribed` to true on a contact who unsubscribed, and Brew never re-subscribes an opt-out through the API, MCP or an import; `details.email` names the contact. | Drop `subscribed` from the write; a contact who opted out re-subscribes through their own action, or from their contact page in the Brew app once they ask. | ### Content | Code | HTTP | Type | Retry | What it means | What to do | | - | - | - | - | - | - | | `CONTENT_OPERATION_FAILED` | 422 | `invalid_request` | after fixing the request or resource | The media operation could not be completed for the given input. | Check the input described in the message and retry. | | `UPLOAD_IN_PROGRESS` | 409 | `conflict` | later (transient) | Another request is still adding this uploaded image. | Wait a few seconds, then call POST /v1/content/add-image with the same uploadId to receive its result. | | `UPLOAD_NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | The image upload is unknown, expired, or belongs to another brand. | Open a new upload with POST /v1/content/image-uploads, send the file, then add it within 15 minutes. | | `UPLOAD_NOT_RECEIVED` | 409 | `conflict` | after fixing the request or resource | The image upload has not received its file yet. | POST the raw file bytes to the uploadUrl, then call POST /v1/content/add-image with the same uploadId. | ### Contracts | Code | HTTP | Type | Retry | What it means | What to do | | - | - | - | - | - | - | | `CONTRACT_LOCKED_BY_PUBLISHED_AUTOMATIONS` | 409 | `conflict` | after fixing the request or resource | A published automation consumes this trigger, so the contract change must stay backward compatible: enforcement cannot tighten, a referenced field cannot be removed, retyped, or made required without a fallback, and an open object or list cannot gain a shape that drops a field a published automation reads. | Unpublish or detach the published automations that consume this trigger, or make a backward-compatible change (adding optional fields and loosening enforcement stay allowed). | ### Domains | Code | HTTP | Type | Retry | What it means | What to do | | - | - | - | - | - | - | | `DOMAIN_ALREADY_EXISTS` | 409 | `conflict` | after fixing the request or resource | The brand already has this domain. | Fetch the existing domain with GET /v1/domains. | | `DOMAIN_CLAIMED_ELSEWHERE` | 409 | `conflict` | after fixing the request or resource | The domain is registered in another Brew workspace. | Remove it from the other workspace first, or contact support to move it. | | `DOMAIN_NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | No domain with that id exists in the brand. | Use GET /v1/domains to choose a verified domain. | | `DOMAIN_NOT_READY` | 422 | `invalid_request` | after fixing the request or resource | The domain is not verified for sending. | Use a verified domain, or finish domain verification before sending. | | `DOMAIN_OTHER_BRAND` | 409 | `conflict` | after fixing the request or resource | The domain is attached to a different brand in this workspace. | Use that brand’s credential, or remove the domain from it first. | | `DOMAIN_PROVIDER_ERROR` | 422 | `invalid_request` | after fixing the request or resource | The sending provider rejected the domain. | Check the domain name is a valid, registrable domain and retry. | | `DOMAIN_PURPOSE_NOT_ALLOWED` | 422 | `invalid_request` | after fixing the request or resource | The sending domain is admitted for a different purpose than this send (marketing vs transactional). | Use a marketing domain for campaigns and audience sends. For transactional flows, wire the design into a published automation with a trigger and fire POST /v1/automations/triggers/\{triggerEventId}/fire. | | `DOMAIN_VERIFICATION_FAILED` | 422 | `invalid_request` | after fixing the request or resource | The DNS records are not published yet, so verification did not pass. | Confirm the DNS records from GET /v1/domains are published, then retry verify. | | `DOMAIN_VERIFIED_ELSEWHERE` | 409 | `conflict` | after fixing the request or resource | Another workspace already verified this domain. | Only unverified domains can be reclaimed. Remove it from the other workspace first. | ### Emails | Code | HTTP | Type | Retry | What it means | What to do | | - | - | - | - | - | - | | `AUDIT_NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | No saved audit matches that id in this brand, or its seven day retention has expired. | Use an auditId returned by POST /v1/emails/audit for this brand, or run a new audit. | | `COMMENT_NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | The design has no open comment thread with that id (resolving a thread deletes it). | List the design’s threads with GET /v1/emails/\{emailId}/comments and use a returned commentId. | | `EMAIL_GENERATION_FAILED` | 502 | `internal_error` | later (transient) | The email agent could not produce a design for the prompt. | Retry the request. If it keeps failing, simplify or rephrase the prompt. | | `EMAIL_GROUP_NAME_CONFLICT` | 409 | `conflict` | after fixing the request or resource | A group with that name already exists in the brand. | Pick a different name, or rename the existing group. | | `EMAIL_GROUP_NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | No email group with that id exists in the brand. | List groups with GET /v1/email-groups. | | `EMAIL_IMPORT_FAILED` | 422 | `invalid_request` | after fixing the request or resource | The supplied markup could not be imported as an email. | Check that `content` is valid for the declared `format` and retry. | | `EMAIL_IMPORT_PERSISTENCE_FAILED` | 502 | `internal_error` | later (transient) | The markup converted, but the design could not be stored; nothing was created. | Retry the import. If it keeps failing, contact support with the request id in the message. | | `EMAIL_IN_PROGRESS` | 409 | `conflict` | later (transient) | The design is being generated and cannot be edited or cloned yet. | Poll GET /v1/emails/\{emailId} until `status` is `ready`, then retry. | | `EMAIL_IN_USE_BY_AUTOMATION` | 409 | `conflict` | after fixing the request or resource | A published automation sends this design, so it cannot be deleted. | Unpublish the automation (or swap the design on its send step), then retry the delete. | | `EMAIL_NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | No email design with that id exists in the brand (cross-brand ids surface as 404). | List designs with GET /v1/emails. | | `EMAIL_NOT_READY` | 422 | `invalid_request` | later (transient) | The design is still generating or failed to generate, so it cannot be sent or cloned. | Use a completed design, or wait for generation to finish. | | `EMAIL_RESULT_UNAVAILABLE` | 409 | `conflict` | never | The email was saved, but its completed result could not be read for this response. | Read GET /v1/emails/\{emailId}?include=html with emailVersionId set to the saved value from error.details. Do not repeat the generation or edit: it already committed. | | `EMAIL_RUN_AMBIGUOUS` | 409 | `conflict` | after fixing the request or resource | A legacy generation run matches more than one saved version of the design. | List versions with GET /v1/emails/\{emailId}?include=versions and read the one you want by emailVersionId. | | `EMAIL_TEMPLATE_INVALID` | 400 | `invalid_request` | after fixing the request or resource | The design’s template could not be resolved for the audit (unresolved merge tags or broken syntax); `details` carries the telemetry. | Fix the template syntax or add fallbacks for unresolved values, then run the audit again. | | `EMAIL_VERSION_NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | The design has no version with that id. | List versions with GET /v1/emails/\{emailId}?include=versions and retry with a valid emailVersionId. | | `FLOW_NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | No public flow matches that slug: it is unknown, private, or one of its steps is no longer public. | List flows with GET /v1/flows and use a returned slug (the brand domain, for example notion.com). | | `LIQUID_RENDER_ERROR` | 422 | `invalid_request` | after fixing the request or resource | A Liquid template failed to parse or render. | Fix the template syntax, or supply the payload data the template references. Strict-mode fires fail on any unresolved variable; \| default: is the sanctioned fallback. | | `PREVIEW_NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | No rendering job matches that id in this brand, or its results have expired. | Use the previewId returned by POST /v1/emails/\{emailId}/client-previews, or start a new job. | | `REFERENCE_EMAIL_NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | The referenceEmailId names no design in the brand. | Check the referenceEmailId and retry with a valid email id. | | `TEMPLATE_NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | No public template matches that id. | List templates with GET /v1/templates and use a returned emailId as the templateId. | ### Fields | Code | HTTP | Type | Retry | What it means | What to do | | - | - | - | - | - | - | | `CORE_FIELD_IMMUTABLE` | 422 | `invalid_request` | after fixing the request or resource | The field is a core contact column and cannot be created, changed, or deleted as a custom field. | Use a custom field name instead. | | `FIELD_NAME_COLLISION` | 422 | `invalid_request` | after fixing the request or resource | Two keys in one request name the same contact field (`plan` and `Plan`, `team_size` and `Team Size`), so one value would be lost. | Send one of the two keys, or rename one so it names a different field. | | `FIELD_NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | No custom field definition with that name exists in the brand. | Create the field first with POST /v1/fields or use a field that already exists. | | `FIELD_TYPE_MISMATCH` | 409 | `conflict` | after fixing the request or resource | A value does not match the declared type of its custom field. | Send a value that matches the field's type. To change the type, delete the field (this clears its value on every contact) and create it again. | ### Figma | Code | HTTP | Type | Retry | What it means | What to do | | - | - | - | - | - | - | | `FIGMA_ACCESS_DENIED` | 403 | `authorization_error` | after fixing the request or resource | The connected Figma account cannot read the file or frame. | Grant the connected Figma account access to the file and selected frame, then retry. | | `FIGMA_CONVERSION_FAILED` | 422 | `invalid_request` | after fixing the request or resource | The frame could not be converted into an email design; `details.emailId` references the partial design. | Confirm the frame is a self-contained email design, then retry. | | `FIGMA_FRAME_NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | The file or frame no longer exists. | Confirm the file and frame still exist, then copy a fresh frame link from Figma. | | `FIGMA_NOT_CONNECTED` | 422 | `invalid_request` | after fixing the request or resource | No Figma account is connected to the brand. | Connect Figma on the Integrations page, then retry. | | `FIGMA_UNAVAILABLE` | 503 | `service_unavailable` | later (transient) | Figma did not answer in time. | Retry after a short delay. | | `FIGMA_URL_INVALID` | 400 | `invalid_request` | after fixing the request or resource | The Figma link is not a frame link with a node-id. | In Figma, select the email frame and copy its link. The URL must include a node-id. | ### Insights | Code | HTTP | Type | Retry | What it means | What to do | | - | - | - | - | - | - | | `INSIGHT_NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | No insight with that id is visible to this credential’s brand. | Use an insightId from the brand’s insight list, and check that your key or connector is bound to that insight’s brand. | ### Integrations | Code | HTTP | Type | Retry | What it means | What to do | | - | - | - | - | - | - | | `EXPORT_PROVIDER_ERROR` | 502 | `service_unavailable` | later (transient) | The connected provider refused or failed the template export; the status mirrors the provider reply. | Check the connection to the provider and retry the export. | | `EXPORT_UNSUPPORTED` | 422 | `invalid_request` | after fixing the request or resource | The export target rejected a field value it does not support. | Review the provider export fields and retry with a supported value. | | `INTEGRATION_NOT_CONNECTED` | 400 | `invalid_request` | after fixing the request or resource | The export target is not connected to this brand. | Connect the provider on the Integrations page, then retry the export. | ### Runs | Code | HTTP | Type | Retry | What it means | What to do | | - | - | - | - | - | - | | `AUDIENCE_RUN_NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | No manual-audience run with that id exists in the brand. | List runs with GET /v1/automations/audience-runs. | | `AUTOMATION_RUN_NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | No automation run with that id exists in the brand. | List runs with GET /v1/automations/runs. | | `INVALID_PAYLOAD` | 400 | `invalid_request` | after fixing the request or resource | The test payload does not match the trigger’s payload schema. | Send fields and types matching the trigger’s payloadSchema (see GET /v1/automations/triggers/\{triggerEventId}). | | `RUN_IN_PROGRESS` | 409 | `conflict` | later (transient) | A manual-audience run is already in progress for this automation. | Wait for the in-progress run to finish (or cancel it) before running again. | | `RUN_NOT_CANCELLABLE` | 409 | `conflict` | never | The run already reached a terminal state. | The run has already finished and can no longer be canceled. | | `RUN_NOT_PAUSABLE` | 409 | `conflict` | after fixing the request or resource | A manual-audience run that is scheduled, completed, failed, canceled or held at the plan limit cannot be paused. Pausing a run its operator already paused returns 200. | Only a running run can be paused; a run held at the plan limit resumes on its own, so cancel it to stop it. Check its status with GET /v1/automations/audience-runs/\{audienceRunId}. | | `RUN_NOT_PAUSED` | 409 | `conflict` | after fixing the request or resource | Only a paused or failed manual-audience run can be resumed; this one is scheduled, queued, running, completed or canceled. | Only a paused or failed run can be resumed. Check its status with GET /v1/automations/audience-runs/\{audienceRunId}. | | `RUN_NOT_RESUMABLE` | 409 | `conflict` | after fixing the request or resource | The run cannot be resumed: a failed run needs an undelivered send step, and a run held at the plan limit resumes on its own. | For a failed run, start a new run for the remaining steps instead. A run held at the plan limit needs no call: it resumes once the monthly send allowance has room, or you can cancel it. | | `RUN_START_FAILED` | 503 | `service_unavailable` | later (transient) | The workflow engine could not start the run right now. | The workflow engine was momentarily busy; retry the run in a few seconds. | | `RUN_STOP_FAILED` | 503 | `service_unavailable` | later (transient) | The previous run of this cohort could not be stopped. | Retry the resume in a few seconds, or cancel the previous run first. | ### Sends | Code | HTTP | Type | Retry | What it means | What to do | | - | - | - | - | - | - | | `CONSENT_REQUIRED` | 422 | `invalid_request` | after fixing the request or resource | An inline marketing recipient has no contact record with marketing consent and the send carried no consent provenance; details.recipients lists the addresses. | Create the contacts first with POST /v1/contacts carrying a consent record, or include consent provenance on the send to create them as subscribed contacts. | | `EMAIL_IMAGES_MISSING` | 422 | `invalid_request` | after fixing the request or resource | The email shows an image on cdn.brew\.new that does not exist, so it was not sent; `details.missingImages[]` lists each URL and the email it is in. | Replace or remove each image listed in `details.missingImages` in the email, then send again. | | `NO_ELIGIBLE_RECIPIENTS` | 422 | `invalid_request` | after fixing the request or resource | Every contact the send targets is unsubscribed, suppressed or undeliverable (or there are none), so an immediate send would deliver nothing; `details.eligibility` carries the counts. | Target an audience with subscribed, deliverable contacts, or schedule the send for a time when the audience will have them. | | `RECIPIENT_UNSUBSCRIBED` | 422 | `invalid_request` | after fixing the request or resource | An inline recipient is an existing contact who unsubscribed from marketing email; details.recipients lists the addresses and Brew never re-subscribes an opt-out. | Remove the unsubscribed addresses from the recipients; a contact re-subscribes only through their own action. | | `SEND_NOT_CANCELLABLE` | 409 | `conflict` | never | The send already finished, so there is nothing left to cancel. | Check the send status with GET /v1/sends/\{sendId} before canceling. | | `SEND_NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | No send with that id exists in the brand. | Use the sendId returned by POST /v1/sends, or list sends with GET /v1/sends. | | `SEND_NOT_PAUSABLE` | 409 | `conflict` | after fixing the request or resource | Only a delivering gradual send can be paused. | Check the send status with GET /v1/sends/\{sendId}. | | `SEND_NOT_RESUMABLE` | 409 | `conflict` | after fixing the request or resource | Only a manually paused gradual send can be resumed. | Check the send status with GET /v1/sends/\{sendId}. | | `SEND_QUOTA_EXCEEDED` | 402 | `payment_required` | after fixing the request or resource | The send or manual-audience run would exceed the plan’s monthly email volume. A send must fit at launch and draws from the allowance chunk by chunk as it delivers; `reserved` is only the batch going out right now (`details` carries `used`, `reserved`, `remaining`, `limit`, `planKey` and `requested`, and `periodEnd` when known). The window resets with the billing period. | Upgrade your plan for a higher monthly send volume, send to fewer recipients, or wait for the billing period to reset. | | `TEST_RECIPIENT_NOT_ALLOWED` | 422 | `invalid_request` | after fixing the request or resource | A test email can reach only a teammate with access to the brand, an address on a verified sending domain of the brand, or, for a signed-in person (not an API key), their own address or one on their company domain; details.recipients lists the refused addresses. | Send the test to a teammate on the brand (or yourself, when signed in), or verify the recipient’s domain under Domains. Use a campaign send for anyone else. | ### Triggers | Code | HTTP | Type | Retry | What it means | What to do | | - | - | - | - | - | - | | `NO_PUBLISHED_AUTOMATION` | 422 | `invalid_request` | after fixing the request or resource | The trigger fired, but no published automation listens for it, so nothing would run. | Publish an automation wired to this trigger, then fire again. GET /v1/automations/triggers/\{triggerEventId}/readiness reports this before you send a live event. | | `PAYLOAD_SCHEMA_EMAIL_REQUIRED` | 400 | `invalid_request` | after fixing the request or resource | A trigger payload schema must declare a required string `email` field. | Add \{ key: "email", type: "string", required: true } to payloadSchema.fields before retrying. | | `TRIGGER_ALREADY_EXISTS` | 409 | `conflict` | after fixing the request or resource | A trigger with that id already exists in the brand. | Reuse the existing trigger, or choose a different triggerEventId. | | `TRIGGER_EVENT_NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | No trigger with that id exists in the brand. | List triggers with GET /v1/automations/triggers. | | `TRIGGER_HAS_DEPENDENT_AUTOMATIONS` | 409 | `conflict` | after fixing the request or resource | Automations still reference the trigger; `details.referencingAutomations[]` names them. | Delete or detach the automations listed in `details.referencingAutomations` first, then retry DELETE. | | `TRIGGER_IMMUTABLE` | 422 | `invalid_request` | never | Integration-provisioned and Brew-event triggers cannot be changed through the API. | Only brew_api and custom triggers can be patched. Toggle integration per-event settings on the Integrations page instead. | | `TRIGGER_INSTANCE_NOT_FOUND` | 404 | `not_found` | after fixing the request or resource | No fired trigger instance with that id exists in the brand. | List recent fires with GET /v1/automations/trigger-instances. | | `TRIGGER_LIMIT_REACHED` | 409 | `conflict` | after fixing the request or resource | The brand already holds the maximum number of trigger events. | Delete an unused trigger with `DELETE /v1/automations/triggers/{triggerEventId}`, then retry. Each brand holds at most 100. | | `TRIGGER_NOT_FIREABLE` | 409 | `conflict` | never | Brew starts this trigger itself when its event happens, so it cannot be fired over the API. | Try the automation with its Test action (POST /v1/automations/\{automationId}/test) instead. | ### Row-Level Codes Batch contact writes (`POST /v1/contacts`, `POST /v1/contacts/import`, `POST /v1/contacts/import-csv`) can answer `2xx` and still reject individual rows. Those rejections arrive in a per-row `errors[]` array rather than as the response status, and each entry carries its own `code`: | Code | Meaning | | - | - | | `INVALID_EMAIL` | That row's address is not a deliverable shape. Fix the row and resubmit it. | | `DUPLICATE_EMAILS_IN_BATCH` | The same address appears more than once in one request. Keep one row per email. | | `FIELD_NAME_COLLISION` | Two keys in that JSON row name the same contact field (`plan` and `Plan`, `team_size` and `Team Size`), so one value would be lost. `field` is `customFields.`. Send one key, or rename one. See [Property Names](/audience/manage-contacts#property-names). | The accepted rows still apply, so read `summary` and `errors[]` rather than branching on the status alone. ## Warnings A `2xx` response can also carry a `warnings[]` array. A warning never fails the request; it reports something you probably want to fix. | Code | Operations | What it means | | - | - | - | | `CONSENT_RECORD_MISSING` | `createSend` | An inline recipient is a subscribed contact with no consent record, so the send proceeds on subscription alone; `field` names the address and PATCH /v1/contacts/\{email} records consent. | | `CONTACT_EXISTS_SKIPPED` | `importContacts`, `importContactsCsv` | The import ran with `onConflict` set to `skip` and this row names a contact that already exists, so the contact was left unchanged; `email` and `row` name it, and the row counts in `summary.skipped`. | | `CORE_FIELD_IGNORED` | `upsertContacts`, `importContacts` | A `customFields` key named a field Brew manages, such as `createdAt`, so its value was not stored while the rest of the contact was; `field` names the key, and sending the value under a custom field name keeps it. | | `CSV_COLUMN_IGNORED` | `importContactsCsv` | A CSV column was not imported, because the field it maps to is managed by Brew (such as `createdAt`) or because `mapping` fills the same core field from another column; `field` names the column, and mapping it to a custom field name keeps its values. | | `CSV_ROW_SKIPPED` | `importContactsCsv` | A CSV row was omitted for a missing/invalid email or a later duplicate; the last duplicate is kept for processing. Up to 100 row-specific warnings include `row` (the data row; header and blank lines not counted) and `email` when present; a final rowless warning counts further omissions. All omissions count in `summary.skipped`. | | `DATE_ORDER_ASSUMED` | `upsertContacts`, `importContacts`, `importContactsCsv`, `updateContact` | A date field held dates such as 03/04/2026 that read as either day/month or month/day, and nothing in the request settled the order, so they were read month/day, or in the order most of the field's dates use; `field` names the field, and YYYY-MM-DD dates or `dateOrder` on a CSV import choose it. | | `DRAFT_SAVED_NOT_LIVE` | `updateAutomation` | The update was saved as a new draft version; live traffic still serves the previously published version until you republish. | | `ENFORCEMENT_LOOSENED_WHILE_PUBLISHED` | `setTriggerContract` | Enforcement was loosened while published automations consume the trigger; tightening it back will be refused with CONTRACT_LOCKED_BY_PUBLISHED_AUTOMATIONS until they are unpublished or detached. | | `FIELD_TYPE_COERCED` | `upsertContacts`, `importContacts`, `importContactsCsv`, `updateContact` | A custom-field value was converted to its field's declared type before it was stored, such as the number 5 saved as the text 5 in a `string` field or `yes` saved as true in a `bool` field (a date sent as text to a `date` field is not reported); `field` names the field, `from` the type sent and `to` the type stored. Create the field with POST /v1/fields to pin its type up front. | | `NODE_ID_REPLACED` | `createAutomation`, `updateAutomation` | A node id in the request was stored under another id, because the trigger node is always `trigger` and an id shaped like `wait-3-days` (a node type, a hyphen and a slug) gets an opaque one; `field` names the node, the message gives the stored id, and connections point at it. Every other id is stored as sent. | | `RECIPIENTS_EXCLUDED` | `createSend`, `runAutomation` | Some contacts the send or manual-audience run targets are unsubscribed, suppressed or undeliverable and will be skipped; the message gives the counts by reason. | | `REQUIRED_FIELD_SATISFIED_BY_FALLBACK` | `setTriggerContract` | A required field declares a fallbackValue, so a payload that omits it passes in every enforcement mode and every recipient receives the fallback; `field` names it. | | `RESUBSCRIBE_SKIPPED` | `upsertContacts`, `importContacts`, `importContactsCsv` | A row set `subscribed` to true for a contact who unsubscribed, so its other fields were saved but the contact stays unsubscribed; `email` names the contact. | | `TRIGGER_EVENT_NOT_RECEIVED` | `updateAutomation` | The automation is live, but Brew has not received its trigger's event from the integration on its current connection, so it runs only once the source sends that event; the message says what to set up, and `field` is `triggerEventId`. | | `VALIDATION_SKIPPED` | `upsertContacts`, `importContacts`, `importContactsCsv` | The request set `validate` to true, but some or all of the saved addresses were not queued for background validation because they are unsubscribed or suppressed, or were validated in the last 30 days; the message gives the counts, and `validationJobId` is absent when none were queued. | ## SDK Error Handling (TypeScript) The official `@brew.new/sdk` throws a typed `BrewApiError` on every non-2xx response, exposing the full envelope: ```ts theme={null} import { BrewApiError, createBrewClient } from '@brew.new/sdk' const brew = createBrewClient({ apiKey: process.env.BREW_API_KEY! }) try { await brew.automations.triggers.fire( { triggerEventId: 'tri_signup', payload: { email: 'jane@example.com' } }, { idempotencyKey: `signup-${userId}-${eventTimestamp}` }, ) } catch (err) { if (err instanceof BrewApiError) { console.error('Brew error', { code: err.code, // 'TRIGGER_EVENT_NOT_FOUND' etc. type: err.type, // 'not_found' message: err.message, requestId: err.requestId, // include in support tickets param: err.param, suggestion: err.suggestion, docs: err.docs, retryAfter: err.retryAfter, }) if (err.code === 'RATE_LIMITED') { // back off, then retry } if (err.code === 'AUTOMATION_GRAPH_INVALID') { const issues = (err.details?.issues ?? []) as Array<{ kind: string; code?: string; nodeId?: string; nodeLabel?: string; message: string }> for (const issue of issues) { console.error(` ${issue.kind}${issue.code ? ` (${issue.code})` : ''} on ${issue.nodeId ?? 'the graph'}: ${issue.message}`) } } if (err.code === 'INVALID_REQUEST') { // Present only when the request had more than one problem. const issues = (err.details?.issues ?? []) as Array<{ param?: string; message: string }> for (const issue of issues) { console.error(` ${issue.param ?? '(top level)'}: ${issue.message}`) } } } throw err } ``` ## Branching Agent / SDK Logic on `code` Three rules: 1. **`code` is stable.** It's part of our public contract. We will not change the spelling of a code; we may add new ones. 2. **`type` is a coarse bucket** for default UX. Use `type === 'rate_limit'` to gate a retry; use `type === 'authentication_error'` to ask the user to re-issue the key. 3. **Never branch on `message`.** Operator-facing copy may change between releases. ## Related * [Rate limits](/api-reference/api/rate-limits): `429 RATE_LIMITED` + `Retry-After` cookbook. * [Idempotency](/api-reference/api/idempotency): `409 IDEMPOTENCY_CONFLICT` semantics. * [Authentication](/api-reference/api/authentication): `401` / `403` codes. * [Organization and brand credentials](/api-reference/api/organization-and-brand-scope): why `ORG_SCOPE_REQUIRED`, `INSUFFICIENT_ROLE`, and `INSUFFICIENT_PERMISSIONS` are three different problems. * [Migrate to the new v1 surface](/api-reference/api/v1-migration): the codes and statuses the v1 cleanup renamed. * [TypeScript SDK error handling](/sdks/typescript/error-handling): patterns + retry helpers. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Events and Webhooks Source: https://docs.brew.new/api-reference/api/events-and-webhooks Event-driven integration with the Brew Public API v1: fire automation triggers and receive signed email lifecycle webhooks. Send events into Brew to run automations. Subscribe to outgoing webhooks to receive email delivery and engagement events in your application. ## Direction Map (TL;DR) | Direction | Who calls who | Status | | - | - | - | | **You → Brew**: fire a custom event from your backend so Brew runs the matching automation | `POST /v1/automations/triggers/{triggerEventId}/fire { payload }` with an `Idempotency-Key` header | Shipped | | **You → Brew**: managed integration receivers (Clerk, Stripe, Shopify, Stytch, Supabase, WorkOS, RevenueCat) push their events INTO Brew through a Brew-hosted receive URL you configure once | Per-integration setup in the [Integrations tab](/integrations/integrations) | Shipped | | **Inside Brew**: Brew starts an automation itself when a contact unsubscribes | `POST /v1/automations/triggers/brew-events` returns the trigger to wire; see [Unsubscribe Events](/create-emails/automation-triggers#unsubscribe-events) | Shipped | | **Brew → You**: email delivery and engagement events | [Outbound Email Webhooks](#outbound-email-webhooks) | Supported | | **Brew → You**: live automation run logs | Poll the run resource | Polling | For automation run completion, use polling. See [Async jobs & polling](/api-reference/api/async-jobs). ## Inbound: You Call Brew ### Pattern: Fire a Custom Event The canonical agent / backend integration path: ``` your-backend → POST /v1/automations/triggers → mint triggerEventId your-backend → POST /v1/emails → mint email bodies (untyped designs) your-backend → GET /v1/domains → pick verified sending domain your-backend → POST /v1/automations → assemble graph (trigger → sendEmail → wait → …) your-backend → PATCH /v1/automations/{automationId} → { published: true } to go live your-backend → POST /v1/automations/triggers/{id}/fire → fire whenever the real-world event happens ``` The fire call: ```bash theme={null} curl -X POST https://brew.new/api/v1/automations/triggers/tri_signup/fire \ -H "Authorization: Bearer $BREW_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: signup-jane@example.com-1779292800" \ -d '{ "payload": { "email": "jane@example.com", "firstName": "Jane" } }' # → 202 { triggerInstanceId: "tin_...", triggerEventId: "tri_signup", # status: "triggered", automationRunIds: ["run_..."], # publishedAutomations: [...], counts: { automations: 1, skipped: 0 }, # warnings: [], receivedAt: "2026-04-08T12:34:56.789Z" } ``` Key invariants: * **`payload.email` is the contact key.** Every trigger's `payloadSchema.fields` MUST declare `{ key: 'email', type: 'string', required: true }`. The fire endpoint also upserts the contact from the declared top-level scalar fields the fire sent: `firstName` / `lastName` / `subscribed` land in core columns, and the rest land in `customFields` under the key's [folded camelCase name](/audience/manage-contacts#property-names) (with the field definition auto-created on the brand). A trigger can't declare two top-level fields that fold to one contact field, such as `plan` and `Plan`; see [Typed Payload Contracts](/api-reference/guides/typed-payload-contracts#store-a-contract). A field with `syncToContact: false` reaches the email only. Object and array fields are not stored on the contact; they stay available to the email as `{{ trigger.account.tier }}`. A field's `fallbackValue` fills the email only and is never written onto the contact (a `subscribed` fallback only sets the subscription of a new contact). A value the contact field's type refuses, such as `"abc"` for a `number` field, is not saved: the rest of the contact is, the automation still runs, and the response's `warnings[]` carries `{ code: "FIELD_TYPE_MISMATCH", field, expectedType, actualType }`. * **Use a stable `Idempotency-Key` when firing from a webhook.** See [Idempotency](/api-reference/api/idempotency) for the contract and [API design notes](/api-reference/api/design-notes#why-every-retry-needs-idempotency) for the duplicate-delivery rationale. * **The fire endpoint accepts and returns `202`**, with `automationRunIds[]` at the top level (no `details` wrapper), `notStarted[]` naming any matched automation that could not start and why, and the `triggerInstanceId` for the fire itself. A replay of the same `Idempotency-Key` answers `200` with `status: "replayed"` and the original run ids. Failures use the standard [error envelope](/api-reference/api/errors), so a bad payload is `400 INVALID_PAYLOAD`. Don't block on delivery. Poll the run with [Async jobs & polling](/api-reference/api/async-jobs). * **At least one bound automation must be Published.** Triggers are always-on, but emails only fire when at least one bound automation has `published: true`. If every bound automation is in Draft, the fire call returns `422 NO_PUBLISHED_AUTOMATION`. Publish the automation in the builder (or via `brew.automations.patch({ published: true })`) and retry. ### Pattern: Integration-Provisioned Triggers For events that originate inside another product (Clerk's `user.created`, Stripe's `customer.subscription.deleted`, Shopify's `orders/paid`, etc.), Brew can RECEIVE the integration's webhook directly (no code on your side). Setup is per-integration in the dashboard (the receiver URL is hosted at `/api/integrations//webhook/`). Once configured, the integration's events appear in `GET /v1/automations/triggers` with `provider: 'clerk' | 'stripe' | 'shopify' | …` and fire your published automations exactly like custom `brew_api` triggers. You can bind any of these to an automation. Supported providers today: | Provider | Common events | | - | - | | Clerk | `user.created`, `organization.created`, `subscription.created` | | Stripe | `customer.subscription.created/updated/deleted`, `invoice.paid`, `customer.deleted` | | Shopify | `orders/paid`, `customers/create`, `customers/update` | | Stytch | `direct.user.create`, `direct.user.delete`, `direct.organization.create` | | Supabase | `auth.user.created`, `auth.user.signed_in`, `auth.user.deleted` (auth.users only) | | WorkOS | `user.created`, `dsync.user.created`, `organization.created` | | RevenueCat | `INITIAL_PURCHASE`, `RENEWAL`, `CANCELLATION`, `EXPIRATION` | Each provider's adapter normalizes into a flat `{ email, …provider-specific fields }` payload that flows through the same fire pipeline as `brew_api` triggers. **Inbound integration webhooks also auto-upsert the contact** using a richer per-provider mapper that lands under provider-prefixed camelCase custom field names (for example `clerkUserId`, `stripeCustomerId`). ## Outbound Email Webhooks Receive email lifecycle and engagement events at your HTTPS endpoint. Create an endpoint in **Settings → Webhooks**, or use the public API. Each endpoint belongs to one brand. Organization API keys select the brand with `X-Brand-Id`; brand API keys use their existing brand. Management requires the `emails` scope. Merging brands that have separate registered webhook configurations currently requires Brew support. Deleting every endpoint does not remove retained configuration state or unblock that merge. ### Manage in Settings 1. Open **Settings → Webhooks** and choose the brand whose events you want. 2. Expand **Add webhook endpoint**, enter your public HTTPS receiver URL, select the email events, and choose **Add endpoint**. 3. Store the displayed signing secret on your server, then hide it. Verify the unmodified request body before processing a notification. 4. Choose a subscribed event beside the endpoint and select **Send test event**. Test fixtures use example data and do not send an email or change email stats. 5. Open **Configure and inspect** to edit the endpoint and view delivery history. Select a delivery to inspect its payload and HTTP attempts. Use **Refresh** to check a queued test or replay. Expired payloads cannot be replayed. 6. After fixing a receiver, choose **Replay webhook** for the affected delivery. Replay queues the same notification and confirms that it was accepted; the receiver's response appears in delivery history. Enable/disable, signing-secret rotation and deletion are available on each endpoint. Rotation and deletion ask for confirmation. If endpoint loading fails, use **Refresh** to retry without changing your configuration. | Event | Meaning | | - | - | | `email.sent` | The sending provider accepted the message for delivery. | | `email.delivered` | The recipient mail server accepted the message. Inbox placement is unknown. | | `email.delivery_delayed` | A temporary delivery failure occurred. Delivery may be retried. | | `email.bounced` | The provider reported a final recipient delivery rejection. | | `email.complained` | The provider received a spam complaint for the message. | | `email.failed` | The provider reported an email failure or definitively rejected a recipient before acceptance. Recipient bounces are separate. | | `email.opened` | An open tracking signal was observed. | | `email.clicked` | A tracked link request was observed. | Open and click signals can come from privacy proxies or security scanners. They are observations, not proof of a person reading the message. Brew's reporting applies its own bot classification and unique counts. Some repeated pixel refetches are throttled before they create events. Internal mail, test sends and unsupported event types do not produce customer webhook events. ### Create an Endpoint ```ts theme={null} import { createBrewClient } from '@brew.new/sdk'; const brew = createBrewClient({ apiKey: process.env.BREW_API_KEY!, brandId: 'your_brand_id', }); const webhook = await brew.webhooks.create({ endpoint: 'https://example.com/webhooks/brew', events: ['email.delivered', 'email.bounced', 'email.complained'], }); // Store webhook.signing_secret in your application's secret manager. ``` Endpoints must resolve to public HTTPS addresses. Credentials in URLs, custom ports and redirects are unsupported. Endpoint creation does not backfill historical analytics events. Subscriptions apply when an event is dispatched, so an endpoint created while older dispatch work is pending can receive that work. For a manual retry after an uncertain creation response, pass the same `idempotencyKey` in the SDK method's second argument for the unchanged request. Use a new key for a changed request or a new creation after confirmed success. ### Payload ```json theme={null} { "type": "email.delivered", "created_at": "2026-10-26T12:00:02.000Z", "data": { "email_id": "provider_message_123", "created_at": "2026-10-26T12:00:00.000Z", "from": "Acme ", "to": ["reader@example.net"], "subject": "Welcome", "brew": { "event_id": "canonical_event_123", "schema_version": 1, "recipient": "reader@example.net", "send_id": "your_send_id", "design_id": "your_email_design_id" } } } ``` The envelope and event-specific field names follow Resend conventions. Brew extensions live under `data.brew`. * Top-level `created_at` is event occurrence time. `data.created_at` is message acceptance time from the delivery mapping or provider payload when available; otherwise it falls back to event occurrence time. * `data.email_id` identifies one provider message, with a Brew delivery or event ID fallback for failures before provider acceptance. It is not the reusable email design ID. Use `data.brew.design_id` and `data.brew.send_id` to correlate with Brew resources. * Recipient-specific events include only the affected recipient in `to`. * Bounce details use `bounce.type`, `bounce.subType`, `bounce.message`, and optional `bounce.diagnosticCode`, an array of SMTP response strings. Failures use `failed.reason`. Link requests use `click.link` and optional tracking metadata. * A definitive rejection before provider acceptance emits `email.failed` with a safe reason. Analytics count it as a pre-send skip, so it cannot reduce the pending count of other accepted messages. Rendering, admission, and sender configuration failures do not produce email lifecycle webhooks. * Missing legacy envelope fields are omitted. Message bodies, attachment contents and internal provider metadata are excluded. Secret-rendered subjects and full links are redacted. Secret-rendered messages also omit free-form bounce messages and diagnostic strings, retaining the bounce classification. ### Verify Requests Read the original request body as text before parsing it. Use the endpoint's signing secret and the `svix-id`, `svix-timestamp`, and `svix-signature` headers. `verifyWebhook` needs no API key, so a receiver does not create a client. ```ts theme={null} import { BrewWebhookVerificationError, verifyWebhook } from '@brew.new/sdk'; export async function POST(request: Request) { let event; try { event = await verifyWebhook({ payload: await request.text(), headers: { id: request.headers.get('svix-id') ?? '', timestamp: request.headers.get('svix-timestamp') ?? '', signature: request.headers.get('svix-signature') ?? '', }, webhookSecret: process.env.BREW_WEBHOOK_SECRET!, }); } catch (error) { if (error instanceof BrewWebhookVerificationError) { return new Response(null, { status: 400 }); } throw error; } // Durably enqueue the verified event, deduplicating by the svix-id header. // Acknowledge only after your durable write completes. return new Response(null, { status: 204 }); } ``` Verification rejects altered payloads and timestamps outside a five-minute window; the error's `reason` says which check failed. Brew adds event types over time, so acknowledge a `type` your handler does not know instead of failing it. You can also verify with the `svix` library. Store secrets on the server. ### Retries and Replay Delivery is at least once, with no ordering guarantee. Deduplicate on the `svix-id` header. `data.brew.event_id` names the underlying email fact; test events (`data.brew.test: true`) all reuse one fixture `event_id`, so leave them out if you deduplicate on it. Retries and replays keep the original `svix-id`, event identity and payload. Replaying a webhook never sends another email. Return `2xx` within 30 seconds after durably accepting the event. Other statuses, including redirects, count as failures. The default retry intervals after failed attempts are 5 seconds, 5 minutes, 30 minutes, 2 hours, 5 hours, 10 hours, and another 10 hours. Persistently failing endpoints can be disabled automatically. In **Settings → Webhooks**, inspect the payload, HTTP response, attempt history and next retry. Replay a delivery after fixing your receiver. Payloads for customer events are retained for 30 days; replay is available while provider retention allows it. Synthetic fixtures contain example data and may follow a different retention period. Signing-secret rotation preserves the previous key during the provider's grace period so you can update your receiver. ### API Operations | Method | Path | Purpose | | - | - | - | | `GET`, `POST` | `/v1/webhooks` | List or create endpoints. Creation accepts `endpoint`, `events`, and optional `description`. | | `GET`, `PATCH`, `DELETE` | `/v1/webhooks/{webhookId}` | Read, edit or remove an endpoint. PATCH supports `endpoint`, `events`, `description`, and `status: enabled` or `disabled`. | | `POST` | `/v1/webhooks/{webhookId}/rotate-secret` | Rotate the signing secret. | | `POST` | `/v1/webhooks/{webhookId}/test` | Send a synthetic fixture for the requested `type`. | | `GET` | `/v1/webhooks/{webhookId}/events` | List deliveries with payload, status and next attempt. | | `GET` | `/v1/webhooks/{webhookId}/events/{eventId}/attempts` | Inspect delivery attempts and responses. | | `POST` | `/v1/webhooks/{webhookId}/events/{eventId}/replay` | Replay a webhook notification. | `eventId` in the delivery-history paths is the message `id` returned by the webhook events list. List operations accept `limit` and `cursor` and use Brew's standard pagination envelope. POST operations accept `Idempotency-Key`. Synthetic test events have `data.brew.test: true` and never affect email stats. Aggregate statistics, deliverability threshold alerts, inbound email, contact and automation lifecycle webhooks are outside this release. ## Related * [Authentication](/api-reference/api/authentication) * [Async Jobs and Polling](/api-reference/api/async-jobs) * [Idempotency](/api-reference/api/idempotency) * [Integrations](/integrations/integrations) ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Idempotency Source: https://docs.brew.new/api-reference/api/idempotency Reuse stable idempotency keys for supported Brew API writes. Learn the replay windows, conflict handling, and safe retry key patterns. Supported `POST` endpoints use the `Idempotency-Key` HTTP header. Most writes replay the cached response for 24 hours; [trigger fires](#replayed-trigger-fires) replay for 90 days. The same key with a different body returns `409 IDEMPOTENCY_CONFLICT`. A key is shared by the HTTP API and [MCP](/api-reference/mcp/authentication-and-scoping#safe-retries-idempotency). A write retried over the other interface with the same inputs and key replays its first result. One replay can look different from a normal HTTP result. When an MCP `create_email` call outlasts its wait, it returns `status: "generating"`, `emailId`, and `runId`. An HTTP retry of `POST /v1/emails` with the same key replays the accepted result instead of generating a second design. Poll `GET /v1/emails/{emailId}?runId={runId}` until the design is `ready` or `failed`. ## Contract | Property | Value | | - | - | | Header | `Idempotency-Key: <≤ 100 chars>` | | Methods | Supported `POST` endpoints. Check the endpoint schema; image-upload handshakes do not support replay. | | Window | 24 hours from the first request. A [trigger fire](#replayed-trigger-fires) key lasts as long as the fire's receipt: 90 days. | | Same key + same body | Returns the original cached response (same status, same body, same headers). A [trigger fire](#replayed-trigger-fires) is the one exception. | | Same key + different body | `409 IDEMPOTENCY_CONFLICT`. The same body on another resource of the route, such as a different id in the path, conflicts the same way. | | Different key | Treated as a fresh request. | | Scope | Namespaced per organization, brand, and operation, with the request's path ids part of what the key is bound to. One tenant's key cannot collide with another's. | | Surfaces | Shared by HTTP and MCP. `Idempotency-Key` and the MCP `idempotency_key` argument are the same key. | ## Why Every Retry Needs It Stable keys prevent duplicate work when a network error or event redelivery makes a caller repeat a `POST`. See [API design notes](/api-reference/api/design-notes#why-every-retry-needs-idempotency) for the rationale and this page's contract for the exact behavior. ## In-Progress Requests and Storage Outages For writes using the response cache, a running request holds its key for up to 15 minutes. A retry during that time returns `409 IDEMPOTENCY_IN_PROGRESS`. Wait, then replay with the same inputs and key. Replay guarantees depend on the idempotency store. If that store is unavailable, six writes fail closed. They return a retryable `503 SERVICE_UNAVAILABLE` with a `Retry-After` header: * `POST /v1/sends` * `POST /v1/emails/audit` * `POST /v1/emails/{emailId}/inbox-placement-tests` * `POST /v1/automations/{automationId}/test` * `POST /v1/automations/{automationId}/run` * `POST /v1/automations/triggers/{triggerEventId}/fire` Other writes using it can run without deduplication. For another write that must never repeat, disable automatic retries and check whether the first request succeeded before retrying. ## Replayed Trigger Fires `POST /v1/automations/triggers/{triggerEventId}/fire` says when a response is a replay. The first fire answers `202` with `status: "triggered"`. A repeat answers `200` with `status: "replayed"` and the original `triggerInstanceId` and `automationRunIds`. No new runs start. The MCP `fire_trigger_event` tool reports a replay the same way. A fire key is matched against the stored trigger receipt and keeps replaying for its 90-day retention period. Use one key per business action and never reuse a key for a different fire. The fire takes its key only from the `Idempotency-Key` header. A body `idempotencyKey` field is rejected with `400 INVALID_REQUEST`. ## Recommended Key Patterns The key MUST be stable per logical operation. Common recipes: | Operation | Recommended key | | - | - | | Trigger fire from a webhook | `--` (for example `signup-user_123-1779292800`) | | Trigger fire from an internal job | `--` | | Campaign send | `send---` | | Email generate from a chat | `email-gen--` | | Batch contact upsert | `contacts-batch-` | | Cron-driven daily blast | `daily-promo-` | Anti-patterns to avoid: * `` per call: defeats the purpose; every retry gets a fresh key. * `Date.now()` per call: same as above. * ``: vulnerable to partial replays where body bytes change. ## Worked Example: Fire a Trigger with Retry ```ts theme={null} const idempotencyKey = `signup-${userId}-${eventTimestamp}` const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)) async function fireWithRetry() { for (let attempt = 0; attempt < 5; attempt += 1) { let res: Response try { res = await fetch('https://brew.new/api/v1/automations/triggers/tri_signup/fire', { method: 'POST', headers: { Authorization: `Bearer ${process.env.BREW_API_KEY!}`, 'Content-Type': 'application/json', // Same key on every attempt, first one wins, the rest replay 'Idempotency-Key': idempotencyKey, }, body: JSON.stringify({ payload: { email: 'jane@example.com', firstName: 'Jane' }, }), }) } catch { // Network error: the outcome is unknown, so retry with the same key await sleep(1000 * 2 ** attempt) continue } if (res.ok) return res.json() if (res.status === 429) { await sleep(Number(res.headers.get('Retry-After') ?? '1') * 1000) continue } const body = await res.json().catch(() => null) if (res.status === 409 && body?.error?.code === 'IDEMPOTENCY_IN_PROGRESS') { // The first attempt is still running: wait, then replay with the same key await sleep(1000 * 2 ** attempt) continue } throw new Error(`HTTP ${res.status}: ${JSON.stringify(body)}`) } throw new Error('Exhausted retries') } ``` Two invariants: 1. **Reuse the same `idempotencyKey` across every retry of the same logical operation.** The first request wins; later attempts replay its result. 2. **Mint a fresh `idempotencyKey` when the body changes.** A new email recipient = a new key. ## `409 IDEMPOTENCY_CONFLICT` Envelope ```json theme={null} { "error": { "code": "IDEMPOTENCY_CONFLICT", "type": "conflict", "message": "Idempotency-Key 'signup-jane@example.com-1779292800' was previously used with a different request body.", "suggestion": "Use a fresh key OR submit the exact same body as the original request.", "docs": "https://docs.brew.new/api-reference/api/idempotency" } } ``` The cached original response can be re-fetched by replaying with the same body. There is no separate "get cached result" endpoint. ## Where It Interacts with Other Contracts * **Rate limits**: an idempotent replay counts against the rate-limit window. If you saw a `429` on the first attempt, the retry will hit the gate too. Honor `Retry-After`, don't burn keys. A `429` isn't stored under the key, so the same key works once the window clears. * **Workflow runs**: a trigger replay returns the original `automationRunIds[]` at the top level, so polling follows the same runs. * **Sends**: a production-send replay returns the original `sendId`. A fresh key creates another send of the design. ## SDK Behavior The official `@brew.new/sdk` generates a key for each supported `POST` operation and retains it across automatic retries. Image-upload steps have [separate retry rules](/api-reference/guides/upload-a-local-image). To recover across processes, supply and retain a stable key in `RequestOptions`: ```ts theme={null} await brew.automations.triggers.fire( { triggerEventId: 'tri_signup', payload: { email: 'jane@example.com' }, }, { idempotencyKey: `signup-${userId}-${eventTimestamp}` } ) ``` ## Related * [Rate limits](/api-reference/api/rate-limits): pair with idempotency for safe retry loops. * [Errors](/api-reference/api/errors): full `409 IDEMPOTENCY_CONFLICT` envelope. * [Async jobs & polling](/api-reference/api/async-jobs): for fire / send retries you typically don't need to call again. Poll the run instead. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Organization and Brand Credentials Source: https://docs.brew.new/api-reference/api/organization-and-brand-scope How a Brew credential is scoped to one brand or a whole organization, when to send X-Brand-Id, and what ORG_SCOPE_REQUIRED and INSUFFICIENT_ROLE mean. Every Brew credential answers two separate questions before an operation runs. **What can it reach?** is the credential's scope: one brand, or the whole organization. **Who is asking?** is the person's role. The two produce different `403` codes, and no amount of permission scopes fixes either one. ## Two Kinds of Credential | Credential | Reaches | Names the brand with | | - | - | - | | **Brand-bound key** | Exactly one brand, fixed when the key was minted. | Nothing. The key carries its brand. | | **Organization-scoped key** | Every brand in the organization. | The `X-Brand-Id` header, on every brand-scoped request. | A key is bound when you create it in [**Settings → API**](https://brew.new/settings/api): choose one brand, or the whole organization. Keys are made, rotated, and revoked there only; see [Key Lifecycle](/api-reference/api/authentication#key-lifecycle). No v1 endpoint accepts a brand in a body or query string. ## Naming the Brand There is **no default brand**. An organization-scoped credential that omits `X-Brand-Id` on a brand-scoped operation gets `400 BRAND_ID_REQUIRED`, not a guess. Discover the ids with `GET /v1/brands`, which returns every brand in the organization for an organization-scoped credential and exactly the one bound brand for a brand-bound key. ```bash theme={null} curl https://brew.new/api/v1/brands \ -H "Authorization: Bearer $BREW_API_KEY" curl https://brew.new/api/v1/emails \ -H "Authorization: Bearer $BREW_API_KEY" \ -H "X-Brand-Id: kx7b3s7fapqz8mjm12ekz1kxdx87yceg" ``` A brand-bound key may omit the header. If it sends one naming a **different** brand, that is `403 BRAND_SCOPE_MISMATCH`: use the brand it is bound to, or switch to an organization-scoped key. A brand id from outside the organization is `404 BRAND_NOT_FOUND`, so the API never confirms that another organization's resources exist. ## Organization Operations A few operations act on the organization itself, not on a brand. They take no `X-Brand-Id`, and a brand-bound key cannot call the ones that write or bill: | Operation | Why it is organization-level | | - | - | | `GET /v1/usage` | Plan, credit balance, and send quota belong to the organization. | | `POST /v1/brands` | Creating a brand is an act on the organization, and it needs the `brands` scope, which `emails` does not imply. | | `GET /v1/brands`, `GET /v1/brands/{brandId}` | The brand directory. A brand-bound key sees only its own brand. | | `GET`, `POST`, `DELETE /v1/api-keys` | Key management. Session-only, see below. | | `GET /v1/templates`, `GET /v1/flows` | Organization-wide public catalogs. | | `GET /v1/health`, `GET /v1/help` | No auth at all. | ### `403 ORG_SCOPE_REQUIRED` A brand-bound key calling an organization operation gets: ```json theme={null} { "error": { "code": "ORG_SCOPE_REQUIRED", "type": "authorization_error", "message": "This operation acts on the organization, so a brand-scoped credential cannot call it.", "suggestion": "Create an organization-scoped API key in Settings, API, or reconnect MCP at the organization level." } } ``` This is about the credential's **binding**, not its permission list. A brand-bound key holding `all` still gets `ORG_SCOPE_REQUIRED` on `GET /v1/usage`. The fix is to mint an organization-scoped key at [brew.new/settings/api](https://brew.new/settings/api) (create the key without choosing a brand) and use that one for billing and brand-directory reads. Over MCP, reconnect at the organization level instead of picking a single brand. ### `403 INSUFFICIENT_ROLE` A person, rather than a key, can fail for a different reason: they do not hold the access the operation needs. `error.param` says which: | `param` | Meaning | Fix | | - | - | - | | `member` | The caller has no access to this brand. | An organization admin adds them to the brand. | | `org_admin` | The operation needs the organization admin role. | An organization admin runs it, or grants the role. | `INSUFFICIENT_ROLE` and `ORG_SCOPE_REQUIRED` are not interchangeable. Minting an organization-scoped key does not grant a person a role, and granting a role does not re-bind a key. A third code, `403 INSUFFICIENT_PERMISSIONS`, is the only one that a different **scope set** on the key fixes; see [Authentication](/api-reference/api/authentication) for the scope table. ## Key Management Is Session-Only The three `/v1/api-keys` operations back the dashboard's own API page and accept only a signed-in `org:admin` session, so a leaked key can never mint or revoke another one. [Key Lifecycle](/api-reference/api/authentication#key-lifecycle) owns the rule. ## Choosing a Scope * **One product, one brand.** Use a brand-bound key. It cannot touch another brand even if it leaks, and it never has to send a header. * **An agency, a platform, or anything multi-brand.** Use an organization-scoped key and pass `X-Brand-Id` per request. Read `GET /v1/brands` once at startup and cache the mapping. * **Billing dashboards and provisioning.** Use an organization-scoped key: `GET /v1/usage` and `POST /v1/brands` accept nothing less. ## Related * [Authentication](/api-reference/api/authentication): permission scopes, headers, and key lifecycle. * [Errors](/api-reference/api/errors): the full envelope and every code, including the three `403` codes above. * [MCP authentication and scoping](/api-reference/mcp/authentication-and-scoping): the same rule as an MCP connection sees it. * [Multiple brands](/brand/multiple-brands): what a brand is in the product. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Pagination Source: https://docs.brew.new/api-reference/api/pagination Cursor-based pagination conventions for list endpoints in the Brew Public API v1, limits, cursors, hasMore, and the standard iteration loop. Brew list endpoints use **opaque cursor pagination**. Every paginated response carries a `pagination: { limit, cursor, hasMore }` envelope so callers can iterate without page-counting math. ## The Pagination Envelope ```ts theme={null} type Pagination = { limit: number // page size used for this response cursor: string | null // opaque token. Pass back as `?cursor=…` for the next page; null on the last hasMore: boolean // true when more rows exist } ``` Where it appears (read mode): ```ts theme={null} type ListResponse = { data: Array // the rows for this page, always under `data` pagination?: Pagination } ``` ## Endpoints That Paginate Every list endpoint accepts `limit` (1-100) + `cursor` and returns the `pagination` envelope. The default `limit` is **100** except where noted. | Endpoint | Default `limit` | Max `limit` | Notes | | - | - | - | - | | `GET /v1/contacts` | 100 | 100 | The brand's contacts, newest first. Filterable on `search`, `audienceId`; order with `sort` + `order`. | | `POST /v1/contacts/search` | 50 | 100 | Structured contact search. Filterable + sortable (`search`, `sort`, `order`, `logic`, `filters`, `audienceId`) in the JSON body. With `include: ["openProfile"]` a page holds at most 10 contacts, and `pagination.limit` reports the size read. | | `GET /v1/fields` | 100 | 100 | Custom contact-field definitions for the brand. `?include=coverage` adds per-field fill stats. | | `GET /v1/audiences` | 100 | 100 | Saved audiences for the brand. | | `GET /v1/domains` | 100 | 100 | All sending domains; `?sendableOnly=true` for verified-only, `?sendingPurpose=` to split marketing from transactional. | | `GET /v1/emails` | 100 | 100 | Latest version per `emailId`. Filterable on `status`, `groupId`, and a `from`/`to` window on whichever timestamp `sortBy=updatedAt\|createdAt` names. | | `GET /v1/email-groups` | 100 | 100 | Named email folders for the brand. | | `GET /v1/emails/{emailId}/comments` | 100 | 100 | One design's open comment threads, newest activity first. With `include=messages` a page holds at most 3 threads, and each thread pages its own older messages with `messagesCursor` (see [Cursor Semantics](#cursor-semantics)). | | `GET /v1/templates` | 100 | 100 | Public template catalog; each row is a **full** template (`html` + `previewImage` + title/category/brand). Filterable on `brand`, `category`, `semantic`. | | `GET /v1/flows` | 100 | 100 | Public email flows: one brand's real multi-step sequence per row (`brand`, `type`, `category`, `emailCount`, `spanDays`, `previewImages`). Filterable on `brand`, `category`, `type`, `semantic`; order with `sort=newest\|emails\|span\|remixes`. Each page also carries `total` (every flow the query matches, across all pages) and `isTotalExact` (`false` when the read was cut at 500 flows, so `total` is a floor). A `semantic` search that cannot run is `503`. | | `GET /v1/brand/images` | 100 | 100 | The brand's logos and images, newest first. Filterable on `kind`; order with `sort=newest\|oldest`. With `q`, a free semantic search in relevance order. | | `GET /v1/automations` | 100 | 100 | Latest version per `automationId`, newest first; **lean by default**. Read one with `GET /v1/automations/{automationId}`. `?search=` keeps the name matches, still newest first. | | `GET /v1/automations/triggers` | 100 | 100 | Integration-provisioned, API-created, and Brew-event triggers. | | `GET /v1/automations/runs` | 100 | 100 | Filterable on `automationId`, `triggerEventId`, `triggerInstanceId`, `recipientEmail`, `status`, `mode`, `from`, `to`. | | `GET /v1/automations/audience-runs` | 100 | 100 | Manual-audience launches. Filterable on `automationId`, `status`. | | `GET /v1/automations/trigger-instances` | 100 | 100 | Fired-trigger audit log. Filterable on `triggerEventId`. | | `GET /v1/sends` | 100 | 100 | Sends + lifetime `stats`. Filterable on `status`, `emailId`, `kind`, `messageClass`, `from`, `to`, plus a join filter (`automationId`, `automationRunId`, `audienceRunId`, `triggerInstanceId`) that switches to the per-recipient automation grain. | | `GET /v1/analytics/events` | 100 | 100 | Unified event explorer. Filterable on `recipient`, `eventType`, `automationId`, `sendId`, `emailId`, `from`, `to`, and more. | | `GET /v1/insights` | 100 | 100 | Brew Insights findings, most severe first. Filterable on `state` and `severity`. At most 200 findings are in view, so at the default limit a full walk is at most two pages. A cursor is refused once the findings above it change (see [Cursor Semantics](#cursor-semantics)). | | `GET /v1/chats` | 100 | 100 | The brand's chats, most recently active first. | | `GET /v1/notifications` | 100 | 100 | The notifications bell, newest first. Filterable on `type`. A page can hold fewer rows than `limit` while `hasMore` is `true`. | These are the HTTP limits. The MCP tools read smaller pages; see [MCP page sizes](#mcp-page-sizes). ## MCP Page Sizes An MCP tool result must fit the host's response budget. A list page that doesn't fit is refused whole with `RESPONSE_TOO_LARGE`: no rows and no cursor, so repeating the call with the same cursor and a smaller `limit` skips nothing. The MCP tools therefore page in smaller steps than HTTP: | MCP tool | Default `limit` | Max `limit` | | - | - | - | | `search_contacts` | 10 | 25 (10 with `include: ["openProfile"]`) | | `search_templates` | 8 | 20 | | `list_insights` | 10 | 10 | | `list_email_comments` | 10 | 25 (3 with `include: ["messages"]`) | | `get_email_analytics`, sends report | 10 | 10 | | `get_email_analytics`, events report | 15 | 15 | | Every other `list_*` / `search_*` tool | 25 | 25 | A contact carries every custom field it has, so a `search_contacts` page is as wide as your brand's field list. Raise `limit` toward 25 only when your contacts carry few custom fields. `list_insights` is the one list that trims instead of refusing. It shortens long text on each finding and cuts the report, suggestions, and memo where its budget ends. A `truncated` array names each cut section as `{ section, shown, total }`: items shown of the total for `report` and `suggestions`, and characters of its `markdown` for `memo`. Every finding on the page stays, so the cursor still continues after the last one. The HTTP read always answers whole. ## Single-Resource Reads (Identity in the Path) Every collection has a real detail read at `/{collection}/{id}`. It returns the **bare row**, not a list envelope, so there is no `data[0]` unwrap and no `pagination` object. `?include=` opt-ins embed the heavier detail: | Read | `include` opt-ins | | - | - | | `GET /v1/emails/{emailId}` (carries `previewImage`) | `html`, `versions` | | `GET /v1/email-groups/{groupId}` | none | | `GET /v1/audiences/{audienceId}` | `count`, `build` | | `GET /v1/automations/{automationId}` | `graph`, `versions` | | `GET /v1/automations/runs/{automationRunId}` | `logs` | | `GET /v1/automations/audience-runs/{audienceRunId}` | none | | `GET /v1/automations/triggers/{triggerEventId}` | `skill` | | `GET /v1/automations/trigger-instances/{triggerInstanceId}` | none | | `GET /v1/sends/{sendId}` | `events` | | `GET /v1/domains/{domainId}` | none | | `GET /v1/domains/{domainId}/health` | `scoreHistory`, `scoreRuns` | | `GET /v1/contacts/{email}` | `openProfile` (needs the `emails` scope as well) | | `GET /v1/insights/{insightId}` | none | | `GET /v1/fields/{fieldName}` | none | | `GET /v1/emails/{emailId}/inbox-placement-tests/{testId}` | none | | `GET /v1/flows/{slug}` (adds `anchor` and `steps[]`: `subject`, `dayOffset`, `delayDays`, `category`, `previewImage`, `emailId`, none of which appear on a list card) | `html` (best-effort per step) | > [!WARNING] > > Passing an id as a **list filter** is retired. `GET /v1/emails?emailId=`, > `?audienceId=`, `?automationId=`, `?automationRunId=`, `?triggerEventId=`, > `?sendId=`, `?triggerInstanceId=` and `?domainId=` are no longer accepted > query keys and return `400 INVALID_REQUEST` with `param` naming the key. > Use the path read above. The one place an id still filters a list is a > deliberate join: `GET /v1/sends` accepts `automationId`, > `automationRunId`, `audienceRunId` or `triggerInstanceId` to list the > per-recipient sends that run produced, and `GET /v1/automations/runs` > accepts `automationId`, `triggerEventId` or `triggerInstanceId` for the > same reason. When the id misses, each detail read returns a resource-specific **`404`**: `EMAIL_NOT_FOUND`, `AUDIENCE_NOT_FOUND`, `SEND_NOT_FOUND`, `DOMAIN_NOT_FOUND`, `AUTOMATION_RUN_NOT_FOUND`, `TRIGGER_INSTANCE_NOT_FOUND`, `CONTACT_NOT_FOUND`, `FLOW_NOT_FOUND`, `INSIGHT_NOT_FOUND`. Check the endpoint in the generated reference for its exact code, and see [Errors](/api-reference/api/errors) for the envelope. ## Canonical Iteration Loop This is the standard cursor pattern. The contact read is a `POST` with a JSON body, so the cursor rides in the body (GET lists put `cursor` in the query instead): ```ts theme={null} async function* paginateAllContacts() { let cursor: string | undefined while (true) { const res = await fetch('https://brew.new/api/v1/contacts/search', { method: 'POST', headers: { Authorization: `Bearer ${process.env.BREW_API_KEY!}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ limit: 100, ...(cursor ? { cursor } : {}) }), }) if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`) const body = (await res.json()) as { data: Array<{ email: string }> pagination: { limit: number; cursor?: string; hasMore: boolean } } for (const contact of body.data) yield contact if (!body.pagination.hasMore) return cursor = body.pagination.cursor } } for await (const contact of paginateAllContacts()) { console.log(contact.email) } ``` ## SDK Pagination (TypeScript) The official `@brew.new/sdk` returns the raw `{ data, pagination }` shape. Pass the cursor back on the next call: ```ts theme={null} import { createBrewClient } from '@brew.new/sdk' const brew = createBrewClient({ apiKey: process.env.BREW_API_KEY! }) let cursor: string | undefined do { const page = await brew.contacts.search({ limit: 100, cursor }) for (const contact of page.data) { console.log(contact.email) } cursor = page.pagination?.hasMore ? page.pagination.cursor : undefined } while (cursor) ``` For automation runs, swap `brew.contacts.search` → `brew.automations.runs.list` with the same shape (runs use a GET list, so its filters are query params). To read one run, call `brew.automations.runs.get(automationRunId)` instead: a detail read is not a one-row page. ## Filter Combinations `POST /v1/contacts/search` takes search + sort + filter in one JSON body: ```http theme={null} POST /v1/contacts/search { "search": "jane", "sort": "createdAt", "order": "desc", "limit": 50 } POST /v1/contacts/search { "logic": "and", "filters": [{ "field": "plan", "operator": "equals", "value": "pro" }], "limit": 100 } ``` `GET /v1/automations/runs` supports time-range and status filters: ```http theme={null} GET /v1/automations/runs?automationId=5hDHjxei7UXO3eOrJTKG7&status=completed&from=2026-04-01T00:00:00.000Z&to=2026-04-08T00:00:00.000Z&limit=100 ``` See the per-endpoint pages under [Public API v1](/api-reference/public-v1/contacts/get-contacts) for the full filter parameter table. ## Cursor Semantics * **Opaque.** Cursors are server-generated tokens. Don't parse them; don't synthesize them. The format may change between releases. * **Safe to change the list while you walk it.** A cursor names the last row it returned, not a position, and the next page is the rows that sort after it. Deleting the rows you have read (for example, every audience that matches a search, page by page) skips nothing, and a row created during the walk is never returned twice. A row created where the walk has already passed is not returned; start a new walk to see it. * **Sort by a field the walk doesn't change.** Lists ordered by `updatedAt` (emails by default, automations, triggers) move a row to the front when it is edited, so a row edited ahead of the cursor during your walk moves behind it. For a walk that edits what it reads, page emails with `sortBy=createdAt`, or collect the ids first and then act on them. Comment threads order by their latest message the same way, so a reply during the walk moves its thread to the front. * **Catalogs page by position.** `GET /v1/fields`, `GET /v1/flows`, `GET /v1/templates` and `GET /v1/integrations` page by offset. Deleting custom fields mid-walk shifts their pages, so collect first, then act. * **Insights refuse a stale cursor.** `GET /v1/insights` ranks its findings again on every request, and its cursor remembers which findings it already returned. A change below the cursor is served when its page comes. A finding added or removed above the cursor, or re-ranked across it, makes the next page `400 INVALID_REQUEST` with `param: "cursor"` rather than skip or repeat findings, so read again from the first page without `cursor`, with the same `state` and `severity`. A walk that reaches its last page has returned every finding exactly once, as the list stands then. A cursor sent with a different `state` or `severity` is refused the same way. * **A short page is not the last page.** `GET /v1/notifications` reads a bounded slice of stored rows per page and leaves out the rows your key can't see, so a page can hold fewer rows than `limit`, even none, while `hasMore` is `true`. Stop when `hasMore` is `false`, never because a page came back short. A `type` filter your credential can't see answers an empty page rather than an error. * **A comment thread pages its own messages.** With `include=messages`, a thread whose older messages didn't fit carries a `messagesCursor`. Send it back with that thread's `commentId` (not with `cursor`) for the next older slice, until it comes back `null`. See [Comments](/create-emails/comments#read-the-messages-in-a-thread). * **Brand images page two ways.** Browsing `GET /v1/brand/images` without `q` continues after the last asset the previous page returned, so uploads and deletes during a walk don't repeat or skip an asset. A browse cursor keeps its `sort` and `kind`: sending it with a different one is a `400 INVALID_REQUEST`. A search with `q` pages its ranked results by position, so send each cursor back with the same `q` and `kind` it came from. * **24-hour TTL.** Cursors don't expire on a strict clock today, but treat them as if they're good for \~24h, and re-start with no cursor if a job pauses overnight. ## Related * [Rate limits](/api-reference/api/rate-limits): a tight pagination loop can burn through `100/min` quickly; consider parallelizing across keys or honoring `X-RateLimit-Remaining`. * [Batch operations](/api-reference/api/batch-operations): for **writing** lots of rows fast (`POST /v1/contacts` accepts up to 1000 rows per request). * [Errors](/api-reference/api/errors): `404` on a get-one lookup; `400 INVALID_REQUEST` on bad cursors or a retired id filter. * [Migrating to the cleaned-up v1 surface](/api-reference/api/v1-migration): every route, field, and status rename in one grep-able table. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Rate Limits Source: https://docs.brew.new/api-reference/api/rate-limits Per-route rate limit policies, the response headers that report your remaining budget, and the canonical 429 retry cookbook for Public API v1. Brew rate-limits every authenticated public v1 endpoint. Most limits apply per credential and route over a rolling 60-second window. Email audits also use an organization-wide request limit and concurrency limits. Rate-limited responses expose standard `Retry-After` semantics. The no-auth `GET /v1/health` and `GET /v1/help` discovery endpoints have no rate limit. ## Headers Every rate-limited response carries the rate-limit headers, and a `429 RATE_LIMITED` or retryable `503` response also carries `Retry-After`. See [Response headers](/api-reference/api/response-headers) for the complete header catalog and wire-level examples. This page owns the policies and recovery behavior. For a rolling-window credential refusal, `Retry-After` is the time until the oldest recorded request leaves the window. The refused request does not take a slot, so repeating it does not extend that window. The error's `details` identify the admission scope, limit, remaining budget, reset time and `consumed: false`. Wait the indicated time and retry the same request, keeping its idempotency key when the operation supports one. ## MCP Tools MCP tools draw on the same per-credential budgets as the routes they call. Tools on one budget share it: for example, `send_email`, `pause_email_send`, `resume_email_send`, and `cancel_email_send` share 10 a minute. Call `get_brew_capabilities` for the current budget of every tool. After `RATE_LIMITED`, wait the seconds it names and retry only the refused calls. ## Per-Route Policies Each route declares a named policy in `lib/api/rate_limit/policy.ts`. The policy name appears in observability dashboards. HTTP rate-limit failures use the stable `RATE_LIMITED` error code, with the policy context available in the message or logs. | Policy | Per-min limit | Routes | | - | - | - | | `triggers.read` | 100 | `GET /v1/automations/triggers` (list or detail), `GET /v1/automations/triggers/{triggerEventId}/contract` | | `triggers.write` | 60 | `POST/PATCH/DELETE /v1/automations/triggers`, `POST /v1/automations/triggers/brew-events`, `PUT /v1/automations/triggers/{triggerEventId}/contract` | | `automations.read` | 100 | `GET /v1/automations` (list or detail) | | `automations.write` | 60 | `POST/PATCH/DELETE /v1/automations` (publish/unpublish is `PATCH … { published }`) | | `automation.runs.read` | 100 | `GET /v1/automations/runs` (list or detail), `GET /v1/automations/audience-runs` (list or detail), `GET /v1/automations/trigger-instances` (list or detail), `GET /v1/automations/triggers/{triggerEventId}/readiness` | | `automation.runs.write` | 60 | `POST /v1/automations/{automationId}/test`, `POST /v1/automations/{automationId}/run`, `POST /v1/automations/triggers/{triggerEventId}/fire`, `POST /v1/automations/runs/{automationRunId}/cancel`, `POST /v1/automations/audience-runs/{audienceRunId}/{pause,resume,cancel}` | | `emails.read` | 100 | `GET /v1/emails` (list or detail), `GET /v1/email-groups` (list or detail), `GET /v1/emails/{emailId}/inbox-placement-tests` (list or detail), `GET /v1/emails/{emailId}/comments`, `GET /v1/chats` (list or detail) | | `emails.generate` | 20 | `POST /v1/emails` | | `emails.edit` | 20 | `PATCH/DELETE /v1/emails/{emailId}`, `POST /v1/emails/{emailId}/clone`, `/restore`, `/export` | | `sends.read` | 100 | `GET /v1/sends` (list or detail) | | `sends.write` | 10 | `POST /v1/sends` (campaign + `{ test: true }`), `POST /v1/sends/{sendId}/{cancel,pause,resume}` | | `contacts.read` | 100 | `GET /v1/contacts` (list or detail), `POST /v1/contacts/search` | | `contacts.write_single` | 100 | `POST /v1/contacts` with a single-row body, `PATCH/DELETE /v1/contacts/{email}` | | `contacts.write_batch` | 10 | `POST /v1/contacts` with a batch body, `POST /v1/contacts/import`, `POST /v1/contacts/import-csv`, `POST /v1/contacts/batch-delete` | | `audiences.read` | 100 | `GET /v1/audiences` (list or detail) | | `audiences.write` | 60 | `POST/PATCH/DELETE /v1/audiences` | | `domains.read` | 100 | `GET /v1/domains` (list or detail), `GET /v1/domains/{domainId}/health` | | `domains.write` | 20 | `POST/PATCH/DELETE /v1/domains`, `POST /v1/domains/{domainId}/verify` (hits the sending provider) | | `analytics.read` | 100 | `GET /v1/analytics/*` (`overview`, `automations`, `events`), `GET /v1/insights` (list or detail) | | `brand.read` | 100 | `GET /v1/brand`, `GET /v1/brand/images`, `GET /v1/notifications` | | `brand.write` | 60 | `PATCH /v1/brand`, `DELETE /v1/brand/images/{assetId}` | | `usage.read` | 100 | `GET /v1/usage` | | `fields.read` | 100 | `GET /v1/fields` (list or detail) | | `fields.write` | 100 | `POST /v1/fields`, `DELETE /v1/fields/{fieldName}` | | `templates.read` | 100 | `GET /v1/templates`, `GET /v1/flows` (one shared budget: the public gallery) | | `content.generate` | 20 | `POST /v1/content/generate-image`, `POST /v1/content/gif` | | `email.audit` | 6 | `POST /v1/emails/audit` | | `content.transform` | 60 | `POST /v1/emails/import`, `POST /v1/emails/figma`, `POST /v1/emails/{emailId}/client-previews`, `POST /v1/emails/{emailId}/inbox-placement-tests`, `POST /v1/contacts/validate`, `POST /v1/content/transform`, `POST /v1/content/html-to-png`, `POST /v1/content/add-image`, `POST /v1/content/image-uploads` | ### Brands, Integrations, and API Keys These routes have their own policies: `brands.read`, `brands.write`, `integrations.read`, `api_keys.read`, and `api_keys.write`. An API key reads its limit from the `X-RateLimit-Limit` header, the same as every other route. | Routes | API key limit | Budget | | - | - | - | | `GET /v1/brands`, `GET /v1/brands/{brandId}` | 100 per minute | One budget for the list and the detail read | | `GET /v1/integrations` | 100 per minute | Its own budget | | `/v1/api-keys`, `/v1/api-keys/{keyId}` | None: API keys and OAuth get `403` | A signed-in `org:admin` dashboard session only, under the [session ceiling](#session-traffic-300min-ceiling) | On these routes, brand keys and organization keys get the same limits. The limit for `POST /v1/brands`, which takes an organization key, isn't listed yet. ### Email Audit Admission Email audits fan out to several external checks. They use these additional limits across the Public API, MCP, and agent calls: | Dimension | Limit | Scope | | - | - | - | | Credential or session requests | 6 per minute | One credential or signed-in session | | Organization requests | 20 per minute | All credentials, sessions, MCP calls, and agent calls in one organization | | Organization concurrency | 4 running audits | One organization | | Global concurrency | 16 running audits | All organizations | Capacity rejections return `429 RATE_LIMITED` with `Retry-After`. They do not run or charge the audit. ### Open Image Uploads A brand can hold 20 [local-file image uploads](/api-reference/guides/upload-a-local-image) open at once. An upload is open from `POST /v1/content/image-uploads` until `POST /v1/content/add-image` adds it or it expires. Opening a 21st is `429 RATE_LIMITED`, with `Retry-After` set to when the oldest expires. ### Session Traffic: `300/min` Ceiling UI-backed session traffic (dashboard, Brew chat orchestrator) gets a flat `300/min` ceiling across every policy above except `email.audit`, which stays at 6 per minute. API-key traffic uses the strict per-route limits in the table. ### Generosity and Burst Behavior * The window is a **rolling 60 seconds**, not a fixed wall-clock minute. A spike at the top of a minute does NOT get a free second budget. * The store uses Redis sorted-sets (when available); when Redis is unavailable, every rate-limited endpoint **fails open** with `X-RateLimit-Remaining: ` and `X-RateLimit-Reset: now+60`. You will not see spurious 429s during a Redis blip. * Test mode bypass: `BREW_DISABLE_API_RATE_LIMIT=1` on the dev server skips the gate entirely (test-only env var; never set in production). ## `429` Recovery Cookbook The canonical retry loop: ```ts theme={null} import { setTimeout as sleep } from 'node:timers/promises' async function withRetry(fn: () => Promise): Promise { for (let attempt = 0; attempt < 5; attempt += 1) { const res = await fn() if (res.status !== 429) { if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`) return (await res.json()) as T } const retryAfterSec = Number(res.headers.get('Retry-After') ?? '1') const backoffSec = Math.max(retryAfterSec, 2 ** attempt) await sleep(backoffSec * 1000) } throw new Error('Exhausted retries after repeated 429 responses') } // Create one stable key per logical send, outside the retry callback. const idempotencyKey = 'send-promo-2026-11-27' const sendResponse = await withRetry<{ status: string; sendId: string }>(() => fetch('https://brew.new/api/v1/sends', { method: 'POST', headers: { Authorization: `Bearer ${process.env.BREW_API_KEY!}`, 'Content-Type': 'application/json', 'Idempotency-Key': idempotencyKey, }, body: JSON.stringify({ emailId: 'KGZkvIj8ifId3IMSM8tud', domainId: 'wmwql8hly6k2rk1ekvf61glce48faa7g', audienceId: 'cx0p0pscchoqyofmz8wu9eo7axxsc9wo', subject: 'Black Friday, 40% off', }), }) ) ``` Key invariants: * **Always honor `Retry-After`.** Take the max of `Retry-After` and your own back-off so you don't out-aggressive yourself. * **Reuse the same `Idempotency-Key` on every retry.** See [Idempotency](/api-reference/api/idempotency) for replay semantics. * **Preemptively pause when `X-RateLimit-Remaining` hits 0.** The header ships on rate-limited responses, so a well-behaved client can throttle itself before a 429 ever fires. The standard `429 RATE_LIMITED` and retryable `503` envelopes, including `error.retryAfter`, are documented in [Errors](/api-reference/api/errors). The header and body carry the same wait duration. ## Server-Side Observability Every rate-limited response records an `api.rate_limit.hit` event with the policy, admission scope, limit, retry interval, request id, and actor scope. The event does not include request content. If persistent 429 responses do not match your expected request rate, contact support with the `x-request-id` from one response. ## Related * [Idempotency](/api-reference/api/idempotency): pair with `Idempotency-Key` so retries are safe. * [Errors](/api-reference/api/errors): full error envelope + every `error.code`. * [Response headers](/api-reference/api/response-headers): every header Brew sets. * [Async jobs & polling](/api-reference/api/async-jobs): for `POST /v1/sends` and `POST /v1/automations/triggers/{triggerEventId}/fire`, you don't need to call the API again to wait for delivery. Poll the run. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Response Headers Source: https://docs.brew.new/api-reference/api/response-headers Every header the Brew Public API v1 sets on responses, request correlation, rate limits, idempotency, deprecation, caching. A complete catalog of the headers Brew sets on API responses, what each one means, when it's present, and how to consume it. ## Common Response Headers | Header | Example | Notes | | - | - | - | | `x-request-id` | `req_8cac13fd94e6420cacdd75a1aa403a28` | Opaque per-request correlator. **Always include in support tickets**: Brew engineers can trace your call through the full pipeline. | | `Cache-Control` | `no-store` | Brew responses are never cached; integrators should not cache them either. | | `X-RateLimit-Limit` | `100` | On rate-limited route responses, requests allowed in the current rolling 60s window for this route + key. | | `X-RateLimit-Remaining` | `73` | On rate-limited route responses, requests left before the window exhausts. Honor this to preemptively slow down. | | `X-RateLimit-Reset` | `1717891234` | On rate-limited route responses, Unix epoch seconds when the oldest recorded request leaves the rolling window. | `GET /v1/health` and `GET /v1/help` are public, no-auth discovery surfaces with no rate limit. They may return `x-request-id`, but do not return the `X-RateLimit-*` headers. ## Headers on Specific Responses | Header | When | Format | | - | - | - | | `Retry-After` | `429 RATE_LIMITED` and retryable `503` responses | Integer seconds. Honor verbatim or take `max(Retry-After, your-backoff)`. | | `X-Credit-Cost` | On a **successful fixed-cost** credit-metered `POST` (for example `/v1/content/transform`, `/v1/content/html-to-png`) | Integer credits charged for this call. | | `X-Credits-Remaining` | Alongside `X-Credit-Cost` on a successful fixed-cost call | Integer balance after the charge. | | `Deprecation` | Only on a deprecated alias route: **none are active today** | `true` | | `Sunset` | Only on a deprecated alias route: **none are active today** | RFC 9745 timestamp, for example `2026-12-01T00:00:00Z` | | `Link` | Only on a deprecated alias route: **none are active today** | `<…canonical successor URL…>; rel="successor-version"` | **Usage-metered** operations (email generate / edit, image generation) bill the actual model usage and do **not** emit these headers. Read your balance from `GET /v1/usage` instead. See [Credits](/api-reference/api/credits) for the full metering model. These deprecation headers are defined for forward-compatibility, but no v1 routes are currently deprecated. You will not see them on any live route today. If a route is ever sunset, the `Link` header will point at its canonical successor. ## Request Headers Brew Honors Set these on requests when applicable: | Header | Purpose | See | | - | - | - | | `Authorization: Bearer brew_…` | API key authentication (preferred) | [Authentication](/api-reference/api/authentication) | | `X-API-Key: brew_…` | API key authentication (alternative: pick one) | [Authentication](/api-reference/api/authentication) | | `Idempotency-Key: <≤100 chars>` | Header accepted on `POST` requests | [Idempotency](/api-reference/api/idempotency) | | `Content-Type: application/json` | Required on `POST` / `PATCH` with a body | ## Inspecting Headers from Clients ### `curl` ```bash theme={null} curl -i -H "Authorization: Bearer $BREW_API_KEY" \ https://brew.new/api/v1/audiences ``` `-i` (or `-D -`) prints the response headers above the body. ### TypeScript SDK (Raw Mode) ```ts theme={null} const { headers, data } = await brew.audiences.list( { limit: 50 }, { raw: true } // returns BrewRawResponse<…> instead of just the body ) console.log(headers.get('x-request-id')) console.log(headers.get('X-RateLimit-Remaining')) ``` Pass `{ raw: true }` in `RequestOptions` on any SDK call to get the full `BrewRawResponse` with the headers. ### `fetch` ```ts theme={null} const res = await fetch('https://brew.new/api/v1/contacts', { headers: { Authorization: `Bearer ${process.env.BREW_API_KEY!}` }, }) console.log(res.headers.get('x-request-id')) console.log(res.headers.get('X-RateLimit-Limit')) console.log(res.headers.get('X-RateLimit-Remaining')) console.log(res.headers.get('X-RateLimit-Reset')) console.log(res.headers.get('Retry-After')) console.log(res.headers.get('Deprecation')) console.log(res.headers.get('Sunset')) console.log(res.headers.get('Link')) ``` ## What to Do with Each Header A typical agent / SDK consumes these headers like so: | Header | If you see... | Do | | - | - | - | | `X-RateLimit-Remaining` | `0` or near `0` | Pause until `X-RateLimit-Reset` to avoid a `429`. | | `Retry-After` | Anything (on `429` or retryable `503`) | Sleep that many seconds, then follow the [rate-limit recovery](/api-reference/api/rate-limits#429-recovery-cookbook) guidance. | | `Deprecation: true` | On a legacy route | Migrate to the URL in the `Link: rel="successor-version"` header before `Sunset`. | | `Sunset` | On a legacy route | Plan the migration; the alias stops working at that timestamp. | | `x-request-id` | Always | Log it; surface it on every customer-facing error. | ## Casing HTTP headers are case-insensitive. Brew emits `x-request-id` lowercase, `X-RateLimit-*` and `Retry-After` in canonical case; `fetch` / SDKs read them case-insensitively. ## Related * [Rate limits](/api-reference/api/rate-limits): the canonical `429` cookbook. * [Idempotency](/api-reference/api/idempotency): `Idempotency-Key` semantics. * [Errors](/api-reference/api/errors): error envelope (the body that pairs with `429 RATE_LIMITED`, `409 IDEMPOTENCY_CONFLICT`, etc.). * [API introduction](/api-reference/api/api-introduction): the overview that links every reference page. No v1 routes are currently deprecated, so `Deprecation` / `Sunset` / `Link` are not emitted on any live route today. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Migrate to the New v1 Surface Source: https://docs.brew.new/api-reference/api/v1-migration Every route, field, status, and error rename in the Brew Public API v1 cleanup, with the old spelling next to the new one so you can grep your code. The v1 cleanup gave every collection a real detail read, moved sends to their own root, turned lifecycle changes into action sub-paths, and collapsed four overlapping status vocabularies into one. There are no aliases and no deprecation window: the old spellings return `400` or `404` today. This page is the grep list. Each row is the old string to search your codebase for and the string to replace it with. The generated [Public API v1 reference](/api-reference/public-v1/contacts/get-contacts) is the authority on the exact request and response shapes. ## 1. Read One Row by Its Path The old trick was to call a list with an id filter and take `data[0]`. Those query keys are gone and now return `400 INVALID_REQUEST` with `param` naming the key. Every detail read returns the **bare row**, so drop the `data[0]` unwrap too. | Old | New | | - | - | | `GET /v1/emails?emailId=` | `GET /v1/emails/{emailId}` | | `GET /v1/audiences?audienceId=` | `GET /v1/audiences/{audienceId}` | | `GET /v1/automations?automationId=` | `GET /v1/automations/{automationId}` | | `GET /v1/automations/runs?automationRunId=` | `GET /v1/automations/runs/{automationRunId}` | | `GET /v1/automations/triggers?triggerEventId=` | `GET /v1/automations/triggers/{triggerEventId}` | | `GET /v1/domains?domainId=` | `GET /v1/domains/{domainId}` | | `GET /v1/email-groups?groupId=` | `GET /v1/email-groups/{groupId}` | | `GET /v1/fields?fieldName=` | `GET /v1/fields/{fieldName}` | | A `POST /v1/contacts/search` filter on one address | `GET /v1/contacts/{email}` | | `GET /v1/flows?slug=` → `{ data: [flow] }`, `?include=html` on the list | `GET /v1/flows/{slug}` → the bare flow; `include=html` there only | New reads with no predecessor: `GET /v1/automations/audience-runs/{audienceRunId}`, `GET /v1/automations/trigger-instances/{triggerInstanceId}`, and `GET /v1/emails/{emailId}/inbox-placement-tests/{testId}`. The `?include=` opt-ins still work, now on the path read: `GET /v1/emails/{emailId}?include=html,versions`. The full list is in [Pagination](/api-reference/api/pagination). > [!NOTE] > > An id in a query string is not always wrong. `GET /v1/sends` still takes > `automationId`, `automationRunId`, `audienceRunId`, and > `triggerInstanceId`, and `GET /v1/automations/runs` takes `automationId`, > `triggerEventId`, and `triggerInstanceId`, as deliberate **join** filters, > because those return many rows, not one. ## 2. Sends Moved to Their Own Root | Old | New | | - | - | | `GET /v1/analytics/sends` | `GET /v1/sends` | | `GET /v1/analytics/sends?sendId=` | `GET /v1/sends/{sendId}` | | `GET /v1/analytics/sends?sendId=&include=events` | `GET /v1/sends/{sendId}?include=events` | | `GET /v1/analytics/campaigns` | `GET /v1/sends?kind=campaign`; each row carries `stats` | | `GET /v1/analytics/trigger-instances` | `GET /v1/automations/trigger-instances` | `/v1/analytics` keeps exactly three reports: `overview`, `automations`, and the unified `events` feed. See [Monitor Email Sends](/api-reference/guides/monitor-campaign-sends). ## 3. Lifecycle Changes Are Action Sub-Paths A status is no longer something you PATCH onto a row. | Old | New | | - | - | | `PATCH /v1/domains { domainId, verify: true }` | `POST /v1/domains/{domainId}/verify` | | `PATCH /v1/automations/runs { automationRunId, status: 'canceled' }` | `POST /v1/automations/runs/{automationRunId}/cancel` | | `POST /v1/automations/audience-runs/{audienceRunId}/control { action }` | `POST …/{audienceRunId}/pause`, `/resume`, `/cancel` | | `GET /v1/automations/triggers/{triggerEventId}/fire` as a ready check | `GET /v1/automations/triggers/{triggerEventId}/readiness` | Cancel answers `200` with the new `status` and, for an automation run, the `previousStatus` it left. The readiness body is bare: `{ ready, blockers[], payloadSchema, endpoint, publishedAutomations, counts }`, with no `details` wrapper. ## 4. Renamed Request and Response Fields | Old | New | Where | | - | - | - | | `fromEmail` + `senderName` | `from: { email, name? }` | `POST /v1/sends` | | `replyTo` nested under the sender | `replyTo` at the top level | `POST /v1/sends` | | `runId` on the send `202` and on send rows | Gone. `sendId` is the only handle. | `POST /v1/sends`, `GET /v1/sends` | | `{ version }` | `{ emailVersionId }` | `POST /v1/emails/{emailId}/restore` | | `createdAtFrom` / `createdAtTo` / `updatedAtFrom` / `updatedAtTo` | `sortBy=createdAt\|updatedAt` plus `from` / `to`, which bound whichever timestamp `sortBy` names | `GET /v1/emails` | | `recipientEmail` as a filter | `recipient`, which also accepts `@domain`, a substring, and `!` exclusions | `GET /v1/analytics/events` | | `dry_run` | `dryRun`, in the request and in the preview response | `POST /v1/automations`, `PATCH /v1/automations/{automationId}`, `POST /v1/automations/{automationId}/run` | | `stop_in_flight` | `stopInFlight` | `PATCH /v1/automations/{automationId}` | Those two were the last snake_case fields on the wire. Everything v1 accepts and returns is camelCase now. Send rows gained `automationId`, `nodeId`, `automationRunId`, `audienceRunId`, and `triggerInstanceId`, so an automation delivery can be joined back to the run that produced it without a second call. Two responses became explicit rather than a bare count: `POST /v1/contacts/batch-delete` returns `{ deletedCount, notFound[] }`, and `DELETE /v1/api-keys/{keyId}` returns `{ keyId, deleted, revokedAt? }`. > [!NOTE] > > The event **row** field is still `recipientEmail`. Only the query filter was > renamed to `recipient`. ### `TriggerInstance.state` Became an Enum A fired trigger's `state` used to be a free string. It is now a closed set you can branch on: ``` received | verified | matched | partially_fired | fired | rejected | dead_letter ``` `fired` means every matched automation started. `partially_fired` means some did not, and the fire's `notStarted[]` says why. A start that failed with an unexpected error is retried, so read the instance again. A refusal, such as a merge tag the trigger does not declare, is not retried: when every failed start is a refusal the receipt moves to `dead_letter`, and each new fire is refused the same way until the automation or trigger is fixed. ## 5. One Status Vocabulary Runs, sends, audience builds, and inbox-placement tests all report the same set. Anything typed against an old spelling in a status **filter** is now `400 INVALID_REQUEST`. ``` queued | scheduled | running | paused | completed | partially_completed | failed | canceled ``` | Old | New | | - | - | | `sent` | `completed` | | `partially_sent` | `partially_completed` | | `sending` | `running` | | `pending` | `queued` | | `cancelled` | `canceled` (one `l`, everywhere) | A step or node inside a run reports `running | completed | failed | skipped`. An email **design** reports `generating | ready | failed`, so the old `streaming` and `complete` spellings are gone there too. A synchronous test send now resolves to `200 { status: 'completed', recipient }`. ## 6. Errors | Old | New | | - | - | | `INSUFFICIENT_EMAIL_SENDS` | `SEND_QUOTA_EXCEEDED`, `402` | | `PUBLISH_VALIDATION_FAILED` at `409` | Same code at `422` | | `EVENT_NOT_FOUND` | `TRIGGER_INSTANCE_NOT_FOUND` | | Any other `429` code | `RATE_LIMITED` is the only one | | The trigger-fire "legacy envelope" (`{ success, details }`) | The standard error envelope; a bad payload is `400 INVALID_PAYLOAD` | | A generic `404 NOT_FOUND` from `POST /v1/automations/{automationId}/run` | `404 AUTOMATION_NOT_FOUND` or `404 AUDIENCE_NOT_FOUND`, so you can tell which one is missing | New this cleanup: `403 ORG_SCOPE_REQUIRED` when a brand-bound key calls an operation that acts on the organization, such as `GET /v1/usage`. A person missing the role still gets `403 INSUFFICIENT_ROLE`. See [Organization and brand credentials](/api-reference/api/organization-and-brand-scope). The full catalog, generated from the specification, is on [Errors](/api-reference/api/errors). ## 7. TypeScript SDK 10 Twenty methods were added, mostly the detail reads and the send root: | Method | Route | | - | - | | `audiences.get(audienceId, { include? })` | `GET /v1/audiences/{audienceId}` | | `automations.get(automationId, { include? })` | `GET /v1/automations/{automationId}` | | `automations.runs.get(automationRunId, { include? })` | `GET /v1/automations/runs/{automationRunId}` | | `automations.runs.cancel(automationRunId)` | `POST /v1/automations/runs/{automationRunId}/cancel` | | `automations.audienceRuns.get(audienceRunId)` | `GET /v1/automations/audience-runs/{audienceRunId}` | | `automations.audienceRuns.pause(audienceRunId)` | `POST …/audience-runs/{audienceRunId}/pause` | | `automations.audienceRuns.resume(audienceRunId)` | `POST …/audience-runs/{audienceRunId}/resume` | | `automations.audienceRuns.cancel(audienceRunId)` | `POST …/audience-runs/{audienceRunId}/cancel` | | `automations.triggerInstances.list(query)` | `GET /v1/automations/trigger-instances` | | `automations.triggerInstances.get(triggerInstanceId)` | `GET /v1/automations/trigger-instances/{triggerInstanceId}` | | `automations.triggers.get(triggerEventId, { include? })` | `GET /v1/automations/triggers/{triggerEventId}` | | `automations.triggers.readiness(triggerEventId)` | `GET /v1/automations/triggers/{triggerEventId}/readiness` | | `contacts.get(email)` | `GET /v1/contacts/{email}` | | `contacts.list(query)` | `GET /v1/contacts` | | `domains.get(domainId)` | `GET /v1/domains/{domainId}` | | `emailGroups.get(groupId)` | `GET /v1/email-groups/{groupId}` | | `emails.get(emailId, { include? })` | `GET /v1/emails/{emailId}` | | `emails.inboxPlacementTests.get(emailId, testId)` | `GET /v1/emails/{emailId}/inbox-placement-tests/{testId}` | | `fields.get(fieldName)` | `GET /v1/fields/{fieldName}` | | `sends.list(query)` | `GET /v1/sends` | | `sends.get(sendId, { include? })` | `GET /v1/sends/{sendId}` | And these were removed or retargeted: | Old | New | | - | - | | `analytics.campaigns.*` | `sends.list({ kind: 'campaign' })`; rows carry `stats` | | `analytics.sends.*` | `sends.list(query)` and `sends.get(sendId, { include: 'events' })` | | `analytics.triggerInstances.*` | `automations.triggerInstances.*` | | `automations.triggers.ready(…)` | `automations.triggers.readiness(…)`, bare body | | `automations.runs.cancel({ automationRunId, status })` | `automations.runs.cancel(automationRunId)` | | `automations.audienceRuns.control({ action })` | `pause`, `resume`, `cancel` as three methods | `analytics` keeps only the reports: `overview`, `events`, `automations`. ## 8. CLI 0.7 `brew-cli` 0.7 depends on `@brew.new/sdk` 10. Six commands were retargeted at the new routes, and the command names you already type are unchanged, so `brew-cli automations triggers ready` still works. New commands cover the detail reads, the sends root, trigger instances, and the four lifecycle actions. Raw `brew-cli api` calls in your scripts are **not** retargeted for you: they go straight to the path you typed, so grep those against section 1. ## Migration Checklist **1. Grep for the retired query keys** Search for `?emailId=`, `?audienceId=`, `?automationId=`, `?automationRunId=`, `?triggerEventId=`, `?sendId=`, `?triggerInstanceId=`, and `?domainId=`. Each one that reads a single row becomes a path read. **2. Grep for the analytics paths** `analytics/sends`, `analytics/campaigns`, and `analytics/trigger-instances` have no replacement at the same path. **3. Grep for old status strings** `'sent'`, `'sending'`, `'partially_sent'`, `'pending'`, `'streaming'`, `'complete'`, and `'cancelled'` in filters and comparisons. **4. Drop the data\[0] unwrap** A detail read returns the row. `body.data[0]` will be `undefined`. **5. Drop runId from send handling** `POST /v1/sends` no longer returns one. Persist `sendId` instead. **6. Grep for snake_case request keys** `dry_run` and `stop_in_flight` are rejected. Send `dryRun` and `stopInFlight`. **7. Re-check your credential** If any call now returns `403 ORG_SCOPE_REQUIRED`, mint an organization-scoped key for it. See [Organization and brand credentials](/api-reference/api/organization-and-brand-scope). ## Related * [Pagination](/api-reference/api/pagination): the detail-read table and the cursor loop. * [Errors](/api-reference/api/errors): the generated code catalog. * [Async jobs & polling](/api-reference/api/async-jobs): the poll loops, rewritten for the path reads. * [Changelog](/changelog/api): the dated record of API changes. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Use the CLI from AI Agents Source: https://docs.brew.new/api-reference/cli/agents What makes brew-cli dependable inside coding agents: automatic JSON, semantic exit codes, and a confirmation protocol that never hangs. The CLI treats agents as first-class users. Where the [MCP server](/api-reference/mcp/overview) gives an agent tools over a protocol, the CLI gives any harness that can run shell commands the same reach: composable, pipeable, and cheap on context. ## The Contract * **JSON without asking.** When stdout is not a terminal (which is every agent), commands print the exact API response as one JSON line. Errors are JSON envelopes on stderr with stable `code` fields and a `requestId`. * **Semantic exit codes.** `0` success, `1` API or runtime error, `2` usage error, `3` authentication error, `4` confirmation required, `130` / `143` interrupted by SIGINT / SIGTERM. Unknown commands fail hard with no fuzzy "did you mean" to misread. * **Never hangs.** Nothing waits on stdin unless it is a real terminal, and missing input is an immediate exit 2 with the fix in the message. Every request is bounded, response body included: `--timeout ` (`90s`, `1500ms`, `5m`) caps the whole command, retries and pages included, so it fits a tool-call budget. Long-running commands such as `emails generate` default to their own budget. SIGINT or SIGTERM stops the request in flight. * **Stable surface.** Commands and flags are additive across releases, and the [manifest](#discovery-for-agents) describes the installed build exactly. ## Replaying an Unknown Outcome The API may keep working after the CLI disconnects. A write that ends in `CLI_TIMEOUT`, `CLI_CONNECTION`, `CLI_INTERRUPTED` or a 5xx may still complete. When the request can be replayed, its error envelope includes the original `idempotencyKey` and a `retryCommand` for that action: ```json theme={null} { "error": { "code": "CLI_TIMEOUT", "type": "service_unavailable", "message": "No complete response within 60000ms (POST /v1/emails).", "idempotencyKey": "3f2a9c1e-…", "retryCommand": "brew-cli emails generate --prompt 'Welcome email' --timeout 60s --idempotency-key 3f2a9c1e-…" } } ``` Run the returned `retryCommand`; never re-run the original command with a fresh key. A `409 IDEMPOTENCY_IN_PROGRESS` means the first attempt is still running: wait, then run `retryCommand` again. A read that fails this way changed nothing and simply re-runs. If no `retryCommand` is supplied, inspect the error before retrying. From CLI 0.19.0, image-upload recovery commands replay only `content add-image` with the original upload ID and key, including after a final-step interruption. See [Upload a Local Image](/api-reference/guides/upload-a-local-image#from-the-cli) for recovery limits. The replay needs the API's idempotency store. While it is degraded, the fail-closed writes refuse with a retryable `503` rather than run unmetered or send twice. [Idempotency](/api-reference/api/idempotency#in-progress-requests-and-storage-outages) lists them. Other writes run without the guarantee. So for a write that must not happen twice (creating a brand, say), pass `--max-retries 0`, and check whether it landed before you run `retryCommand`. ## The Confirmation Protocol Irreversible commands (campaign sends, deletes, trigger fires, cancels) do not execute in a non-interactive session. They exit with code 4 and print an envelope: ```json theme={null} { "confirmationRequired": true, "command": "brew-cli emails send", "summary": "Send email KdKkTtkhz8Ri6dPv5sfoz as a REAL campaign to audience cbkr2p4z3e521rdbb9cciacmp5524mez now. Real recipients receive it; this cannot be undone.", "confirmCommand": "brew-cli emails send KdKkTtkhz8Ri6dPv5sfoz --subject 'Fall sale' --audience cbkr2p4z3e521rdbb9cciacmp5524mez --domain yksl4qbeqc4tkjvoay8mfctiaiasf7xt --yes" } ``` The intended flow: show the `summary` to your human, and only run the `confirmCommand` after they approve. Passing `--yes` yourself is reserved for actions the user already asked for explicitly. Test sends (`emails send --test --to you@example.com`) are the safe lane and skip the gate. ## Discovery for Agents ```bash theme={null} brew-cli docs --agent ``` Prints a JSON manifest of every command: path, summary, flags, safety class, whether it needs confirmation, and the API route behind it. Pair it with `brew-cli docs api` (the live `GET /v1/help` catalog) and the served agent guide at `https://brew.new/api/v1/llms.txt`. The repo also ships a ready-made skill at [`skills/brew-cli/SKILL.md`](https://github.com/GetBrew/brew-cli/blob/main/skills/brew-cli/SKILL.md) that teaches Claude Code and compatible harnesses this whole contract in about fifty lines. ## A Typical Agent Session ```bash theme={null} brew-cli contacts count --json brew-cli emails generate --prompt "Welcome email for new signups" --json brew-cli emails send KGZkvIj8ifId3IMSM8tud --test --to qa@yourteam.com --subject "Preview" brew-cli analytics overview --since 2026-08-01T00:00:00Z --json ``` Reads flow freely, generation is metered by [credits](/api-reference/api/credits), and the one real send in the session was a test delivery to your own inbox. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # CLI Authentication Source: https://docs.brew.new/api-reference/cli/authentication Authenticate brew-cli with a Brew API key, understand brand vs organization scoping, and point the CLI at different environments. The CLI authenticates with the same [API keys](/api-reference/api/authentication) as the Public API. Create one in the dashboard under [**Settings → API**](https://brew.new/settings/api). ## Sign In ```bash theme={null} brew-cli login ``` Paste your key when prompted. The CLI validates it against the API before storing anything, then saves it to `~/.config/brew-cli/config.json` with owner-only file permissions. `brew-cli logout` removes it, and `brew-cli whoami` shows the resolved credential (always masked) at any time. Non-interactive environments skip `login` entirely and set an environment variable instead: ```bash theme={null} export BREW_API_KEY=brew_your_key_here ``` ## Precedence When several sources are present, the CLI resolves the key in this order: 1. `--api-key` flag 2. `BREW_API_KEY` environment variable 3. The stored login The same pattern applies to the brand: `--brand`, then `BREW_BRAND_ID`, then `brew-cli config set brandId ...`. ## Brand vs Organization Keys A key is scoped either to one brand or to your whole organization: * **Brand-scoped key**: the brand is implicit for brand-scoped commands. Permission scopes and access rules still apply. * **Organization-scoped key**: brand-level commands need to know which brand you mean. Pass `--brand `, export `BREW_BRAND_ID`, or store a default with `brew-cli config set brandId `. Find ids with `brew-cli brands list`. Omitting the brand returns a `BRAND_ID_REQUIRED` error rather than guessing. Organization-level commands (`brands`, `templates`, `flows`, `usage`) ignore the brand entirely; [Organization operations](/api-reference/api/organization-and-brand-scope#organization-operations) owns the full list. `api-keys` commands remain for compatibility, but the API rejects CLI credentials with `403`. Manage keys in [**Settings → API**](https://brew.new/settings/api); see [Key Lifecycle](/api-reference/api/authentication#key-lifecycle). ## API URL The default is `https://brew.new/api`. Override it with `--api-url`, then `BREW_API_URL`, then the stored `apiUrl`, in that order. For a local API: ```bash theme={null} brew-cli health --api-url http://localhost:3000/api ``` The stored login normally lives in `~/.config/brew-cli/config.json`. `XDG_CONFIG_HOME` changes the base directory; `BREW_CLI_CONFIG_DIR` selects it directly. ## Key Hygiene Keys start with `brew_` and are shown masked in every CLI output, including errors. Prefer `login` or environment variables in shared shells; `--api-key` can land in shell history. Use a brand key when appropriate, and rotate any exposed key in API settings. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # CLI Commands Source: https://docs.brew.new/api-reference/cli/commands What the Brew CLI includes: every Public API operation as a typed command, plus the conventions all commands share. Commands follow a `brew-cli ` shape and cover every operation in [Public API v1](/api-reference/api/api-introduction). Run any command with `--help` for flags and examples. The [generated reference](https://github.com/GetBrew/brew-cli/blob/main/docs/commands/README.md) lists the complete command surface. ## Everyday Commands The ten you will reach for most: ```bash theme={null} brew-cli emails generate --prompt "Welcome email for new signups" # AI-generate a design brew-cli emails get zavwOzhfWqE9HvALKd9bw --include html,versions # read a design brew-cli emails send zavwOzhfWqE9HvALKd9bw --test --to you@company.com --subject "Preview" brew-cli contacts upsert --email jane@example.com --first-name Jane brew-cli contacts search --filter email:contains:@acme.com --limit 20 brew-cli audiences list brew-cli analytics overview --since 2026-08-01T00:00:00Z brew-cli sends get VDDDYjldT4wLfJaaqQCoN --include events brew-cli domains list --sendable-only --json brew-cli usage # plan, credits, send quota ``` For complete worked sequences (sending an email, building a welcome automation, QA before a big send), see [Common Flows](/api-reference/cli/common-flows). ## The Surface | Group | What it covers | | - | - | | `contacts`, `fields` | Search, count, upsert (single and batch), update, delete, validate deliverability, CSV import, and custom field definitions. `contacts get` and `contacts search` take `--include openProfile` for each contact's open-time profile | | `emails` | List and fetch designs with HTML and version history, generate and edit with AI, import HTML, MJML, EML, React Email, or Figma, clone, restore versions, export to another ESP, audit an email, preview clients, test inbox placement, and send. Folders live under `emails groups`, and `--email-ids` moves up to 50 designs into one in a single call. `emails comments list` reads a design's open comment threads, and `--include messages` adds what was said | | `sends` | List and read sends with lifetime stats and optional events; cancel, pause, and resume delivery | | `audiences` | List, create (including from analytics events), update, duplicate, and delete segments | | `automations` | The full lifecycle: create and edit graphs, publish and unpublish, suppression-safe test runs, manual runs, trigger contracts and unsubscribe triggers (`automations triggers ...`, with `automations triggers ensure-brew-event` creating or returning a Brew-event trigger), the `ready` fire preflight, firing events, and run history | | `domains` | Add sending domains, fetch DNS records, verify, health reports (`--include scoreHistory,scoreRuns` adds the score's history and the automated score runs), sender defaults, removal, and each marketing domain's own unsubscribe list (`domains unsubscribes ...`) | | `analytics` | Brand overview, automation performance, the event feed, and grouped event counts (`analytics event-counts`) | | `insights` | Brew Insights findings, most severe first (`insights list`, with `--include pulse,report,suggestions,memo` for the intelligence layer), and one finding in full with its frozen metrics (`insights get`) | | `chats`, `notifications` | The brand's recent chats (`chats list`) and one chat's context for a hand-off (`chats get`), and what finished or failed, as the app's bell shows it (`notifications list`, with `--type` to keep one kind) | | `brand`, `brands` | The active brand's identity and assets, plus organization-level brand lifecycle | | `content` | Image generation, GIFs, transforms, HTML-to-PNG rendering | | `templates`, `flows` | The public gallery: single designs to start from, and real multi-step email sequences by brand (`flows list` leads with how many flows match; `flows get brew.new` returns every step with its timing and template id; `--include html` adds the bodies) | | Utility | `login`, `logout`, `whoami`, `config`, `usage`, `health`, `doctor`, `docs`, `types` (generate [typed payload contracts](/api-reference/guides/typed-payload-contracts) with a `--check` drift gate), and the raw `api` escape hatch | ## Conventions Every Command Shares * **Two output modes.** Human-readable in a terminal; exact API JSON when you pass `--json` or pipe the output. Data goes to stdout, progress to stderr, so pipes stay clean. * **Structured inputs.** Simple values are flags. Full request bodies go through `--input ''` (or `--input -` to read stdin), and file uploads through `--file `. Flags win over `--input` on conflicts, even an explicit empty one, so `""` clears a description or sender name. The id in the command line always wins over ids inside a body. * **Unknown input keys fail.** `--input` refuses a top-level key the command wouldn't send. It exits 2 with a usage error that names the key, suggests a close match (`firstname` → `firstName`), and lists the accepted keys. Inputs whose keys are your own data, such as a bare trigger payload or flat contact fields, aren't checked. * **Safe by default.** Irreversible commands (production sends, deletes, trigger fires) ask for confirmation in a terminal and refuse with exit code 4 anywhere else until you pass `--yes`. Test sends (`emails send --test`) skip the gate. * **Bounded and interruptible.** `--timeout ` caps a whole command, response body included, and `--max-retries ` controls retries on SDK-backed requests. Raw transport commands make one attempt. Ctrl-C stops a request wherever it is and exits 130. Errors include an `idempotencyKey` and `retryCommand` when the request can be replayed. Follow the returned command; [image-upload recovery](/api-reference/guides/upload-a-local-image#from-the-cli) replays only finalization. * **Retry-safe writes.** Pass `--idempotency-key` where the command supports it to make retries [replay instead of duplicate](/api-reference/api/idempotency). * **Pagination handled.** Paginated commands expose `--limit`, `--cursor`, and `--all` where supported. `--all` follows the cursor and combines the pages. * **Typed errors.** Failures print the API's [error envelope](/api-reference/api/errors) with its stable `code` and the `requestId` for support. ## The Escape Hatch `brew-cli api ` sends a raw authenticated request with your key, brand header, and error handling applied: ```bash theme={null} brew-cli api GET '/v1/sends/jpUlHPAzKZIQUxEphr4wP?include=events' ``` Useful for brand-new endpoints, unusual query combinations, or exploring the API interactively. Mutating methods go through the same confirmation gate as every other command. ## Discovery * `brew-cli docs`: pointers to this documentation, the OpenAPI spec, and the agent guide. * `brew-cli docs api`: the live machine-readable API catalog (`GET /v1/help`). * `brew-cli docs --agent`: a JSON manifest of every command, flag, and safety class, built for [AI agents](/api-reference/cli/agents). ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # CLI Common Flows Source: https://docs.brew.new/api-reference/cli/common-flows Use brew-cli to send to opted-in contacts, check a design, build a welcome automation, and read delivery results with runnable examples. Run these commands after [authentication](/api-reference/cli/authentication). Replace example IDs with returned IDs and use `--json` for raw results. For a first test email, start with the [CLI Quickstart](/api-reference/cli/quickstart). ## Send a Scheduled Email Use a contact CSV containing only people who opted in. Record their [consent](/audience/add-contacts), and choose a verified marketing domain before sending. ```bash theme={null} # 1. Get contacts in (one batch in Import History, named contacts.csv) brew-cli contacts import-csv --file contacts.csv --consent-source import \ --mapping "Email=email" --mapping "First Name=firstName" # 2. Segment them brew-cli audiences create --name "Newsletter" \ --input '{"filters":{"filters":[{"field":"subscribed","operator":"equals","value":true}],"logicalOperator":"and"}}' # 3. Generate the design with AI (30 to 90 seconds) brew-cli emails generate --prompt "October product newsletter: three updates, one CTA to the changelog" # 4. Send yourself a test before anything real happens brew-cli emails send zavwOzhfWqE9HvALKd9bw --test --to you@yourcompany.com --subject "October newsletter preview" # 5. Schedule the real send (the CLI asks you to confirm) brew-cli emails send zavwOzhfWqE9HvALKd9bw --subject "What's new in October" \ --audience m3ll218tvnk53pzei1axvn75fowpmvqd --domain tbfyoxx1bhlo563mqdeujwmx6afod8bk --schedule-at 2099-01-01T14:00:00Z # 6. Watch it, or change your mind brew-cli sends get VDDDYjldT4wLfJaaqQCoN brew-cli sends cancel VDDDYjldT4wLfJaaqQCoN ``` Sending needs a [verified sending domain](/get-started/verify-your-sending-domain). Run `brew-cli domains list --sendable-only --json` and choose a record with `sendingPurpose: "marketing"`. Replace the example schedule with your intended future time. ## QA a Design Before a Big Send ```bash theme={null} # Read the design and its version history brew-cli emails get zavwOzhfWqE9HvALKd9bw --include html,versions # Tweak it with AI and keep iterating brew-cli emails edit zavwOzhfWqE9HvALKd9bw --prompt "Tighten the intro to two sentences" # Audit the saved design and inbox copy, then render it in real clients brew-cli emails audit --email-id zavwOzhfWqE9HvALKd9bw \ --subject "What's new in October" --sending-purpose marketing brew-cli emails preview-clients zavwOzhfWqE9HvALKd9bw # Where does it land: inbox or spam? brew-cli emails create-inbox-placement-test zavwOzhfWqE9HvALKd9bw --domain tbfyoxx1bhlo563mqdeujwmx6afod8bk brew-cli emails get-inbox-placement-results zavwOzhfWqE9HvALKd9bw --test-id ibp_xyz ``` If a revision goes wrong, `brew-cli emails restore zavwOzhfWqE9HvALKd9bw --to-version 2` brings back any earlier version as the new latest. ## Build a Welcome Automation Create a trigger, attach a graph, test it, then publish and fire it. Replace every example ID, including the saved email version and verified domain. ```bash theme={null} # 1. Define the event your systems will send. Every payload needs an email field. brew-cli automations triggers create --title "User signed up" \ --input '{"payloadSchema":{"type":"object","fields":[{"key":"email","type":"string","required":true},{"key":"plan","type":"string","required":false}]}}' # 2. Create the automation graph: trigger, then send brew-cli automations create --input '{ "name": "Welcome flow", "triggerEventId": "tev_abc123", "nodes": [ {"id":"t1","label":"Signup","type":"trigger","config":{"mode":"event","triggerEventId":"tev_abc123"}}, {"id":"s1","label":"Welcome email","type":"sendEmail","config":{"emailId":"zavwOzhfWqE9HvALKd9bw","emailVersionId":"iRTEW3YhFGh6j3ZYd2Ql6","domainId":"tbfyoxx1bhlo563mqdeujwmx6afod8bk","subject":"Welcome aboard","previewText":"Here is how to get started"}} ], "connections": [{"from":"t1","to":"s1"}] }' # 3. Test it safely (no real mail) brew-cli automations test OcTszWzAApTlgdJWcSF0P --input '{"payload":{"email":"qa@yourcompany.com"}}' # Read the returned automationRunId, replacing the example below brew-cli automations runs get RUN_ID_FROM_TEST --include logs ``` Wait for a successful test and inspect its logs before publishing. Then enable live runs: ```bash theme={null} brew-cli automations publish OcTszWzAApTlgdJWcSF0P # 4. Check readiness, then fire the event brew-cli automations triggers ready tev_abc123 brew-cli automations triggers fire tev_abc123 --input '{"payload":{"email":"jane@example.com","plan":"pro"}}' --idempotency-key signup-event-001 brew-cli automations runs list --limit 5 ``` Firing sends to the recipient in the payload. For marketing mail, use a recipient who opted in. `brew-cli automations unpublish OcTszWzAApTlgdJWcSF0P` stops new runs. Non-interactive destructive calls require `--yes` for an authorized action. ## Keep Your Contact Base Healthy ```bash theme={null} # Add or update one contact with custom fields brew-cli contacts upsert --email jane@example.com --first-name Jane --custom plan=pro # Define a reusable custom field brew-cli fields create --name lifecycleStage --type string # Check deliverability for your opted-in contacts brew-cli contacts validate --emails jane@example.com bob@example.com # Find who you are about to email brew-cli contacts search --audience m3ll218tvnk53pzei1axvn75fowpmvqd --limit 20 brew-cli contacts count --filter email:contains:@acme.com ``` ## Report on Performance ```bash theme={null} # The account at a glance for a date range brew-cli analytics overview --since 2026-08-01T00:00:00Z --until 2026-09-01T00:00:00Z # Per-send results, with the per-recipient event feed brew-cli sends get VDDDYjldT4wLfJaaqQCoN --include events # One recipient's whole history brew-cli analytics events --recipient jane@example.com --all ``` With `jq` installed, read lifetime counts from each send's `stats`: ```bash theme={null} brew-cli sends list --kind campaign --all --json | jq '.data[] | {sendId, subject, stats}' ``` ## Explore Anything Else ```bash theme={null} # Every command, flag, and example brew-cli docs --agent # The live API catalog brew-cli docs api # Raw access for anything without a dedicated command yet brew-cli api GET '/v1/automations/trigger-instances?limit=5' ``` ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # CLI Installation Source: https://docs.brew.new/api-reference/cli/installation Install brew-cli with Homebrew, a prebuilt binary, or npm, then run your first command. Pick whichever channel fits your machine. All three ship the same CLI. ## Homebrew (macOS and Linux) ```bash theme={null} brew install getbrew/tap/brew-cli ``` A self-contained binary, no runtime required. Upgrade later with `brew upgrade brew-cli`. ## npm ```bash theme={null} npm install -g @brew.new/cli ``` Requires Node 20 or newer. For one-off runs without installing anything, use `npx @brew.new/cli` (handy inside CI jobs and agent sandboxes that already have Node). ## Prebuilt Binaries Every [GitHub release](https://github.com/GetBrew/brew-cli/releases) attaches standalone binaries for macOS (Apple Silicon and Intel), Linux (x64 and arm64), and Windows, plus a `checksums.txt` with SHA-256 hashes. Download, verify, `chmod +x`, and place it on your `PATH`. ## Verify the Install ```bash theme={null} brew-cli --version ``` Then [authenticate](/api-reference/cli/authentication) and run your first command: ```bash theme={null} brew-cli whoami ``` ## Staying Current New platform capabilities ship as new CLI releases. Upgrade through the channel you installed with, for example `brew upgrade brew-cli` or `npm update -g @brew.new/cli`. The full source lives at [github.com/GetBrew/brew-cli](https://github.com/GetBrew/brew-cli). ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Brew CLI Source: https://docs.brew.new/api-reference/cli/overview Use brew-cli to create email designs, manage contacts, send emails, and run automations from your terminal, scripts, CI, or a coding agent. The Brew CLI (`brew-cli`) calls Public API v1 from your terminal. Use it to create designs, send and schedule emails, manage contacts and audiences, run automations, and read analytics. ## Start Here [Install the CLI](/api-reference/cli/installation), then follow the [CLI Quickstart](/api-reference/cli/quickstart) to generate an email and test it in your inbox. ```bash theme={null} brew install getbrew/tap/brew-cli brew-cli login brew-cli emails list --limit 5 ``` Create the API key at [**Settings → API**](https://brew.new/settings/api). The [authentication guide](/api-reference/cli/authentication) covers brand selection and CI setup. ## Scripts and Agents Output becomes JSON when piped or when you pass `--json`. Use `--all` to follow list cursors, `--timeout` to bound work, and `--idempotency-key` on supported writes. Destructive commands require confirmation; non-interactive callers use `--yes` for an authorized action. `brew-cli docs --agent` describes the installed commands and flags. `brew-cli doctor` checks reachability, authentication, and differences between that build and the live API. If it can't check a configured key, it exits 1 with `authValid: null`. The reason is in `reachabilityError` when the API is unreachable. It's in `authCheckError` when the API answers but the key check fails. ## What to Read Next * [Commands](/api-reference/cli/commands): resource groups, flags, and the raw API command. * [Common Flows](/api-reference/cli/common-flows): sending, automation, and reporting examples. * [Use from AI Agents](/api-reference/cli/agents): output, errors, and confirmation. * [Build with Brew](/api-reference/overview): compare CLI, SDK, API, and MCP. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # CLI Quickstart Source: https://docs.brew.new/api-reference/cli/quickstart Generate a saved email and send a test to your own inbox with brew-cli, using a brand API key and no audience or verified sending domain. Generate an on-brand welcome email and receive a test in your inbox. ## Before You Begin [Add your brand](/get-started/add-your-brand), [install brew-cli](/api-reference/cli/installation), and create a brand API key at [**Settings → API**](https://brew.new/settings/api). The key needs permission to generate emails and send tests. Generation uses [credits](/api-reference/api/credits). You do not need an audience or a verified domain. ## 1. Connect to Your Brand ```bash theme={null} brew-cli login brew-cli brand get --json ``` Paste the key at the login prompt. The brand response has `brandId`, `domain`, `status`, and `ready` at the top level. Continue when `ready` is `true`. If extraction is running, wait and repeat the read. For an organization key, [choose a brand first](/api-reference/cli/authentication#brand-vs-organization-keys). ## 2. Generate the Design ```bash theme={null} brew-cli emails generate \ --prompt "Create and save a friendly welcome email with one Get started button" \ --idempotency-key first-cli-email-001 \ --json ``` Generation can take a minute or more. Copy the returned `emailId`. If the result contains only `response`, read that explanation and adjust your prompt. ## 3. Send Yourself a Test Replace `YOUR_EMAIL_ID` with the returned ID and `you@example.com` with your own inbox. ```bash theme={null} brew-cli emails send YOUR_EMAIL_ID \ --test \ --to you@example.com \ --subject "Welcome aboard" \ --idempotency-key first-cli-test-001 \ --json ``` The response is `{ "status": "completed", "recipient": "you@example.com" }`. Open **\[TEST] Welcome aboard** in your inbox. The test uses Brew's default sender. Reuse a retry key when recovering the same request. Use a new key for a new design or test. See [Replay an Unknown Outcome](/api-reference/cli/agents#replaying-an-unknown-outcome). ## Keep Going * [Common Flows](/api-reference/cli/common-flows): schedule an email or build an automation. * [Commands](/api-reference/cli/commands): find commands and inspect their flags with `--help`. * [Use from AI Agents](/api-reference/cli/agents): JSON output, exit codes, and confirmation. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Check Brand Readiness Before Generating Source: https://docs.brew.new/api-reference/guides/check-brand-readiness Use GET /v1/brand to confirm the API key's brand has finished extraction before generating emails from the Brew Public API. Read `GET /v1/brand` before generating an email. The response is the brand row itself, with `ready` at the top level. ## Read the Brand ```bash curl theme={null} curl --fail-with-body "https://brew.new/api/v1/brand" \ -H "Authorization: Bearer $BREW_API_KEY" ``` ```ts SDK theme={null} import { createBrewClient } from '@brew.new/sdk' const brew = createBrewClient({ apiKey: process.env.BREW_API_KEY! }) const brand = await brew.brand.get() console.log(brand.brandId, brand.domain, brand.status, brand.ready) ``` A brand key resolves its brand automatically. An organization key uses `X-Brand-Id`, or the SDK's client `brandId`. See [Authentication](/api-reference/api/authentication). ## Gate Generation on Readiness Continue with the same SDK client: ```ts theme={null} const current = await brew.brand.get() if (!current.ready) { throw new Error(`Brand is ${current.status}; wait for extraction to finish.`) } await brew.emails.generate({ prompt: 'A spring launch announcement' }) ``` Readiness is `true` when extraction is `completed`. If the brand is still extracting, wait and repeat the read. If extraction failed, inspect its `error` and resolve the setup in Brew. See [Add Your Brand](/get-started/add-your-brand) for setup and [Errors](/api-reference/api/errors) for `BRAND_NOT_READY` and `BRAND_NOT_FOUND`. To create and extract customer brands from your own backend, follow [Build a White-Label Email Editor](/sdks/typescript/white-label-email-editor#extract-a-customers-brand). It shows `brands.create()`, lifecycle polling with `brands.get({ brandId })`, and reading the extracted design context. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Monitor Email Sends Source: https://docs.brew.new/api-reference/guides/monitor-campaign-sends List sends, poll a single send's lifecycle and stats, read its per-recipient events, and fire a test send with the Brew Public API v1. A **send** is the unit of delivery and analytics in Brew. Every production send with `POST /v1/sends` returns a `sendId` for lifecycle status and aggregate `stats`. Test sends return a completed status and recipient without a send row. Sends read at their own root: the list is `/v1/sends`, and one send is a path read. * `GET /v1/sends`: list every campaign send for the brand, with `stats`. * `GET /v1/sends/{sendId}`: one send's lifecycle status + stats, as a bare row. * `GET /v1/sends/{sendId}?include=events`: the same row with its per-recipient event feed inlined. * `GET /v1/sends?emailId=…`: every send for one design. These reads need the `sends` scope; see [Authentication](/api-reference/api/authentication) for scopes and [Rate Limits](/api-reference/api/rate-limits) for their budgets. Moving off `GET /v1/analytics/sends`? See the [v1 migration](/api-reference/api/v1-migration). ## List Recent Sends ```bash curl theme={null} curl -G "https://brew.new/api/v1/sends" \ -H "Authorization: Bearer $BREW_API_KEY" \ --data-urlencode "status=completed" \ --data-urlencode "limit=50" ``` ```ts SDK theme={null} import { createBrewClient } from '@brew.new/sdk' const brew = createBrewClient({ apiKey: process.env.BREW_API_KEY! }) const { data, pagination } = await brew.sends.list({ status: 'completed', limit: 50 }) for (const send of data) { console.log(send.sendId, send.status, send.stats?.delivered, '/', send.stats?.sent) } ``` The response is the uniform list envelope: `{ data, pagination }`. See [Pagination](/api-reference/api/pagination) for the cursor loop, or use the SDK auto-pager: ```ts theme={null} for await (const send of brew.sends.listAll({ status: 'completed' })) { console.log(send.sendId, send.stats?.opened) } ``` A status filter accepts the one send vocabulary that [One Status Vocabulary](/api-reference/api/v1-migration#5-one-status-vocabulary) owns. The older `sent` / `sending` / `partially_sent` spellings are rejected as `400 INVALID_REQUEST`. ## Poll a Single Send Read one send by id to watch it move from `queued` to `running` to `completed` and to read its rolled-up `stats`. The response is the send row itself, with no `data` wrapper. An unknown or cross-brand id returns `404 SEND_NOT_FOUND`. ```bash curl theme={null} curl "https://brew.new/api/v1/sends/Cu3GIDFegMRwhokaDbgoY" \ -H "Authorization: Bearer $BREW_API_KEY" ``` ```ts SDK theme={null} const send = await brew.sends.get('Cu3GIDFegMRwhokaDbgoY') console.log(send.status, send.completedAt, send.stats) ``` ## Read the Per-Recipient Feed Once a send is in flight, drill into its individual delivery events: `sent` / `delivered` / `opened` / `clicked` / `bounced` / `complained` / `unsubscribed`. Add `?include=events` to the single-send read to inline a bounded first page of the feed on the same row. For the full, filterable history, use `GET /v1/analytics/events` with the same `sendId` (see [Explore Per-Contact Engagement](/api-reference/guides/per-contact-engagement)). ```bash curl theme={null} curl -G "https://brew.new/api/v1/sends/Cu3GIDFegMRwhokaDbgoY" \ -H "Authorization: Bearer $BREW_API_KEY" \ --data-urlencode "include=events" ``` ```ts SDK theme={null} const send = await brew.sends.get('Cu3GIDFegMRwhokaDbgoY', { include: 'events' }) for (const event of send.events ?? []) { console.log(event.recipientEmail, event.url, event.occurredAt) } ``` ## Join an Automation Run to Its Deliveries An automation send is one row per recipient, so it is never listed brand-wide. Pass a join filter instead and `kind=automation` is implied: `automationId`, `automationRunId`, `audienceRunId`, or `triggerInstanceId`. ```bash theme={null} curl -G "https://brew.new/api/v1/sends" \ -H "Authorization: Bearer $BREW_API_KEY" \ --data-urlencode "automationRunId=jw59ogmh9304b1mdqc3jqzfapbtrxfx4" ``` Naming a run outside the brand returns `404 AUTOMATION_RUN_NOT_FOUND` or `404 AUDIENCE_RUN_NOT_FOUND`. Combining a join filter with `kind=campaign` or with `emailId`, or asking for `kind=automation` without one, returns `400 INVALID_REQUEST`. ## Pause, Resume, or Cancel a Send Lifecycle changes are action sub-paths, not a body verb: | Action | Route | Eligible when | | - | - | - | | Cancel | `POST /v1/sends/{sendId}/cancel` | The send is not terminal and is not an automation send. Otherwise `409 SEND_NOT_CANCELLABLE`. | | Pause | `POST /v1/sends/{sendId}/pause` | A gradual send is running. Pausing a send its operator already paused returns the same `200` and changes nothing. Otherwise (including a send held at the plan limit or for its domain) `409 SEND_NOT_PAUSABLE`. | | Resume | `POST /v1/sends/{sendId}/resume` | A gradual send is paused with `pauseReason: manual`. Otherwise `409 SEND_NOT_RESUMABLE`. | A paused send carries `pauseReason`. `manual` means someone paused it; resume it to continue. The other two are holds Brew places, and both resume on their own, so resume refuses them: * `plan_limit`: the organization ran out of monthly email sends. The send waits until the allowance has room. * `domain_unsendable`: the sending domain stopped passing DNS. The send waits for it to pass again and fails after 7 days. Cancel a held send if it should not go out. See [Pause, Resume, or Cancel a Send](/create-emails/send-options#pause-resume-or-cancel-a-send). ## Send a Test Email The same `POST /v1/sends` endpoint sends a test when you pass `test: true`. A test send forces the Brew default sender unless you name a verified org-owned `domainId`, requires no audience, does **not** write a send row, and resolves synchronously to `200 { status: 'completed', recipient }`. A test reaches only a teammate with access to the brand, an address on a verified sending domain of the brand, or, when a signed-in person makes the request (not an API key), that person's own address or one on their company domain. An API key has no person behind it, so a test sent with a key reaches only teammates and verified sending domains. Any other address is refused with [`422 TEST_RECIPIENT_NOT_ALLOWED`](/api-reference/api/errors#test-recipient-not-allowed), and `details.recipients` lists the refused addresses. ```bash curl theme={null} curl -X POST "https://brew.new/api/v1/sends" \ -H "Authorization: Bearer $BREW_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "test": true, "emailId": "d4tPyXu3HwcN0XZLCePhI", "subject": "Preview: Black Friday", "to": "you@example.com" }' ``` ```ts SDK theme={null} const test = await brew.emails.send({ test: true, emailId: 'd4tPyXu3HwcN0XZLCePhI', subject: 'Preview: Black Friday', to: 'you@example.com', }) if (!('recipient' in test)) { throw new Error('Expected a test-send response.') } console.log(test.status, test.recipient) ``` The live (campaign) send is the same endpoint **without** `test`. It returns `202 { status: 'queued' | 'scheduled' | 'pending_approval', sendId, scheduledAt? }`. `pending_approval` waits for an organization administrator to approve the send. There is no `runId`: `sendId` is the only handle you need. Name the sender with `from: { email, name? }` and put `replyTo` at the top level. See [Async jobs & polling](/api-reference/api/async-jobs). ## Related * `GET /v1/sends` in the [Public API v1 reference](/api-reference/api/api-introduction) (sidebar): full parameter + schema reference. * [Errors](/api-reference/api/errors): `SEND_NOT_FOUND`, `DOMAIN_NOT_READY`, `AUDIENCE_NOT_FOUND`, `SEND_QUOTA_EXCEEDED`, `TEST_RECIPIENT_NOT_ALLOWED`. * [Migrating to the cleaned-up v1 surface](/api-reference/api/v1-migration): the full old-to-new map. * [Sends (SDK)](/sdks/typescript/resources): `emails.send` (pass `test: true` for a QA send), `sends.list`, `sends.get` (`include: 'events'`). ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Explore Per-Contact Engagement Source: https://docs.brew.new/api-reference/guides/per-contact-engagement Pull one contact's email events, slice brand events by type, automation, or send, and read the open-time profile behind a contact's best send time. `GET /v1/analytics/events` is a unified event feed across four domains: `email`, `automation`, `trigger`, and `inbound`. Filter by `recipient` to get one contact's email events (a recipient filter narrows the feed to the `email` domain), or by `eventType` / `automationId` / `sendId` to slice the whole brand. Requires the `emails` scope. Every delivery event attaches to the `sendId` it came from, so you can also scope the feed to a single send: pass `?sendId=` here, or read that send with `GET /v1/sends/{sendId}?include=events` for a bounded first page on the row itself. See [Monitor Email Sends](/api-reference/guides/monitor-campaign-sends). When `from`/`to` are omitted the API defaults to the last 7 days, except for a `sendId` or `automationRunId` read, which spans that send or run unless `from`/`to` are given. The response carries `{ data, pagination, range }`. ## One Contact's Email Events ```bash curl theme={null} curl -G "https://brew.new/api/v1/analytics/events" \ -H "Authorization: Bearer $BREW_API_KEY" \ --data-urlencode "recipient=jane@example.com" \ --data-urlencode "limit=100" ``` ```ts SDK theme={null} import { createBrewClient } from '@brew.new/sdk' const brew = createBrewClient({ apiKey: process.env.BREW_API_KEY! }) const { data, range } = await brew.analytics.events({ recipient: 'jane@example.com', }) for (const event of data) { console.log(event.occurredAt, event.domain, event.eventType, event.emailName) } ``` ## Export Every Page The SDK auto-pager walks every page so you never touch the cursor: ```ts theme={null} const timeline = [] for await (const event of brew.analytics.eventsAll({ recipient: 'jane@example.com', from: '2026-01-01T00:00:00.000Z', })) { timeline.push(event) } ``` ## Filter by Event Type or Automation ```ts theme={null} // Every bounce in the brand over the last 7 days const { data: bounces } = await brew.analytics.events({ eventType: 'bounced' }) // Everything that happened inside one automation const { data: runEvents } = await brew.analytics.events({ automationId: 'yFteJhadz0wK23cscvmtt', }) // Every event from one campaign send const { data: sendEvents } = await brew.analytics.events({ sendId: 'Cu3GIDFegMRwhokaDbgoY', }) ``` `eventType` takes one exact type, such as `delivered`, `opened`, `clicked` or `bounced` (not `open` or `click`); any other value is a `400 INVALID_REQUEST`. A `sendId` read covers the whole send, so the last example needs no `from`. The filter is `recipient`; the row field it matches is `recipientEmail`. Each `EventRow` carries `domain`, `eventType`, `recipientEmail?`, `sendId?`, `emailId?`/`emailName?`, `automationId?`/`automationName?`, `nodeId?`, `mode?` (`live` | `test`), and a human `summary?`. ## Count Events Instead of Listing Them Add `groupBy`, `bucket`, or both to count the email events the same filters list instead of returning them. `groupBy` takes one or two comma-separated fields: `eventType`, `emailId`, `automationId`, `sendId`, `source`, `link`, `recipientDomain`, `unsubscribeReason`. `bucket` takes `day`, `week` or `month` (UTC; weeks start Monday). In the SDK and CLI, counting is its own call: `analytics.eventCounts()` and `brew-cli analytics event-counts`. Since SDK 13.4.0, `analytics.events()` refuses `groupBy` and `bucket` with a `BrewInputError`. ```bash curl theme={null} # Clicks per link on one send curl -G "https://brew.new/api/v1/analytics/events" \ -H "Authorization: Bearer $BREW_API_KEY" \ --data-urlencode "sendId=Cu3GIDFegMRwhokaDbgoY" \ --data-urlencode "eventType=clicked" \ --data-urlencode "groupBy=link" # Email events per type per day since September 1 curl -G "https://brew.new/api/v1/analytics/events" \ -H "Authorization: Bearer $BREW_API_KEY" \ --data-urlencode "groupBy=eventType" \ --data-urlencode "bucket=day" \ --data-urlencode "from=2026-09-01T00:00:00.000Z" # Unsubscribes per stated reason curl -G "https://brew.new/api/v1/analytics/events" \ -H "Authorization: Bearer $BREW_API_KEY" \ --data-urlencode "groupBy=unsubscribeReason" ``` ```ts SDK theme={null} // Clicks per link on one send const perLink = await brew.analytics.eventCounts({ sendId: 'Cu3GIDFegMRwhokaDbgoY', eventType: 'clicked', groupBy: ['link'], }) // Email events per type per day since September 1 const perDay = await brew.analytics.eventCounts({ groupBy: ['eventType'], bucket: 'day', from: '2026-09-01T00:00:00.000Z', }) // Unsubscribes per stated reason const reasons = await brew.analytics.eventCounts({ groupBy: ['unsubscribeReason'], }) ``` ```bash CLI theme={null} brew-cli analytics event-counts --send-id Cu3GIDFegMRwhokaDbgoY --event-type clicked --group-by link brew-cli analytics event-counts --group-by eventType --bucket day --since 2026-09-01T00:00:00Z brew-cli analytics event-counts --group-by unsubscribeReason ``` The answer lists the largest groups first, with `count` for the total and `otherCount` for the groups left out. On a busy window it answers `truncated: true`; narrow `from`/`to` or add `eventType` to count all of it. The `GET /v1/analytics/events` page in the [Public API v1 reference](/api-reference/api/api-introduction) has the full response and limits. A count takes no `cursor` or `automationRunId` (`400`), and `limit` is ignored. `count` counts events, not unique recipients, and an unsubscribe counts once per reason it gave. On a group of opened, clicked or delivered events (not grouped by `link`), `recipients` counts each recipient once per message within `range`, leaving out repeat and machine opens and clicks; with `bucket`, a recipient falls in the period of their first open or click. For windowed unique totals across the brand, use `GET /v1/analytics/overview`. Over MCP, `get_email_analytics` with `report.kind: "events"` takes the same `groupBy` and `bucket`. ## The Open-Time Profile Brew keeps one open-time profile per contact: when in the day they open email. Ask a contact read for `openProfile` to get it. [Intelligent send](/create-emails/send-options#intelligent-send) doesn't read this profile. It times each contact from their human opens and clicks directly. ```bash curl theme={null} curl "https://brew.new/api/v1/contacts/jane%40example.com?include=openProfile" \ -H "Authorization: Bearer $BREW_API_KEY" ``` ```ts SDK theme={null} const contact = await brew.contacts.get('jane@example.com', { include: 'openProfile', }) const best = contact.openProfile?.bestSendMinuteUtc if (best !== undefined) { const hh = String(Math.floor(best / 60)).padStart(2, '0') const mm = String(best % 60).padStart(2, '0') console.log(`Best send time: ${hh}:${mm} UTC`) } ``` ```bash CLI theme={null} brew-cli contacts get jane@example.com --include openProfile --json ``` `openProfile` is `null` until Brew has recorded an open for the contact. Otherwise it holds a 48-slot `histogram` of opens per UTC half hour. With enough history, it also names `bestSendMinuteUtc` (minutes after midnight UTC) and a `confidence` from 0 to 1. The contact read in the [Public API v1 reference](/api-reference/api/api-introduction) lists every field. The profile counts opens as the mail provider reports them. Privacy proxies and security scanners that fetch images on delivery look like opens here, and nothing in the profile tells them apart, so don't use it for bot detection. The event feed does classify each open: `GET /v1/analytics/events` leaves machine-classified opens out unless you pass `includeMachineOpens=true`. ### For a Page of Contacts `POST /v1/contacts/search` takes `include: ["openProfile"]` in its body and attaches the profile to each returned contact. Each row costs a profile read, so a page holds at most 10 contacts, whatever `limit` asks; `pagination.limit` reports the size read. `count: true` can't be combined with it (`400 INVALID_REQUEST`). Over MCP, `search_contacts` takes the same `include`. ```bash theme={null} curl -X POST "https://brew.new/api/v1/contacts/search" \ -H "Authorization: Bearer $BREW_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "audienceId": "jn7a8w4q8m9k2p1x7c3b5v6n9h7s2d4f", "include": ["openProfile"] }' ``` Either read needs the `emails` scope as well as `contacts`, because the profile is engagement data. A `contacts`-only key gets `403 INSUFFICIENT_PERMISSIONS` when it asks for `openProfile`, and reads contacts without it as before. ## Related * `GET /v1/analytics/events` in the [Public API v1 reference](/api-reference/api/api-introduction) (sidebar): full schema + filters. * [Reading analytics](/analytics/reading-analytics): the dashboard view of the same data. * [Pagination](/api-reference/api/pagination): cursor semantics. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Read Brew Insights Source: https://docs.brew.new/api-reference/guides/read-brew-insights List the findings Brew Insights keeps about your brand's email, check how fresh they are, and read one in full with its frozen metrics. Brew Insights watches the brand's email and records what it finds: deliverability problems, campaigns that did better or worse than usual, timing, and audience and automation opportunities. In the app, the **Brew Insights** cards on **Home** open the Insights page. Over the API, `GET /v1/insights` lists the findings as that page ranks them, and `GET /v1/insights/{insightId}` reads one in full. Both reads are free, need the `emails` scope, and count against the `analytics.read` [rate limit](/api-reference/api/rate-limits). An organization key names the brand with `X-Brand-Id`, as on every brand-scoped route. The API only reads. You start a run by hand in the app, where it opens a Brew chat and uses [credits](/analytics/insights#what-a-run-costs). ## List the Findings ```bash curl theme={null} curl -G "https://brew.new/api/v1/insights" \ -H "Authorization: Bearer $BREW_API_KEY" \ --data-urlencode "severity=critical" ``` ```ts SDK theme={null} import { createBrewClient } from '@brew.new/sdk' const brew = createBrewClient({ apiKey: process.env.BREW_API_KEY! }) const page = await brew.insights.list({ severity: 'critical' }) for (const finding of page.data) { console.log(finding.severity, finding.title, finding.description) } ``` ```bash CLI theme={null} brew-cli insights list --severity critical ``` It answers `200` with `{ data, pagination, freshness }`, most severe first and then by score: ```json theme={null} { "data": [ { "insightId": "k17a8m2v4w5x6y7z8a9b0c1d2e3f4g5h", "title": "Spring sale", "description": "Spring sale bounced 6.2% of sends, above the 6% line.", "severity": "critical", "confidence": "high", "kind": "insight", "category": "deliverability", "detectorId": "deliv.bounce_rate_breach", "state": "active", "firstSeenAt": "2026-10-01T12:00:00.000Z", "lastSeenAt": "2026-10-02T06:04:12.000Z", "recurrenceCount": 1, "action": { "kind": "navigate", "label": "Open campaign analytics", "url": "https://brew.new/analytics/sends/Vx2mZ8t9QbY3sW1vR0pLd" }, "url": "https://brew.new/insights/k17a8m2v4w5x6y7z8a9b0c1d2e3f4g5h" } ], "pagination": { "limit": 100, "cursor": null, "hasMore": false }, "freshness": { "dataAsOf": "2026-10-02T06:00:00.000Z", "lastSuccessfulRunAt": "2026-10-02T06:04:12.000Z", "latestAttempt": { "status": "succeeded", "at": "2026-10-02T06:04:12.000Z" } } } ``` `description` is the detector's own headline. Quote it rather than restating its numbers. `kind` says what sort of finding it is: `answer` reports what happened, `insight` is a change that passed its statistical test, and `strategy` is a recommended next step. `action`, when present, either links to a page in Brew (`navigate`) or carries the request the Insights page would send to Brew's assistant (`assistant`, with `intent` and `prompt`). | Query | Values | What it does | | - | - | - | | `state` | `open` (default), `all` | `open` lists active findings and snoozes that have ended. `all` adds resolved, cleared, dismissed, and stale findings, and snoozes still in effect. | | `severity` | `critical`, `warning`, `opportunity`, `info` | Keeps one severity, up to 200 findings of its own however many more severe ones exist. | | `include` | `pulse`, `report`, `suggestions`, `memo` | Comma-separated expansions. See [Add the Intelligence Layer](#add-the-intelligence-layer). | | `limit`, `cursor` | 1 to 100 (default 100) | Page through the list. The engine keeps at most 200 findings in view, so at the default limit a full walk is at most two pages. See [When the Findings Change Mid-Walk](#when-the-findings-change-mid-walk). | ### When the Findings Change Mid-Walk The list is ranked again on every request, so it can change between pages. A refused page answers `400 INVALID_REQUEST` with `param: "cursor"`. Read again from the first page with the same `state` and `severity`. [Cursor Semantics](/api-reference/api/pagination#cursor-semantics) owns the rule. ## Check Freshness Before You Report Every page carries `freshness`, whatever you filter on: * `dataAsOf` is how current the data behind the findings is. It is `null` before the first successful run. * `lastSuccessfulRunAt` is when the engine last finished a run. * `latestAttempt` is the newest run and its `status`: `succeeded`, `running`, `failed`, or `unknown`. A `failed` attempt means the findings may be stale, so say so when you report them. ## Add the Intelligence Layer `include` adds what the Insights page shows beside the findings. Each expansion is a top-level key on the page. `pulse`, `report`, and `memo` are `null` until they exist, and `suggestions` is an empty array when there are none. | Token | Key | What it holds | | - | - | - | | `pulse` | `pulse` | The last 7 days against the 7 before: delivered, unique opens and clicks, and unsubscribes, each with its prior value, plus open and click rates. `openDirection` and `clickDirection` read `up` or `down` only when the change is statistically real. `countsOnly: true` means too few deliveries for rates. | | `report` | `report` | The latest intelligence report the analysis agent published: `reportId`, the `chatId` that wrote it, `runTrigger` (`manual` or `scheduled`), and its `insights`, each with a `title`, `body`, `impact`, and the `suggestionId` it proposes. | | `suggestions` | `suggestions` | Proposed and launched suggestions, up to 25, most recently updated first. Each has a `prompt` (exactly what launching it asks Brew to do), `status`, `rationale`, and the `executionChatId` a launched one runs in. | | `memo` | `memo` | The analysis agent's memory across runs, as `markdown` of at most 8,192 bytes, with its `version` and `updatedAt`. | `measured: false` means open and click measurements are unavailable. Hide their counts and rates, including numeric zeros, without inferring that domain tracking is off. When `measured` is true, zero is still a value. The expansions describe the brand, not the page, so they are the same on every page. Ask for them on the first page only. ```bash curl theme={null} curl -G "https://brew.new/api/v1/insights" \ -H "Authorization: Bearer $BREW_API_KEY" \ --data-urlencode "include=pulse,report,suggestions,memo" ``` ```ts SDK theme={null} const page = await brew.insights.list({ include: ['pulse', 'report', 'suggestions', 'memo'], }) if ( page.pulse?.measured && !page.pulse.countsOnly && page.pulse.openRatePct != null ) { console.log(`Opens ${page.pulse.openDirection}: ${page.pulse.openRatePct}%`) } ``` ```bash CLI theme={null} brew-cli insights list --include pulse,report,suggestions,memo ``` ## Read One Finding Pass the `insightId` a list row carries. ```bash curl theme={null} curl "https://brew.new/api/v1/insights/k17a8m2v4w5x6y7z8a9b0c1d2e3f4g5h" \ -H "Authorization: Bearer $BREW_API_KEY" ``` ```ts SDK theme={null} const finding = await brew.insights.get('k17a8m2v4w5x6y7z8a9b0c1d2e3f4g5h') console.log(finding.method?.resolvesWhen) ``` ```bash CLI theme={null} brew-cli insights get k17a8m2v4w5x6y7z8a9b0c1d2e3f4g5h ``` The answer is the bare finding: the list row's fields plus these. | Field | What it holds | | - | - | | `metrics` | The numbers behind the finding, keyed by name and frozen when it was computed. Each has a `kind` (`count`, `rate`, `share`, `duration`, `delta`, `hourOfDay`, `multiple`, `rank`, `interval`, or `label`) that says how to read it. These are the only numbers to quote about the finding. | | `evidence` | Links that support it, each `{ label, url? }`. | | `subject` | What it is about: `{ kind, id, label }`, such as one send. | | `rationale` | The reasoning behind it, or `null`. | | `method` | How the detector works: `what` it measures, `how`, what it is `comparedAgainst`, what `resolvesWhen`, and an optional `caveat`. | | `generatedBy` | The engine run that produced it: its `trigger`, when it started and completed, and `blindSpots`, what that run could not see. | | `closedReason`, `closedAt`, `lastActedAt`, `churnCount` | Its lifecycle: why and when it closed, when someone last marked it acted on, and how often it has closed and reopened. Acting on a finding doesn't close it; it resolves when the detector sees the problem recover. | | `freshness` | The same freshness block the list carries. | ## Errors | Answer | Why | What to do | | - | - | - | | [`400 INVALID_REQUEST`](/api-reference/api/errors#invalid-request) | An unknown query key, `state`, `severity`, or `include` token, or a malformed `cursor` | Fix the request; `param` names the field | | `400 INVALID_REQUEST`, `param: "cursor"` | The findings changed above the cursor since it was issued, or the cursor came from a different `state` or `severity` | Read the list again from the first page, without `cursor`, with the same `state` and `severity` | | [`403 INSUFFICIENT_PERMISSIONS`](/api-reference/api/errors#insufficient-permissions) | The key has no `emails` scope | Use a key with `emails` | | [`404 INSIGHT_NOT_FOUND`](/api-reference/api/errors#insight-not-found) | No finding with that id for this brand. An unknown id, a malformed one, and another brand's finding all answer the same way. | Take the id from `GET /v1/insights` on the same brand | ## From an Agent Over [MCP](/api-reference/mcp/tools), `list_insights` reads the same findings, and `include` is an array (`include: ["pulse", "report"]`). Pass an `insightId` from a row (not a report insight key) and `list_insights` returns that one finding in full, with its frozen metrics, evidence and detector method, as `GET /v1/insights/{insightId}` does. `insightId` cannot be combined with `state`, `severity`, `include`, `limit` or `cursor`. `list_insights` trims long text and cuts its expansions to fit one tool result, and a `truncated` array names each cut; [MCP Page Sizes](/api-reference/api/pagination#mcp-page-sizes) owns that rule. The HTTP read always answers whole. From the shell, [`brew-cli insights list`](/api-reference/cli/commands) takes `--state`, `--severity`, and `--include`, and `--all` returns every finding with the expansions from the first page. ## Related * [List insights](/api-reference/public-v1/insights/list-insights) and [Get an insight](/api-reference/public-v1/insights/get-an-insight) in the Public API v1 reference: every field and its schema. * [Pagination](/api-reference/api/pagination): the cursor envelope and the MCP page sizes. * [Errors](/api-reference/api/errors): the error envelope and every code. * [Reading Analytics](/analytics/reading-analytics): the sends and events behind the findings. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Send Your First Email from Code Source: https://docs.brew.new/api-reference/guides/send-your-first-email-from-code Call the Brew API with curl to generate an on-brand email and receive a test in your inbox when you are new to the Public API. Generate a saved welcome email and receive a test in your own inbox using curl. ## Before You Begin [Add your brand](/get-started/add-your-brand) and wait for extraction to finish. Create a brand API key at [**Settings → API**](https://brew.new/settings/api) with permission to generate emails and send tests. Generation uses [credits](/api-reference/api/credits). You do not need an audience or a verified domain. ```bash theme={null} export BREW_API_KEY="brew_your_api_key" ``` For an organization key, also send `X-Brand-Id` on the requests below. See [Authentication](/api-reference/api/authentication). ## 1. Check Your Brand ```bash theme={null} curl --fail-with-body "https://brew.new/api/v1/brand" \ -H "Authorization: Bearer $BREW_API_KEY" ``` The response has readiness at the top level: ```json theme={null} { "brandId": "kx7b3s7fapqz8mjm12ekz1kxdx87yceg", "domain": "example.com", "status": "completed", "ready": true } ``` Continue when `ready` is `true`. If extraction is running, wait and repeat the read. ## 2. Generate the Design ```bash theme={null} curl --fail-with-body -X POST "https://brew.new/api/v1/emails" \ -H "Authorization: Bearer $BREW_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: first-api-email-001" \ -d '{"prompt":"Create and save a friendly welcome email with one Get started button."}' ``` Generation can take a minute or more. A saved design returns `201` with this shape: ```json theme={null} { "emailId": "YlwZiHLEKRW39MquCfC6C", "emailVersionId": "GdDGxo23zbtlosRuwfgGV", "html": "...", "group": null } ``` Copy the `emailId`. If the result contains only `response`, read that explanation and adjust your prompt. ## 3. Send Yourself a Test Replace `YOUR_EMAIL_ID` with the returned ID and `you@example.com` with your own inbox. ```bash theme={null} curl --fail-with-body -X POST "https://brew.new/api/v1/sends" \ -H "Authorization: Bearer $BREW_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: first-api-test-001" \ -d '{"test":true,"emailId":"YOUR_EMAIL_ID","subject":"Welcome aboard","to":"you@example.com"}' ``` The test returns `200`: ```json theme={null} { "status": "completed", "recipient": "you@example.com" } ``` Open **\[TEST] Welcome aboard** in your inbox. The test uses Brew's default sender and creates no production send row. Reuse a retry key when recovering the same request. Use a new key for a new design or test. [Idempotency](/api-reference/api/idempotency) explains replay behavior. ## Keep Going * [Monitor Email Sends](/api-reference/guides/monitor-campaign-sends): production delivery and engagement. * [TypeScript Quickstart](/sdks/typescript/quickstart): use the official client. * [OpenAPI Codegen](/sdks/openapi-codegen): generate a client for another language. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Typed Payload Contracts Source: https://docs.brew.new/api-reference/guides/typed-payload-contracts Generate TypeScript contracts for trigger payloads, store and version them, dry-run payloads, and gate drift in CI before a fire reaches production. Every payload you send to Brew has a contract: the trigger's `payloadSchema`, declared when the trigger is created (integration triggers declare theirs per provider event). Every fire of `POST /v1/automations/triggers/{triggerEventId}/fire` is validated against it. You can also store a richer contract per trigger, versioned and renderable as types, which the `/contract` endpoints below cover. This guide turns those contracts into TypeScript types in your codebase, keeps them from drifting, and shows where Brew checks real fires against them. > [!NOTE] > > Nested payload values (objects and arrays) are accepted everywhere. Address a nested leaf by its dotted path, such as `{{ trigger.user.plan }}`. See [Nested Payloads](/create-emails/merge-tags#nested-payloads). ## Generate Types with brew-cli `brew-cli types` writes one file with a type per trigger contract (the command needs a key with the `automations` scope): ```bash theme={null} brew-cli types --out src/brew-contracts.ts ``` Every trigger in the brand is included (every page of the trigger list, nothing is truncated), transactional-purpose flows and marketing flows alike. The contract lives on the trigger either way. The output is deterministic, with a content hash in the header: ```ts theme={null} // brew:contracts sha256:6f1c… /** Payload for POST /v1/automations/triggers/tri_signup/fire */ export type UserSignedUpPayload = { email: string seats?: number | null | "" } /** Payload for POST /v1/automations/triggers/tri_order_receipt/fire */ export type OrderReceiptPayload = { email: string order: { total: number items: Array<{ name: string qty?: number | null | "" }> } note?: string | null } ``` The CLI reads each trigger's authoritative `/contract?format=ts` artifact, matching in-app Copy as TypeScript and the SKILL.md brief. Stored contracts keep their minted type name when a trigger is renamed. A derived contract uses PascalCase of the current trigger title plus `Payload`. Colliding names get the trigger id appended so the file always compiles. A failed contract read leaves the existing output file untouched. The generated types describe accepted inputs. A field is optional when `required: false` or a fallback satisfies its presence requirement. Those fields also accept `null` or an empty string, which Brew treats as missing. The API resolves fallbacks; generated validators do not insert them. A required field without a fallback must be present. The `email` field identifies the recipient downstream automations route on. In CI, gate drift with: ```bash theme={null} brew-cli types --check ``` The command exits `1` when the brand's contracts no longer match the committed file, which is the signal to regenerate and review the diff. A trigger schema edit shows up as a type change in code review instead of a runtime surprise. ## Store a Contract Brew derives a contract on every read, so the guide above works with no setup. You can also **store** one per trigger. A stored contract is content-hash versioned and served from `GET /v1/automations/triggers/{triggerEventId}/contract`. The response says which kind you got. `source: "stored"` carries a `contractHash`, a `version`, and an `enforcement` mode. With no stored contract, `source` is derived instead. `derived_from_schema` is built from the trigger's flat `payloadSchema`, and the enum also allows `derived_from_template`. A derived contract can carry `type: "unknown"` where there was no type evidence to work from. Fields form a tree. Scalars are `string`, `int`, `float`, `boolean`, `date`, or `enum`. An `object` node carries `children`. An `array` node carries either `children` for an element object shape, or `itemType` for scalar elements. Pass `?format=` to get a generated artifact instead of the JSON contract: ```bash theme={null} # The contract as JSON (default) curl "https://brew.new/api/v1/automations/triggers/tri_signup/contract" \ -H "Authorization: Bearer $BREW_API_KEY" # Or as a TypeScript type, a Zod schema, JSON Schema, or a SKILL.md brief curl "https://brew.new/api/v1/automations/triggers/tri_signup/contract?format=ts" \ -H "Authorization: Bearer $BREW_API_KEY" ``` The response shape depends on `format`. The default, `json`, returns `{ format, fields }` and no `content`. `ts`, `zod`, `jsonschema`, and `skill` each return `{ format, content }` and no `fields`. Branch on `format` before reading either key. `POST /v1/payload-contracts/infer` is different: it returns `{ fields, issues }`, with no `format` or `content`. `date` fields accept date-only strings such as `2026-10-12` and timestamps such as `2026-10-12T16:00:00.000-04:00` or `2026-10-12T20:00:00.000Z`. Values keep their supplied representation. The compatibility rule requires a `YYYY-MM-DD` prefix and a successful JavaScript `Date.parse` check. This preserves the existing local and space-separated datetime forms. Date examples and fallbacks must pass that same check before a contract can be saved. Generated Zod schemas apply this rule directly. They reject undeclared keys in `strict` mode and strip them in `prune` mode, including inside nested objects and arrays. They validate contract inputs; authentication, recipient eligibility, and fire resource limits remain server checks. JSON Schema exports use the custom `brew-date` format plus a shared prefix `pattern`. Register the parseability check in your validator for complete date validation. Standard `date-time` alone would exclude date-only and legacy accepted forms. Given a fetched contract response named `contract`, register the format with AJV 2020: ```ts theme={null} import Ajv2020 from 'ajv/dist/2020.js' const ajv = new Ajv2020({ strictSchema: false }) ajv.addFormat('brew-date', { type: 'string', validate: (value: string) => !Number.isNaN(Date.parse(value)), }) if (contract.format !== 'jsonschema' || typeof contract.content !== 'string') { throw new Error('Request the contract with format=jsonschema') } const validate = ajv.compile(JSON.parse(contract.content)) ``` The exported `pattern` checks the prefix separately. JSON Schema defaults describe Brew's fallback behavior; they are not instructions to mutate the integration's payload. Declare or replace the stored contract with `PUT` on the same URL: ```bash theme={null} curl -X PUT "https://brew.new/api/v1/automations/triggers/tri_signup/contract" \ -H "Authorization: Bearer $BREW_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "fields": [ { "key": "email", "type": "string", "required": true }, { "key": "plan", "type": "enum", "required": false, "enumValues": ["free", "pro"], "fallbackValue": "free" }, { "key": "order", "type": "object", "required": false, "children": [{ "key": "total", "type": "float", "required": true }] } ] }' ``` Six rules are worth knowing before you write one: * **The whole tree validates before anything is written.** Unknown-typed nodes are refused, so declare a concrete type. Keys must be unique per level, and an `object` field must declare at least one child. * **Two top-level fields can't land on one contact field.** A fire copies top-level scalar fields onto the contact under their [folded camelCase name](/audience/manage-contacts#property-names), so `plan` and `Plan`, or `team_size` and `Team Size`, would write one field twice. A `PUT` declaring such a pair returns `400 INVALID_REQUEST` with `param: fields`, and flat `POST` and `PATCH /v1/automations/triggers` refuse the same pair with `400`. Rename one, or set `syncToContact: false` on one to keep its value off the contact. Fields a fire never copies are exempt: `object` and `array` containers, nested keys, `secret` fields and `syncToContact: false` fields. * **A trigger contract keeps its `email` field.** It needs a top-level `{ "key": "email", "type": "string", "required": true }` so automations can resolve a recipient. * **`fields` is optional once a contract is stored.** Changing only the enforcement mode is a `PUT` with just `enforcement`, so you never re-send the tree to flip a switch. On a trigger with no stored contract yet, a body without `fields` returns `400 INVALID_REQUEST`. * **The version tracks behavior, not prose.** Keys, types, `required`, and fallbacks bump it. Editing a `description` or an example does not. * **Mark one-time values `secret`.** Set `secret: true` on a code, a sign-in link, or a reset token. The value is used only to render the email. It is never stored on the contact, in logs, or in analytics, and it can't be used in filters, splits, or recipient fields. Scalars only, never `email`. `pii` still controls how a value is masked in logs, so a field can carry both. See [Transactional Email](/create-emails/transactional-email#what-to-know-before-you-ship-one). Declaring a contract does not change what happens at fire time. Enforcement is `off` until you turn it on, and the two enforcing modes are `prune` and `strict`. They differ only in how they treat keys the contract does not declare. `prune` drops them, `strict` fails the payload. Declared-field rules are identical in both. > [!WARNING] > > While a published automation uses the trigger, changes must stay backward > compatible. Enforcement can loosen (`strict` to `prune`, `prune` to `off`) > but not tighten. Removing, retyping, or enum-narrowing a field, or adding a > required field without a fallback, is also refused. > > A refused change returns > [`409 CONTRACT_LOCKED_BY_PUBLISHED_AUTOMATIONS`](/api-reference/api/errors#contract-locked-by-published-automations). > To make one, unpublish or detach those automations first. > > Under `prune`, a misspelled key is dropped silently and the declared field > falls back to its default. Every status signal still reports success, so keep > transactional triggers on `strict`. ## Draft a Contract from an Example Writing a field tree by hand is tedious when you already have the payload. Post a real example to `POST /v1/payload-contracts/infer` and Brew types it for you: ```bash theme={null} curl -X POST "https://brew.new/api/v1/payload-contracts/infer" \ -H "Authorization: Bearer $BREW_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "example": { "email": "jane@example.com", "order": { "total": 9.5, "placedAt": "2026-04-08T12:00:00.000Z" } } }' ``` Integers and floats split automatically, full ISO timestamps become `date`, and object and array shapes are walked recursively. Every inferred field comes back `required: true`, so relax the optional ones yourself. Inference degrades honestly. A `null` or an empty array carries no type evidence, so those land in `issues` with the offending path instead of a guess. Nothing is saved either way: review the draft, then `PUT` it to the trigger's `/contract`. ## Dry-Run a Payload `POST /v1/automations/triggers/{triggerEventId}/contract/validate` runs a payload through the same validator the live path uses, against the stored contract when one exists. Nothing fires, sends, or writes. ```bash theme={null} curl -X POST "https://brew.new/api/v1/automations/triggers/tri_signup/contract/validate" \ -H "Authorization: Bearer $BREW_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "payload": { "email": "jane@example.com", "coupon": "SPRING" }, "enforcement": "strict" }' ``` > [!WARNING] > > An invalid payload still returns `200`. The verdict is the body, not the > status code, so check `valid` rather than the response status. Read `valid`, the per-field `errors` and `warnings`, `resolvedPayload` with fallbacks applied, and `prunedKeys` for anything the contract does not declare. The optional `enforcement` field previews `prune` or `strict` in place of the stored mode. That is how you find out what `strict` would reject before you arm it. ## Pin the Types in SDK Calls `fire` accepts a payload type parameter, so call sites compile against the contract: ```ts theme={null} import { createBrewClient } from '@brew.new/sdk' import type { OrderReceiptPayload, UserSignedUpPayload } from './brew-contracts' const brew = createBrewClient({ apiKey: process.env.BREW_API_KEY }) await brew.automations.triggers.fire({ triggerEventId: 'tri_signup', payload: { email: 'jane@example.com', seats: 3 }, }) // A transactional flow fires the same way. The receipt automation's // send step uses a transactional-purpose sending domain. await brew.automations.triggers.fire({ triggerEventId: 'tri_order_receipt', payload: { email: 'jane@example.com', order: { total: 42, items: [{ name: 'Beans' }] } }, }) ``` A missing required field or a wrong scalar type is a compile error. The wire request is unchanged; the generics are type-level only. ## Fetch the Wiring Brief for an Agent The trigger read accepts `?include=skill`, which adds a `skill` field: a complete SKILL.md-shaped brief (endpoint, auth, the typed contract inline, copy-paste snippets, and a test loop) that a coding agent can follow to wire your service. ```bash theme={null} curl "https://brew.new/api/v1/automations/triggers/tri_signup?include=skill" \ -H "Authorization: Bearer $BREW_API_KEY" ``` Save the field as `SKILL.md` in your repo, or hand the URL to an agent. The in-app contract panel offers the same file under **Copy as → Download SKILL.md**, and it is generated from the same source as the API response. ## Preflight Before the First Fire `GET /v1/automations/triggers/{triggerEventId}/readiness` runs the same credential, brand-scope, and permission gates a real fire hits, without firing: ```bash theme={null} brew-cli automations triggers ready tri_signup ``` The body is bare, not wrapped in `details`: `{ ready, blockers[], payloadSchema, endpoint, publishedAutomations, counts }`. `ready: true` means the key, brand scope, and permissions all pass and a fire right now would start at least one run. `ready: false` with a `NO_PUBLISHED_AUTOMATION` blocker still answers `200`; `counts.automations` is `0`. A real fire returns `422 NO_PUBLISHED_AUTOMATION` until a bound automation is published. ## Verify Live Fires in the App Brew checks what your service actually sent against the contract: * A trigger fire's detail sheet (Events page) shows a **Contract check**: the raw body replayed through the same validator the live fire used, so a key the fire dropped is labeled exactly as dropped. * The trigger's page walks you through wiring with a step list whose completion is derived from real data: a key exists, your test fire arrived, an automation is live. Together the loop is: generate types, pin them in calls, gate drift in CI, and read the live ledger when something looks off. ## From an Agent The MCP server covers the same steps. See [MCP Tools](/api-reference/mcp/tools). * `get_trigger_contract` reads a contract in any format. * `infer_payload_contract` drafts one from an example. * `set_trigger_contract` stores it. * `check_trigger` runs the readiness preflight. ## Related * [Merge Tags](/create-emails/merge-tags): how templates read payload values. * [Build an Automation](/create-emails/build-an-automation): wire a trigger to a flow. * [Errors](/api-reference/api/errors): every code above. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Upload a Local Image Source: https://docs.brew.new/api-reference/guides/upload-a-local-image Add an image file from your machine to the brand library with the Brew API in three free calls: open an upload, send the bytes, then add it. `POST /v1/content/add-image` takes a public image URL. A file on your machine takes three free calls, because a JSON request body can't carry a file that size. Open an upload, POST the raw bytes to the URL it returns, then add the image with its `uploadId`. ## What You Can Upload | Limit | Value | | - | - | | Types | PNG, JPEG, GIF, WebP, AVIF, TIFF, and SVG | | Size | 20,000,000 bytes (20 MB). SVG: 2,097,152 bytes (2 MB). The app's **Upload** dialog takes files up to 25 MB. | | Time | 15 minutes to send the bytes, then 15 minutes from when they land to add the image | | Open uploads | 20 per brand at once. An upload stops counting once it is added or expires. | ## Open an Upload Name the file, its type, and its size in bytes (`wc -c < logo.png` prints it). ```bash curl theme={null} curl -X POST "https://brew.new/api/v1/content/image-uploads" \ -H "Authorization: Bearer $BREW_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "fileName": "logo.png", "contentType": "image/png", "size": 48213 }' ``` ```ts SDK theme={null} import { readFile } from 'node:fs/promises' import { createBrewClient } from '@brew.new/sdk' const brew = createBrewClient({ apiKey: process.env.BREW_API_KEY! }) const bytes = await readFile('logo.png') const upload = await brew.content.createImageUpload({ fileName: 'logo.png', contentType: 'image/png', size: bytes.byteLength, }) ``` It answers `201`: ```json theme={null} { "uploadId": "imgup_V1StGXR8_Z5jdHi6B-myT", "uploadUrl": "https://…/uploads/brand-image?uploadId=imgup_V1StGXR8_Z5jdHi6B-myT&token=…", "expiresAt": "2026-10-02T18:15:00.000Z", "maxBytes": 20000000 } ``` An unsupported `contentType` or a `size` over the cap is `400 INVALID_REQUEST`. With 20 uploads already open, the brand gets `429 RATE_LIMITED`, and `Retry-After` is when the oldest one expires. An organization key names the brand with `X-Brand-Id` here and on the last call, as on every brand-scoped route. ## Send the File POST the raw bytes to `uploadUrl` before `expiresAt`. Send no `Authorization` header. The URL carries its own credential, so keep it as private as an API key. ```bash curl theme={null} curl -X POST --data-binary @logo.png "" ``` ```ts TypeScript theme={null} await fetch(upload.uploadUrl, { method: 'POST', body: bytes }) ``` It answers `200` with `{ uploadId, status: "uploaded", size, expiresAt }`. The new `expiresAt` is 15 minutes after the bytes landed, and it is your deadline for the next call. Sending again never replaces the first file. | Answer | Why | What to do | | - | - | - | | [`404 UPLOAD_NOT_FOUND`](/api-reference/api/errors#upload-not-found) | The URL is unknown or expired | Open a new upload | | [`413 PAYLOAD_TOO_LARGE`](/api-reference/api/errors#payload-too-large) | The file is over `maxBytes` | Upload a smaller file | ## Add It to the Library ```bash curl theme={null} curl -X POST "https://brew.new/api/v1/content/add-image" \ -H "Authorization: Bearer $BREW_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "uploadId": "imgup_V1StGXR8_Z5jdHi6B-myT" }' ``` ```ts SDK theme={null} const image = await brew.content.addImage({ uploadId: upload.uploadId }) console.log(image.assetId, image.url) ``` It answers `200` with the image, now in the brand library and on [Assets](/brand/assets): ```json theme={null} { "url": "https://cdn.brew.new/uploads/normalized/4d9f6217b5a70ce01e94b6498712ee63643ef769497327f9b2d523de6295d79e.png", "width": 1200, "height": 675, "aspectRatio": "wide", "assetId": "5f750e5f" } ``` The bytes decide the format: a declared `contentType` that differs is ignored. `fileName` names the converted file, and the image's description in the library comes from its caption. Use `assetId` to find the image in `GET /v1/brand/images` or to remove it with `DELETE /v1/brand/images/{assetId}`. A repeat with the same `uploadId` returns the same answer for 24 hours, even if the image was deleted since. A retry after a timeout is safe. | Answer | Why | What to do | | - | - | - | | [`404 UPLOAD_NOT_FOUND`](/api-reference/api/errors#upload-not-found) | The upload is unknown, expired, or another brand's | Open a new upload and send the file again | | [`409 UPLOAD_NOT_RECEIVED`](/api-reference/api/errors#upload-not-received) | The bytes never arrived | Send the file to `uploadUrl`, then call again | | [`409 UPLOAD_IN_PROGRESS`](/api-reference/api/errors#upload-in-progress) | Another call is converting this upload | Wait a few seconds and call again with the same `uploadId` | | [`413 PAYLOAD_TOO_LARGE`](/api-reference/api/errors#payload-too-large) | The file is over 20 MB, or an SVG over 2 MB | Upload a smaller file | | [`422 CONTENT_OPERATION_FAILED`](/api-reference/api/errors#content-operation-failed) | The bytes aren't PNG, JPEG, GIF, WebP, AVIF, TIFF, or SVG | Upload an image file | ## All Three Steps in One Call The TypeScript SDK's `brew.content.uploadImage` opens the upload, sends the bytes, and adds the image: ```ts theme={null} const image = await brew.content.uploadImage({ file: await readFile('logo.png'), fileName: 'logo.png', }) console.log(image.assetId, image.url) ``` `contentType` is optional here; the file name's extension gives it. Before sending anything it refuses an empty file, a file over 20 MB, or an SVG over 2 MB with a `TypeError`. It does not retry opening the upload (a retry after a lost answer would hold a second of the 20 slots), so if that step fails, call `uploadImage` again. The other answers and errors are the ones above. ### Recover a Lost Final Answer > [!NOTE] > > These recovery fields need TypeScript SDK 13.4.0 or later. On 13.3.0 or > earlier, use the explicit steps above and keep the upload ID yourself. If the final `addImage` call loses its answer, its transport error exposes the original `uploadId` and `idempotencyKey`. Replay only that step with the same brand client you used for `uploadImage`: ```ts theme={null} import { BrewTransportError } from '@brew.new/sdk' try { const image = await brew.content.uploadImage({ file: await readFile('logo.png'), fileName: 'logo.png', }) console.log(image.assetId, image.url) } catch (error) { if ( !(error instanceof BrewTransportError) || !error.uploadId || !error.idempotencyKey || error.inProgress ) { throw error } const image = await brew.content.addImage( { uploadId: error.uploadId }, { idempotencyKey: error.idempotencyKey }, ) console.log(image.assetId, image.url) } ``` If `error.inProgress` is true, this example rethrows instead of replaying immediately. Save the upload ID and key with that job, wait, then call `addImage` on the same brand client. API and parse errors expose the fields too; inspect the API code or report the parse error before deciding to replay. Calling `uploadImage()` again opens a new upload, even with the same file and key. Reusing that key with a different `{ uploadId }` body correctly returns `409 IDEMPOTENCY_CONFLICT`. See [Idempotency](/api-reference/api/idempotency). Use the original ID and key with `addImage` instead. The completed result replays for 24 hours, as described in [Add It to the Library](#add-it-to-the-library). An exposed ID does not prove the image was saved. If finalization did not complete, the upload can still expire or return one of the errors above. Failures while opening the upload or sending its bytes leave `uploadId` undefined. The SDK exposes the ID only after the helper returns an error. For recovery after cancellation or a process exit before you save that state, use the explicit steps above and retain the upload ID and your chosen final key. Caller aborts still return the signal's original `reason` without adding recovery fields. ## From the CLI ```bash theme={null} brew-cli content upload-image ./logo.png ``` It checks the type and size locally, runs all three steps, and prints the image (`--json` for the raw answer). To drive the steps yourself, run `brew-cli content create-image-upload --file-name logo.png --size 48213`, then the `curl` it prints, then `brew-cli content add-image --upload-id `. `brew-cli brand delete-image ` removes an image (it asks first; pass `--yes` in scripts). From CLI 0.19.0, errors from a finalization request include its original `uploadId` and `idempotencyKey`. If the outcome is unknown, the error also includes a `retryCommand` that runs `content add-image` with those values and the original brand and API target. This works after a final-step connection failure, timeout or interruption. Run the returned command to recover; repeating `content upload-image` opens a new upload. Wait before running the command if the error says finalization is still in progress. A definite API refusal keeps its original guidance without a replay command. Failures before finalization do not provide a finalization recovery record. The command reuses your configured authentication and does not include credentials in its text. ## From MCP Over MCP the flow is `create_image_upload`, the bytes to `uploadUrl`, then `add_image` with the `uploadId`. Sending the bytes takes a client with a shell or an HTTP tool on the file's machine, such as Claude Code or Cursor. A chat-only client should ask for a public link and call `add_image` with `imageUrl` (see [Assets](/brand/assets#from-an-agent-or-code)). ## Related * [Assets](/brand/assets): find, add, and delete images in the app and from an agent. * `POST /v1/content/image-uploads` and `POST /v1/content/add-image` in the [Public API v1 reference](/api-reference/api/api-introduction) (sidebar): full schemas. * [Rate limits](/api-reference/api/rate-limits#open-image-uploads): the 20 open uploads. * [Errors](/api-reference/api/errors): every code above. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Sync Brew and Attio over MCP Source: https://docs.brew.new/api-reference/mcp/attio Map Attio's record and list-entry attributes to Brew, sync the fields you filter on, and write email engagement back onto the Attio entry. Attio holds the context. Brew sends the email. Then Brew writes back what happened, onto the record your team already opens. Two things make Attio different from a flat CRM, and both change how you set this up. List entries carry their own attributes, and interaction data is read-only. > [!WARNING] > > Every marketing recipient must have opted in to hear from you. Importing or syncing contact data into Brew is not permission to email it. See [What You Can Send](/get-started/what-you-can-send). This page covers what's specific to Attio. For creating custom fields, running the sync, and building the audience, see [Sync a CRM into Brew over MCP](/api-reference/mcp/sync-a-crm). You need both MCPs connected to the same assistant. ## Records and List Entries Attio stores attributes in two places. Picking the wrong one is the mistake that costs you later. **Record attributes** live on the person. Job title, company, email addresses. They're shared everywhere that person appears. **List entry attributes** live on the entry and are scoped to one list. The same person can sit in two lists with different entry values at once. That distinction matters for email state. Put "received the onboarding sequence" on the record and your next send overwrites it. Put it on the entry and each list keeps its own history. The mapping to aim for: **One Attio list, one Brew audience, one Email.** Facts about the human go on the record. State about a particular send goes on the entry. ## What to Sync from Attio These attributes exist in every Attio workspace. Attio maintains them, you read them. | Attribute | Lives on | Type | What you get | | - | - | - | - | | `record_id` | people | text | Stable join key. Emails change, IDs don't | | `email_addresses` | people | email, multi-value | Match key | | `last_interaction` | people | interaction | Recency, maintained by Attio | | `last_email_interaction` | people | interaction | Email-only version | | `strongest_connection_strength` | people | select | Very weak through Very strong | | `strongest_connection_user` | people | actor reference | Who on your team knows them | | `created_at` | list entry | timestamp | How long they've been in the list | All of these are read-only. Actor references resolve to a workspace member, so store the name or email as a string on the Brew side. Add one Brew field per workspace-specific attribute you want to filter on. Then sync and build the audience as described in [Sync a CRM into Brew over MCP](/api-reference/mcp/sync-a-crm). > [!TIP] > > Attio display names and API slugs differ. A list shown as "Trial Signups" can have the slug `trial_list`. Ask your assistant to read the definitions before you write any filter. `email_addresses` holds more than one address. Decide which is authoritative before you sync, or one person becomes two Brew contacts. ## Write Engagement Back to Attio This is the half most people skip, and it's what makes the record worth opening. Your team sees which emails a contact actually received, next to everything else you know about them. Brew's per-contact events are the source. Read them with `get_email_analytics` and `report: { kind: "events", recipient }` over MCP, or `GET /v1/analytics/events` filtered by `recipient`. See [Explore Per-Contact Engagement](/api-reference/guides/per-contact-engagement). The event types you can write back are `sent`, `delivered`, `opened`, `clicked`, `bounced`, `complained`, and `unsubscribed`. Write them to a `status` or `select` attribute on the entry. > After the send, update the Attio list entries for these contacts with their latest Brew email status. **Brew doesn't observe replies or meetings.** Those aren't Brew events at all. Attio tracks them through mailbox and calendar sync. They flow Attio into Brew as suppression inputs, not the other way. ### One Owner per Attribute This is the rule that keeps the loop from quietly wrecking your data. Picture it. A teammate moves someone forward after a real conversation. The next sync sees that an email went out and overwrites their judgment, with no error and no warning. Give machine-observed facts their own column. Brew writes to something like `brew_email_status`, and human-judgment columns stay human. Brew never touches them. The tempting alternative is one shared column with a rule like "Brew only advances from this value." That rule lives in prompt text, and prompt text gets edited and forgotten. One extra attribute per list is cheaper than a funnel nobody trusts. ## Attio-Specific Traps **Interaction attributes are read-only.** Attio's API rejects writes to them outright. Use your own attributes for anything Brew observes. **They're also often empty.** They're enriched attributes, not available on every Attio billing plan. That means they can be blank for reasons unrelated to your data. A filter on an empty attribute matches nothing and never errors, so check a real sample first. **One entry per record, or the write fails.** Updating an entry by parent record ID errors on zero entries in that list, and on more than one. Handle both cases before you run it at volume. **Multi-value attributes prepend by default.** Values stack instead of replacing, so email state written that way accumulates. Use a `status` or `select` attribute, which holds one value at a time. ## Verify Use two or three test records in one list. Change one thing, re-sync, and check the audience count moves by the number you expect, not just that it moved. | Change in Attio | Expected in Brew | | - | - | | Entry attribute set to your excluded value | Contact drops out of the audience | | Entry attribute set back | Contact returns | | Add a person to the list | Appears after the next sync | Then test the reverse. Send to one test contact and sync back. Confirm your Brew-owned attribute updated on the entry, and that the human-owned ones didn't move. ## Start Small Pick one list that nothing else is writing to. Run the whole loop on a handful of records: Attio list, Brew audience, send, status back on the entry. Don't build this on a list another tool already manages. Two systems writing the same column is the exact failure this page exists to prevent. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # MCP Authentication and Scoping Source: https://docs.brew.new/api-reference/mcp/authentication-and-scoping How the Brew MCP server authenticates (a native OAuth connector or an API key), scopes a connection to one brand or a whole organization, and makes writes safe. ## Authentication The connection URL is clean and the same for everyone: ``` https://brew.new/api/mcp ``` There are two ways to authenticate it. > [accordion] OAuth connector (recommended) > > Brew is its own **OAuth 2.1 authorization server**, so compatible clients need **no key to copy**. Add the URL as a ChatGPT plugin or MCP connection, then use the client's authenticate action. **Sign in with Brew** and **pick a brand**, or your whole organization. > > Brew issues a token scoped to that choice. See and revoke it under **Settings → MCP**, in the **Connected via OAuth** list. > > OAuth-capable clients include ChatGPT web and desktop, Claude, Grok, Cursor, Codex, and VS Code. Other clients can use API keys. See [Connect your client](/api-reference/mcp/connect-your-client). > [accordion] API key (alternative) > > For clients with no OAuth UI, or headless / CI setups, send an **API key** as a bearer token instead. A brand key gives a brand connection, and an organization key gives an organization connection: > > ``` > Authorization: Bearer brew_YOUR_API_KEY > ``` > > Create keys at **Settings → API**. A request with no or invalid credential returns `401`; OAuth-capable clients use its challenge to begin discovery. > > Apps and agents deployed on Vercel have a third route. [Vercel Connect](/integrations/ai-agents/vercel-connect) holds the Brew credential at the team level and hands your code a short-lived token. ### OAuth Discovery and Security Compatible clients discover authentication from Brew's `401 WWW-Authenticate` challenge and protected-resource metadata. Brew publishes RFC 8414 authorization-server metadata (plus the OIDC discovery fallback), supports Dynamic Client Registration for public clients, and requires Authorization Code + PKCE S256. Redirect URIs are exact-match registered, web callbacks require HTTPS, and loopback HTTP remains available for desktop clients. The only public scope is `brew:all`. Authorization and refresh requests are bound to the exact resource audience `https://brew.new/api/mcp`. An authorization request that omits `resource` gets that audience; unknown scopes and audience mismatches are rejected. Access tokens are short-lived, refresh tokens rotate, and reusing an already-rotated refresh token revokes that grant. Brew does not advertise Client ID Metadata Documents (CIMD). ## Brand Scoping A connection covers either **one brand** or your **whole organization**, and there is no brand in the URL. With OAuth you choose when you sign in. With an API key, the key's scope decides which kind you get. `get_brew_capabilities` reports which kind of connection you have. **Brand connection.** Every tool acts on the bound brand, so leave `brand_id` out. Passing a different brand fails with `BRAND_SCOPE_MISMATCH` rather than touching the wrong brand. To work on another brand, disconnect and connect again picking it, or use that brand's key. **Organization connection.** There is no default brand. Every brand-scoped tool requires `brand_id`, and leaving it out returns `BRAND_ID_REQUIRED`. Call `list_brands` for the ids, and ask the user which brand they mean when it isn't clear. Organization-level tools (brands, templates, flows, usage) take no `brand_id`; [Organization operations](/api-reference/api/organization-and-brand-scope#organization-operations) owns the full list. An OAuth connection has the access of the person who connected it. An organization admin reaches every brand, and a member reaches only the brands they were added to. An organization API key reaches every brand. Find brand details with the `get_brand` tool or in the dashboard. [Authentication](/api-reference/api/authentication#brand-vs-organization-keys) covers how brand and organization keys work over the API. ## Confirmation On OAuth connections, and on every organization connection, a call that emails people or removes contact data pauses first. Called without `confirmed`, it returns `confirmation_required` and does nothing. The result says what would happen (the design and its preview, the recipients, the automation, the addresses, the field or the domain) so the user can approve it, plus a `confirmation_id`. The same call with `confirmed: true` and that `confirmation_id` then carries it out. The id holds only for those exact arguments, from the same connection, for 15 minutes, and runs one call, so a call can't skip the request, an approved call can't change after the fact, and one approval can't run twice. Calling again with a used id returns a new confirmation request, except a retry of that same call with the same `idempotency_key`, which replays its first result. The id doesn't cover `idempotency_key`, so a fresh key on the confirmed call keeps it. | Tool | Pauses when | | - | - | | `send_email` | A campaign, or any `test: true` send, except on OAuth a test to only the signed-in person | | `test_automation` | `testRecipient` is set, except on OAuth when it is the signed-in person | | `run_automation` | A real launch (a `dryRun` never pauses) | | `fire_trigger_event` | Always. `check_trigger` checks a payload without firing | | `save_automation` | It publishes, unpauses, or stops contacts mid-flow (`stopInFlight`), unless `dryRun` | | `resume_email_send`, `resume_audience_run` | Every resume | | `verify_domain` | Campaigns are held on the domain, so a passing check would resume them. Otherwise it runs at once | | `delete_contacts`, `delete_contact_field` | Always | The preview shown for a design is Brew's stored screenshot of it. A design with no screenshot yet comes with its Open in Brew link only. Brand API-key connections are meant for programmatic use and do not pause at this gate. Get approval before the first real `send_email` call, and make it once. ## Safe Retries (Idempotency) **Write** tools that support retries accept an optional `idempotency_key` (≤ 100 chars), the MCP equivalent of the `Idempotency-Key` header. Pass it only where the tool's input schema lists it. Keys are honored identically across the MCP and HTTP surfaces: a write sent over HTTP with `Idempotency-Key: k1` and retried with `idempotency_key: "k1"` here (or the reverse) replays the first result instead of running again. [Idempotency](/api-reference/api/idempotency) owns the replay window, conflict behavior, and key patterns. Always pass one on the fail-closed tools: `send_email`, `fire_trigger_event`, `run_automation`, `test_automation`, `audit_email`, and `create_inbox_placement_test`. [Idempotency](/api-reference/api/idempotency#in-progress-requests-and-storage-outages) owns what fail-closed means. ## Errors and Observability A failed call starts with `Error : `, followed by `Next:` and what to do. The code and its recovery facts are also in `_meta["brew/error"]`, so branch on the code. Out of credits is `INSUFFICIENT_CREDITS`, and permission gaps return their own codes. Arguments that don't match a tool's input schema fail before the tool runs. They return MCP error `-32602` ("Input validation error") with no Brew code. Fix the arguments and call again. Request ids stay in Brew's server logs. To report a failure, use the `report_mcp_issue` workflow, or `report_tool_issue`. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Connect Your MCP Client Source: https://docs.brew.new/api-reference/mcp/connect-your-client Connect the Brew MCP server to ChatGPT web, desktop, Codex, Claude, Cursor, and other clients with complete authentication and verification steps. Every client connects to the **same clean endpoint**: ``` https://brew.new/api/mcp ``` Brew supports **OAuth 2.1** in compatible clients. Add the URL, authenticate, and pick one brand or your organization. Revoke the scoped token anytime in **Settings → MCP**. For clients that use API-key authentication, follow the alternative below. The `brew:all` scope gives the connected client full access to what you select. It can read and change emails, audiences, contacts, automations, sending setup, and analytics there. An organization connection reaches every brand you can access, so pick a single brand unless the client needs them all. See [Brand scoping](/api-reference/mcp/authentication-and-scoping#brand-scoping). To extract a new brand from a website, an organization administrator chooses **All brands**, then asks for the `onboard_brand` workflow. This works before the organization's first brand exists. A brand connection can update its existing brand and sending domain with `configure_brand`. [MCP Workflows](/api-reference/mcp/workflows) covers the next steps. > [!TIP] > > Wiring up a headless / CI setup, or a client with no OAuth UI? Send an > API key as `Authorization: Bearer brew_…` instead. See [the API-key > alternative](#alternative-connect-with-an-api-key) below. For setup, authentication, and brand verification, choose your client: > [card] [ChatGPT and Codex Desktop](/integrations/ai-agents/chatgpt-codex-desktop) > [card] [Claude](/integrations/ai-agents/claude) > [card] [Cursor](/integrations/ai-agents/cursor) > [card] [Grok Bot](/integrations/ai-agents/grok-bot) The Grok tab below covers Grok web and Grok Build. Pick your agent: > [tab] Claude Desktop > > **Custom connector** > > **1. Configure** > > Open **Customize → Connectors → + Add → Add custom connector**. > > Name it Brew, enter the server URL below, and select **Continue**. Review the detected authentication settings and continue. > > ```text theme={null} > https://brew.new/api/mcp > ``` > > **2. Authenticate** > > Choose **Sign in now** or connect when needed. Finish adding the connector, select **Connect**, sign in with Brew, and choose one brand or all brands. > > **3. Verify** > > Enable Brew from the conversation’s **+ → Connectors** menu. Call get_brew_capabilities to confirm the connection and inspect its brand or organization scope. > > > [!NOTE] > > > > For Team or Enterprise, an owner or authorized admin first uses **Organization settings → Connectors → Add → Custom → Web**. Members then connect individually. Free accounts are limited to one custom connector. > > **API-key alternative** > > **1. Configure** > > Use the same custom connector flow and server URL. Choose **No sign in** when using a fixed API key. > > ```text theme={null} > https://brew.new/api/mcp > ``` > > **2. Authenticate** > > Under **Request headers**, add **Authorization** with the value **Bearer brew_YOUR_API_KEY**, using a key from Brew’s **Settings → API**. Finish adding the connector. > > **3. Verify** > > Call get_brew_capabilities to confirm the connection and inspect its brand or organization scope. > > > [!NOTE] > > > > On Team or Enterprise, a fixed credential is shared by everyone using the connector. Choose a key limited to the access those members need. > [tab] ChatGPT web > > **1. Configure** > > On chatgpt.com, open **Plugins → + → Add custom MCP server**. > > Name it Brew. Under **Connection**, enter the server URL below and choose **OAuth**. > > Review the warning, select **I understand and want to continue**, then **Create as a plugin**. > > ```text theme={null} > https://brew.new/api/mcp > ``` > > **2. Authenticate** > > Install the plugin. Complete the OAuth sign-in with Brew, choose one brand or all brands, and approve the access when prompted. > > **3. Verify** > > In a new chat, type **@** and select **Brew**. Call get_brew_capabilities to confirm the connection and inspect its brand or organization scope. > > > [!NOTE] > > > > Full MCP support on the web requires Business or Enterprise/Edu. Pro supports read/fetch access. Workspace permissions govern who can create custom MCP plugins; Business requires an admin or owner. > > > [!NOTE] > > > > If tools changed after installation, refresh the plugin’s tools or actions using the controls your workspace provides. An administrator may need to review and publish the update. > [tab] Grok > > **Grok Bot desktop** > > **1. Configure** > > In a Bot conversation, ask to reuse your Brew connection or add the server URL below with OAuth. Keep setup read-only. > > ```text theme={null} > https://brew.new/api/mcp > ``` > > **2. Authenticate** > > On the Brew connection card, select **Authorize**. Sign in with Brew in your browser, choose your brand, and review access before approving. If prompted, open Grok Bot to return to the app. > > **3. Verify** > > Call get_brew_capabilities to confirm the connection and inspect its brand or organization scope. Then call get_brand and check the returned brand name, website, and readiness. > > > [!NOTE] > > > > A Connected badge alone does not prove a tool call succeeded. Keep verification read-only; do not create drafts or send emails. > > [Full setup guide](https://docs.brew.new/integrations/ai-agents/grok-bot) > > **Web connector** > > **1. Configure** > > Open **grok.com/connectors → New Connector → Custom** and enter the server URL below. > > ```text theme={null} > https://brew.new/api/mcp > ``` > > **2. Authenticate** > > Start authentication, sign in with Brew, select a brand or all brands, and approve access. > > **3. Verify** > > Start a new chat; Grok can use connected tools when relevant. Call get_brew_capabilities to confirm the connection and inspect its brand or organization scope. > > > [!NOTE] > > > > For Business or Enterprise, a team admin provisions the connector first. > > **Grok Build** > > **1. Configure** > > Run the command below. > > ```bash theme={null} > grok mcp add --transport http brew 'https://brew.new/api/mcp' > ``` > > **2. Authenticate** > > If authentication is needed, open **/mcps**, select Brew, and press **i** to sign in with Brew and select your brand. > > **3. Verify** > > Run `grok mcp doctor brew`, then start a session. Call get_brew_capabilities to confirm the connection and inspect its brand or organization scope. > [tab] Claude Code > > **1. Configure** > > Run the command below with **--scope user** for every project, or omit it for this project’s local configuration. Adding the server only saves its configuration. > > ```bash theme={null} > claude mcp add --transport http --scope user brew 'https://brew.new/api/mcp' > ``` > > **2. Authenticate** > > Run `claude mcp login brew`, or open **/mcp** in a Claude Code session and select Brew to authenticate. Sign in with Brew and choose a brand or all brands. > > **3. Verify** > > Run **/mcp** to confirm Brew is connected. Call get_brew_capabilities to confirm the connection and inspect its brand or organization scope. > [tab] Cursor > > **1. Configure** > > Use **Add to Cursor** below, or merge the configuration into **\~/.cursor/mcp.json** (all projects) or **.cursor/mcp.json** (this project). > > [Add to Cursor](cursor://anysphere.cursor-deeplink/mcp/install?name=brew\&config=eyJ1cmwiOiJodHRwczovL2JyZXcubmV3L2FwaS9tY3AifQ) > > ```json mcp.json theme={null} > { > "mcpServers": { > "brew": { > "url": "https://brew.new/api/mcp" > } > } > } > ``` > > **2. Authenticate** > > Open **Customize → MCP**, select Brew, and use its sign-in action if prompted. Sign in with Brew and choose a brand or all brands. > > **3. Verify** > > Confirm Brew’s tools appear in Customize. Call get_brew_capabilities to confirm the connection and inspect its brand or organization scope. > > > [!NOTE] > > > > Older Cursor builds call this settings section **Tools & MCP**. > [tab] OpenCode > > **1. Configure** > > Merge this block into **\~/.config/opencode/opencode.json**. > > ```json opencode.json theme={null} > { > "mcp": { > "brew": { > "type": "remote", > "url": "https://brew.new/api/mcp", > "enabled": true > } > } > } > ``` > > **2. Authenticate** > > Run `opencode mcp auth brew`, sign in with Brew, and select a brand or all brands. OpenCode can also prompt on first use. > > **3. Verify** > > Run `opencode mcp list` to confirm Brew is connected. Call get_brew_capabilities to confirm the connection and inspect its brand or organization scope. > [tab] VS Code > > **1. Configure** > > Run **MCP: Add Server** from the Command Palette and choose HTTP, or create **.vscode/mcp.json** with the block below. > > For all workspaces, use **MCP: Open User Configuration**. > > ```json mcp.json theme={null} > { > "servers": { > "brew": { > "type": "http", > "url": "https://brew.new/api/mcp" > } > } > } > ``` > > **2. Authenticate** > > Select **Start** above Brew’s entry in mcp.json. Complete the browser sign-in with Brew and select a brand or all brands. > > **3. Verify** > > In Chat, select **Agent**, then **Configure Tools** and enable Brew’s tools. Call get_brew_capabilities to confirm the connection and inspect its brand or organization scope. > > > [!NOTE] > > > > Requires GitHub Copilot. On Copilot Business or Enterprise, an administrator must allow MCP servers in Copilot. > [tab] Codex and ChatGPT desktop > > **ChatGPT desktop** > > **1. Configure** > > Open **Settings → Plugins → MCPs → Add → Add MCP server**. Some builds use **Settings → MCP servers → Add server**. > > Name it brew, select **Streamable HTTP**, and enter the URL below. Leave token and header fields empty for OAuth, then **Save**. Restart the connection if offered. > > ```text theme={null} > https://brew.new/api/mcp > ``` > > **2. Authenticate** > > Select **Authenticate** on the Brew server, sign in with Brew, and choose a brand or all brands. > > **3. Verify** > > Type **/mcp** to inspect connected servers. Call get_brew_capabilities to confirm the connection and inspect its brand or organization scope. > > **Codex CLI or IDE configuration** > > **1. Configure** > > Merge this block into **\~/.codex/config.toml**. The desktop app, CLI and IDE extension share it on the same Codex host. > > ```toml config.toml theme={null} > [mcp_servers.brew] > url = "https://brew.new/api/mcp" > ``` > > **2. Authenticate** > > Run `codex mcp login brew`, sign in with Brew, and select a brand or all brands. The desktop and IDE server lists also offer **Authenticate**. > > **3. Verify** > > Run `codex mcp list` or **/mcp** in a session. Call get_brew_capabilities to confirm the connection and inspect its brand or organization scope. > > > [!NOTE] > > > > Windows and WSL can use different hosts and home directories. ChatGPT web does not read this file. For an API key, set bearer_token_env_var to the name of an environment variable containing your Brew key. > [tab] Manus > > **1. Configure** > > Open **Connectors → Create → Add MCP by URL**. Name the server Brew and enter the URL below. Older builds use **Settings → Integrations → Custom MCP Servers → Add Server**. > > ```text theme={null} > https://brew.new/api/mcp > ``` > > **2. Authenticate** > > Create a key in Brew’s **Settings → API**. Use the key in Manus’s bearer-token field, or set **Authorization** to **Bearer brew_YOUR_API_KEY**. Save and test the connection. > > **3. Verify** > > Confirm Brew’s tools are available. Call get_brew_capabilities to confirm the connection and inspect its brand or organization scope. > > > [!NOTE] > > > > Use API-key authentication for custom servers. Brew OAuth in Manus’s custom-server flow still needs a live compatibility check. > [tab] Devin Desktop > > **1. Configure** > > Merge this block into **\~/.config/devin/mcp_config.json** on macOS/Linux, or **%APPDATA%\devin\mcp_config.json** on Windows. For private project settings, use **.devin/mcp_config.local.json**. > > ```json mcp_config.json theme={null} > { > "mcpServers": { > "brew": { > "url": "https://brew.new/api/mcp" > } > } > } > ``` > > **2. Authenticate** > > Run `devin mcp login brew` in Devin CLI, or use the authentication action when Devin Local first uses Brew. Sign in with Brew and select a brand or all brands. > > **3. Verify** > > Run `devin mcp list` or inspect the session’s MCP servers. Call get_brew_capabilities to confirm the connection and inspect its brand or organization scope. > > > [!NOTE] > > > > Current Devin Desktop uses Devin Local. Upgrade legacy Windsurf builds before following these steps. Organization policy may restrict available servers. > [tab] Cline > > **Remote Servers** > > **1. Configure** > > Click the **MCP Servers** icon and open **Remote Servers**. > > Enter Server Name brew and the Server URL below. Choose **Streamable HTTP**, then **Add Server**. > > ```text theme={null} > https://brew.new/api/mcp > ``` > > **2. Authenticate** > > Click **Authenticate** on the Brew server row. Complete the browser sign-in with Brew and select a brand or all brands. > > **3. Verify** > > Call get_brew_capabilities to confirm the connection and inspect its brand or organization scope. > > **JSON alternative** > > **1. Configure** > > Open **MCP Servers → Configure → Configure MCP Servers** and merge the block below into the settings file. Save it. > > ```json cline_mcp_settings.json theme={null} > { > "mcpServers": { > "brew": { > "type": "streamableHttp", > "url": "https://brew.new/api/mcp", > "disabled": false > } > } > } > ``` > > **2. Authenticate** > > Click **Authenticate** on Brew’s server row, sign in with Brew, and select a brand or all brands. > > **3. Verify** > > Call get_brew_capabilities to confirm the connection and inspect its brand or organization scope. > > > [!NOTE] > > > > The type field is required here: omitting it selects legacy SSE in Cline. > [tab] Goose > > **1. Configure** > > Run goose configure. Choose **Add Extension → Remote Extension (Streamable HTTP)**, name it brew, and enter the endpoint below. > > ```bash theme={null} > goose configure > # Add Extension → Remote Extension (Streamable HTTP) > # name: brew > # endpoint: https://brew.new/api/mcp > ``` > > **2. Authenticate** > > Complete the OAuth sign-in when Goose requests it. Sign in with Brew and select a brand or all brands. > > **3. Verify** > > Start a session with the Brew extension enabled. Call get_brew_capabilities to confirm the connection and inspect its brand or organization scope. > > > [!NOTE] > > > > Goose Desktop: open **Extensions → Add custom extension**, choose **Streamable HTTP**, and enter the same endpoint. > [tab] Any MCP client > > **1. Configure** > > Use your client’s documented remote-server format. The example below is for clients that accept mcpServers with type http. Merge it into your existing config. > > ```json mcp.json theme={null} > { > "mcpServers": { > "brew": { > "type": "http", > "url": "https://brew.new/api/mcp" > } > } > } > ``` > > **2. Authenticate** > > Run the client’s sign-in or authenticate action, then sign in with Brew and choose a brand or all brands. For clients without OAuth, use an API-key bearer header in their supported format. > > **3. Verify** > > Call get_brew_capabilities to confirm the connection and inspect its brand or organization scope. > > > [!NOTE] > > > > This example is for clients that accept mcpServers and type: http. VS Code uses servers, OpenCode uses mcp and type: remote, and Cline requires type: streamableHttp. Follow your client’s recipe. ## Alternative: Connect with an API Key Create a key in **Settings → API**. A brand key covers one brand. An organization key covers your organization; pass a **brand_id** for brand-scoped tools. For clients using the HTTP JSON format, add a bearer header: ```json theme={null} { "mcpServers": { "brew": { "type": "http", "url": "https://brew.new/api/mcp", "headers": { "Authorization": "Bearer brew_YOUR_API_KEY" } } } } ``` Use your client’s own wrapper and transport name. Cline requires **streamableHttp**; VS Code uses **servers**; OpenCode uses **mcp** and **remote**. Claude’s custom connector supports **Request headers**. Set **Authorization** to **Bearer brew_YOUR_API_KEY** and choose **No sign in** for fixed credentials. On Team or Enterprise, everyone using that connector shares its credential’s access. In ChatGPT desktop or Codex, set **bearer_token_env_var** to an environment variable name such as **BREW_API_KEY**. Put the key in that environment variable before launching the client. ### Optional Compatibility Bridge For a client that only supports local stdio servers, use mcp-remote. Install Node.js so npx is available on the client host. Use your client’s local-server wrapper. This example uses mcpServers: ```json claude_desktop_config.json theme={null} { "mcpServers": { "brew": { "command": "npx", "args": [ "-y", "mcp-remote", "https://brew.new/api/mcp", "--header", "Authorization:${AUTH_HEADER}" ], "env": { "AUTH_HEADER": "Bearer brew_YOUR_API_KEY" } } } } ``` The full header value stays in AUTH_HEADER. The argument contains no spaces, which avoids argument-splitting problems in some clients. Restart the local client after changing its process configuration. [mcp-remote configuration](https://github.com/punkpeye/mcp-remote#custom-headers) ## Verify Your Connection Once connected, ask your agent to call **`get_brew_capabilities`**. It returns the connection's scope, the tool catalog, and the guided workflows. Or smoke-test the endpoint directly with a key: ```bash theme={null} curl -sN https://brew.new/api/mcp \ -H "Authorization: Bearer brew_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' ``` Next: the [quickstart](/api-reference/mcp/quickstart) create → send → analyze loop, the full [tool catalog](/api-reference/mcp/tools), and the guided [workflows](/api-reference/mcp/workflows). ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Brew MCP Server Source: https://docs.brew.new/api-reference/mcp/overview Connect an assistant to Brew over MCP to create email designs, manage contacts, run automations, and read results from your Brew account. The Brew MCP server gives compatible assistants tools to work with your Brew brands and data. Use it to create designs, manage subscribers, send emails, run automations, and read results. ## Connect ```text theme={null} https://brew.new/api/mcp ``` Add the URL to your client, sign in with Brew, and choose a brand or your organization. OAuth is the recommended connection. Headless clients can use an API key. [Connect Your Client](/api-reference/mcp/connect-your-client) has client-specific steps. MCP tools are organized around tasks. Some combine several HTTP calls, and some have no direct HTTP equivalent. The [tool catalog](/api-reference/mcp/tools) lists the available operations. Your agent already sees every Brew tool once connected. When it needs the connection's scope or guidance for a task, it can call `get_brew_capabilities`. The default answer is a short overview. Filter it by topic or tool for full steps and schemas. ## Start Here * [MCP Quickstart](/api-reference/mcp/quickstart): connect, generate an email, and send yourself a test. * [Workflows](/api-reference/mcp/workflows): production sends, segments, and automations. * [Authentication and Scoping](/api-reference/mcp/authentication-and-scoping): credentials, brands, confirmation, and retries. * [AI Assistants](/integrations/integrations#ai-assistants): setup guides for ChatGPT and Codex Desktop, Claude, Cursor, and Grok Bot. * [Run Your Email Ops from an AI Agent](/recipes/run-brew-from-an-ai-agent): drafting, review, and sending once your assistant is connected. For an agent that runs shell commands, use the [CLI](/api-reference/cli/overview). [Build with Brew](/api-reference/overview) compares all four interfaces. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # MCP Quickstart Source: https://docs.brew.new/api-reference/mcp/quickstart Connect your assistant to Brew with OAuth, discover its tools, generate a saved email, and receive a test in your own inbox through MCP. Connect your assistant, then create an email and test it in your inbox. ## Before You Begin [Add your brand](/get-started/add-your-brand) and wait for extraction to finish. Use a client that supports remote MCP and OAuth. Generation uses [credits](/api-reference/api/credits). You do not need an audience or a verified domain for a test with Brew's default sender. ## 1. Connect Your Client Add this server URL in your client's MCP settings: ```text theme={null} https://brew.new/api/mcp ``` Sign in with Brew and choose the brand for this tutorial. [Connect Your Client](/api-reference/mcp/connect-your-client) has the exact setup for each client. For a headless client, use the [API-key alternative](/api-reference/mcp/authentication-and-scoping#authentication). ## 2. Generate and Test an Email Ask your assistant: ```text theme={null} Call get_brew_capabilities to check the connection and current tool schemas. Check that my brand is ready, then create and save a friendly welcome email with one Get started button. Send a test with subject "Welcome aboard" to my own inbox: you@example.com. ``` Replace the address with the inbox of the person connected through OAuth. The assistant should: 1. Call `get_brew_capabilities` and `get_brand` to check scope and readiness. 2. Call `create_email`. If it returns `generating`, poll `get_email` with its `emailId` and `runId`. 3. Call `send_email` with `test: true`, the saved `emailId`, `subject`, `to`, and an `idempotency_key`. Polling continues the existing generation; calling `create_email` again creates another billed design. If a test returns `confirmation_required`, review it before confirming with its `confirmation_id`. [MCP Authentication and Scoping](/api-reference/mcp/authentication-and-scoping#confirmation) owns that flow. Open **\[TEST] Welcome aboard** in your inbox. Test delivery returns a completed status and recipient, without a production send row. ## Keep Going [Workflows](/api-reference/mcp/workflows) covers live sends, segments, and automations. [Tools](/api-reference/mcp/tools) is the reference catalog. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Sync a CRM into Brew over MCP Source: https://docs.brew.new/api-reference/mcp/sync-a-crm Pull CRM fields into Brew contacts with an MCP assistant: create custom fields, map properties, run the sync, and verify counts before you send. Your sales team is working a deal. Your marketing email goes to that person anyway. Fixing that means Brew needs to know what your CRM knows. If you have both connected to an MCP assistant, you can sync the fields you filter on, with no code. This page covers a one-directional sync, CRM into Brew. It works with any MCP-connected CRM, including Attio and HubSpot. Using Attio? See [Sync Brew and Attio over MCP](/api-reference/mcp/attio) for its list-entry model and the engagement writeback loop. > [!WARNING] > > Every marketing recipient must have opted in to hear from you. Importing or syncing contact data into Brew is not permission to email it. See [What You Can Send](/get-started/what-you-can-send). This syncs CRM **context** onto contacts who already opted in. It is not a way to import a prospecting list. A CRM contact from a sales conversation has not consented. ## Before You Start You need: * A Brew brand connected to your assistant, with opted-in contacts already in it * A CRM connected to the same assistant, with read access to contacts * Contacts that exist in **both** systems under the same email address Matching is on email. A contact in one system and not the other won't sync. ## 1. Check What Brew Already Has Some fields are native. Don't create custom fields that duplicate them. | Native field | Type | Holds | | - | - | - | | `email` | string | Contact identifier | | `firstName` / `lastName` | string | Name | | `subscribed` | bool | Consent state | | `validationStatus` | string | Deliverability verdict | | `lastValidatedAt` | date | When that was checked | | `createdAt` / `updatedAt` | date | Record timestamps | | `importId` | string | Source import | Ask your assistant: > List the custom fields in my Brew brand. ## 2. Create the Fields You're Missing Name each field after its source so nobody has to guess where the data came from. > Create these custom fields in Brew: crm_lifecycle_stage (string), crm_owner (string), crm_last_contacted (date), crm_record_id (string). **Brew normalizes names to camelCase.** You declare the underscored name and get the camelCase one back: ```json theme={null} { "fieldName": "crmLifecycleStage", "fieldType": "string", "label": "Crm Lifecycle Stage", "isCore": false, "isFilterable": true, "isSortable": true, "isSearchable": false } ``` The returned `fieldName` is what your audience filters use, not the name you typed. Field types are `string`, `number`, `date`, or `bool`. Declare anything date-like as `date` so comparisons work. ## 3. Pick Which CRM Properties to Sync Only sync what you'll actually filter on. Four fields cover most exclusion cases: | What you want | Why it earns a field | | - | - | | Lifecycle or deal stage | The main suppression signal | | Record owner | Separates rep-owned contacts from the open pool | | Last contacted date | Catches someone a rep emailed who hasn't moved stage yet | | CRM record ID | Stable join key. Emails change, IDs don't | **Verify the internal property names before you build anything.** Display labels and internal names differ in most CRMs. > Read the property definitions for contacts in \[CRM] and show me the internal names and stored values for \[your properties]. Some CRMs store dropdown values as internal codes or numeric IDs rather than the label you see. A filter written against the label matches nothing, so check the real stored values first. ## 4. Run the Sync > Get \[your four properties] from \[CRM] for every contact in \[list or segment]. Update each matching Brew contact with those values. Tell me how many you updated and list any you couldn't match. **Always ask for the count and the unmatched list.** An assistant working a long list can skip rows without error. The count is your only proof it finished. Ask for the report in this shape so gaps are obvious: ``` Updated: 47 of 52 Unmatched (5): jane@oldcompany.com no Brew contact found sam@example.com no lifecycle stage set in CRM ... ``` Run a full sync across the whole group once before you trust any filter. After that, re-runs only need to cover what changed. ## 5. Build the Audience Add filter conditions in the Brew UI, or ask your assistant: > Create a Brew audience called "Q3 nurture" where crmLifecycleStage is not opportunity, crmOwner is empty, and crmLastContacted is before 30 days ago. Use the camelCase field names from step 2. Available operators: | Type | Operators | | - | - | | String | `equals`, `not_equals`, `contains`, `not_contains`, `contains_any`, `not_contains_any`, `starts_with`, `ends_with`, `in`, `not_in` | | Number | `gt`, `gte`, `lt`, `lte`, `between` | | Date | `before`, `after`, `on_date`, `between` | | Boolean | `is_true`, `is_false` | | Any | `is_empty`, `is_not_empty`, `exists`, `not_exists`, `is_set` | `in`, `not_in`, `contains_any`, and `not_contains_any` take an array, such as `["lead", "mql"]`. A comma-separated string such as `"lead,mql"` is refused, because a saved filter would read it as one value and match nobody. Audiences are saved filters, not frozen snapshots. They re-evaluate at send time against whatever was last synced. Creating one returns the match count immediately: ``` Created audience "Q3 nurture", 3 contacts currently match. audienceId: j971pkqx7yzfkvk02371yffqb58by8tq ``` If that count is zero and you expected more, check your filter first. The usual cause is a value written against a display label instead of the stored one. See [Create Audiences](/audience/create-audiences) for what else you can filter on. ## 6. Verify Change one thing in your CRM and re-run the sync. Check that the audience count moves **by the number you expect**, not just that it moved. | Change in the CRM | Expected in Brew | | - | - | | Stage set to your excluded value | Contact drops out of the audience | | Stage set back to an included value | Contact returns | | Assign an owner | Owner field populates, drops from unowned-only audiences | | Log an activity | Last-contacted date updates | Use two or three test contacts and confirm before you rely on it for a real send. ## From MCP Your Brew connection covers one brand or your whole organization, depending on what you picked when you connected. The CRM side may be workspace-scoped depending on the provider, so confirm you are pointed at the right brand before writing. On a brand connection, `brand_id` is optional. Omit it to use the bound brand, since supplying a different one fails with `BRAND_SCOPE_MISMATCH` rather than writing to the wrong place. On an organization connection, every brand-scoped tool requires `brand_id`, so get the id from `list_brands` and pass it on every call. See [Authentication and Scoping](/api-reference/mcp/authentication-and-scoping). * `list_contact_fields` lists the brand's contact fields, including built-in ones marked `isCore: true`, so you can see which custom fields already exist. Call this before creating anything. Built-in fields such as `email` can't be created or deleted. * `create_contact_field` takes `fieldName` and `fieldType`. Creating a field that already exists with the same type is safe, it returns the existing definition. Field names can't contain whitespace, path separators, or quotes. * `update_contact` takes an `email` and a `fields` map, one contact per call, and changes only the fields you pass. An address Brew doesn't have fails with `CONTACT_NOT_FOUND`. The result's `updated` lists only the fields whose stored value changed. It's empty, with nothing written, when every value matched. `warnings` carries caveats such as `FIELD_TYPE_COERCED`. * Send CRM record ids as strings to a `string` field. A JSON number above 9007199254740991 (2^53 - 1) arrives already rounded, so Brew refuses it with `FIELD_TYPE_MISMATCH`. * `import_contacts` (JSON rows) and `import_contacts_csv` (CSV text) write many contacts in one call: missing ones are created, existing ones updated, and the batch is listed in Import History with its `importId`. A row that fails is reported on its own and the other rows still land. * `update_contact` only updates a contact Brew already has. New contacts join through an import, your own signup or checkout over the API (`POST /v1/contacts`, see [Batch Operations](/api-reference/api/batch-operations)), or a connected integration. Pass an `idempotency_key`, a fresh UUID per intended action, so a retry replays the original result instead of acting twice. The same key with a different payload returns a 409. See [Idempotency](/api-reference/api/idempotency). If a CRM property has no value for a contact, leave the Brew field unset. Don't write an empty string. An unset field reads as "not synced yet", while a blank one falsely reads as "synced, and empty." The full tool catalog is in [MCP Tools](/api-reference/mcp/tools). ## When the Sync Fails | What you see | What it means | What to do | | - | - | - | | "requires additional permissions" | Scope missing, or a transient error | Retry once first, this appears transiently and resolves on its own. If it persists, disconnect and reconnect the CRM, since scopes are granted at connect time | | Count lower than expected | Assistant skipped rows | Re-run on the remainder and ask for the unmatched list | | Contact not found | Email differs between systems, or the contact is missing from Brew | Upsert it, or reconcile the address | | Filter matches nothing | Filter written against a display label | Use the stored internal value | | `BRAND_SCOPE_MISMATCH` | Wrong brand asserted on a brand connection | Omit `brand_id` to use the bound brand | | `BRAND_ID_REQUIRED` | No brand named on an organization connection | Pass `brand_id`, taken from `list_brands` | ## What This Does and Doesn't Do **Syncs when asked, not automatically.** Nothing fires when a record changes in your CRM. Run the sync immediately before a send. A daily sync leaves up to 24 hours of drift. That's long enough for a rep to open a deal at 9am and your 4pm send to email them anyway. **One direction.** This pulls CRM data into Brew. To write engagement back to the CRM, see [Sync Brew and Attio over MCP](/api-reference/mcp/attio). **Matches on email only.** If your CRM stores multiple addresses per contact, decide which one is authoritative before syncing. Otherwise one person becomes two Brew contacts. **Stores values, not flags.** Write `crmLifecycleStage = "customer"`, not `isCustomer = true`. Keeping the real value means un-suppressing costs nothing and new filters don't need a re-sync. **Empty fields may be invisible.** Some CRMs omit unset properties from API responses entirely rather than returning null. An absent value is ambiguous. It can mean "never happened" or "this CRM isn't tracking it." Check that a real sample is populated before you filter on it. A recency filter built on an empty field won't error. It will silently fail to suppress, and you'll hear about it from a recipient. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # MCP Tools Source: https://docs.brew.new/api-reference/mcp/tools The full Brew MCP tool catalog by topic: email, automations, contacts and audiences, domains, brand, images and media, and account. The Brew MCP server exposes customer tasks, not one tool per HTTP route. Some tools compose several Public API v1 operations (`get_email_analytics` answers the overview, send, and event reads), and a few have no HTTP route at all. The catalog below is generated from what an organization connection's `tools/list` returns, grouped under the topics `get_brew_capabilities` uses. A brand connection sees the same tools except `create_brand`. Every tool is strictly typed and carries all four MCP annotations as booleans: `readOnlyHint`, `destructiveHint`, `idempotentHint`, and `openWorldHint`, shown as the catalog's Read-only, Destructive, Idempotent and Open world columns. A write that overwrites, unsubscribes, or sends is marked destructive. Call `get_brew_capabilities` with a `tool` for one tool's full input schema, or with a `topic` for focused help. Each description is exactly what your agent reads, and it states the tool's cost: every credit-metered tool names its price there, and running out returns [`INSUFFICIENT_CREDITS`](/api-reference/api/errors#insufficient-credits). ## Tool Catalog ### Email | Tool | What it does | Read-only | Destructive | Idempotent | Open world | HTTP equivalent | | - | - | - | - | - | - | - | | `audit_email` | Use this when checking an email before a production send. A complete audit costs 5 credits; a partial result is free and does not establish readiness. Pass exactly one of `emailId` (a saved design; pin `emailVersionId`), `emailJsx` or `emailHtml`; `sendingPurpose` is inferred when omitted. | no | no | no | yes | `POST /v1/emails/audit` | | `cancel_email_send` | Cancel an existing scheduled, queued, or in-flight email send by sendId from get_email_analytics. Permanently stops remaining deliveries; delivered emails cannot be recalled. Repeating a cancellation is idempotent. | no | yes | yes | no | `POST /v1/sends/{sendId}/cancel` | | `clone_email` | Copy a Brew design exactly without AI; it shows no preview, since the copy looks like its source. Omit groupId/groupName to inherit its folder. Use edit_email to change content or import_email for external source. | no | no | no | no | `POST /v1/emails/{emailId}/clone` | | `create_email` | Create an on-brand email from the requested content and design brief, metered in credits; use clone_email for an exact copy or import_email for source content. The brand must be ready. Set groupId or groupName to choose its folder. A ready result already shows the design; only if generating, poll get_email. Repeating creation starts another billed design. Imagery it generates stays inside the email: it is never saved to the brand library or returned as a separate image, and its URLs appear only in the design’s HTML. | no | no | no | yes | `POST /v1/emails` | | `create_inbox_placement_test` | Start a 10-credit seed test for inbox/spam placement; it sends a real email from the domain to the Brew seed inboxes. Requires a verified domain. Check get_domain_health first; poll get_inbox_placement_results. Visual client screenshots use test_email_rendering. | no | yes | no | yes | `POST /v1/emails/{emailId}/inbox-placement-tests` | | `delete_email` | Permanently delete a design and all its versions. Delivered campaigns remain delivered. deleted:false explains already_deleted (with its deletedAt) or not_found; a retry changes nothing. On OAuth and organization connections it returns a confirmation request first; the same call with confirmed:true and its confirmation_id deletes. | no | yes | yes | no | `DELETE /v1/emails/{emailId}` | | `delete_email_group` | Delete a named email folder; its designs move to Ungrouped. Cannot delete Ungrouped. Use delete_email to delete a design itself. On OAuth and organization connections it returns a confirmation request first; the same call with confirmed:true and its confirmation_id deletes. | no | yes | yes | no | `DELETE /v1/email-groups/{groupId}` | | `edit_email` | Change an existing design with a natural-language prompt (required). Each edit creates a version, moves automation steps pinned to the previous latest onto it (as a draft), and is usage-metered in credits. A ready result already shows the edited design; only if generating, poll get_email with the returned emailId and runId. To rename a design, set its subject or language, or move it to a group, use update_email_metadata: free, with no new version. Imagery it generates stays inside the email: it is never saved to the brand library or returned as a separate image, and its URLs appear only in the design’s HTML. | no | yes | no | yes | `PATCH /v1/emails/{emailId}` | | `export_email` | Export a design as a template to an ESP already connected in Brew. Use list_integrations to check the provider, or send_email to deliver through Brew. | no | yes | yes | yes | `POST /v1/emails/{emailId}/export` | | `get_email` | Show an existing email design with its preview, creator and Open-in-Brew link, read a saved version with emailVersionId, or read a generation with the runId it returned (the read waits for it to finish). Free. Request include html, versions or links only when needed; those reads show no preview. preview:false reads a design without showing it again. Use test_email_rendering only for paid inbox-client screenshots. | yes | no | yes | no | `GET /v1/emails/{emailId}` | | `get_email_analytics` | Read report.kind overview for totals over time, sends for campaign sends and their lifetime stats (pass sendId for one send; include events for its recipients), or events for recipient engagement (groupBy/bucket count them per link, day, email or unsubscribe reason). Use list_automations or get_automation with analytics:\{} for flow performance. | yes | no | yes | no | `GET /v1/analytics/overview`, `GET /v1/sends`, `GET /v1/sends/{sendId}`, `GET /v1/analytics/events` | | `get_email_audit` | Read a saved email audit and its precise findings without running or charging for a new audit. Use audit_email to create a fresh audit. | yes | no | yes | no | `GET /v1/emails/audits/{auditId}` | | `get_email_rendering` | Read a saved inbox-rendering job with previewId; waits while it runs. Returns per-client status and screenshot links without starting another paid render. Use test_email_rendering to start a new job. | yes | no | yes | no | `GET /v1/emails/client-previews/{previewId}` | | `get_inbox_placement_results` | Read saved placement results with emailId and testId; background collection refreshes them independently and takes several minutes. While queued or running, tell the user and read again later rather than in a loop. Omit testId to compare a design’s previous tests. This read does not poll the provider or modify results. | yes | no | yes | no | `GET /v1/emails/{emailId}/inbox-placement-tests`, `GET /v1/emails/{emailId}/inbox-placement-tests/{testId}` | | `get_template` | Use this when viewing one public template selected with search_templates. Returns its preview and emailId, which create_email takes as referenceEmailId. Include html only to inspect its content; large HTML is a downloadable file. Use get_email for a design in your brand. | yes | no | yes | no | `GET /v1/templates/{templateId}` | | `import_email` | Import existing HTML, MJML, React Email JSX, or a connected Figma frame as an editable email. Choose source.kind content or figma. For a new design from a prompt use create_email. | no | no | no | yes | `POST /v1/emails/import`, `POST /v1/emails/figma` | | `list_email_comments` | List the open comment threads teammates left on one email design, newest activity first: commentId, whether it is on the whole email or one element, the 12 most recent participants and their count, message count and the latest preview. include \["messages"] adds each thread’s newest messages (author, body, mentions) and caps the page at 3 threads; a thread with older ones returns messagesCursor: pass it with that commentId for the next older messages, until null. An unknown emailId is EMAIL_NOT_FOUND; a commentId that is not an open thread on it (resolving deletes one) is COMMENT_NOT_FOUND. Read-only and free. Use get_email for the design itself. | yes | no | yes | no | `GET /v1/emails/{emailId}/comments` | | `list_email_groups` | List email folders with their groupId values and creators, including Ungrouped. Use list_emails with groupId to read a folder’s designs. save_email_group creates or renames folders. | yes | no | yes | no | `GET /v1/email-groups` | | `list_emails` | List this brand’s saved email designs by group or status. Returns public emailId, title, group, creator, and links; a page of up to 8 shows as a gallery (to show designs, pass limit 8 or preview:true). Pass preview:false to look up ids or act on many designs. Use get_email to view one design or retrieve its content. search_templates browses the public gallery. | yes | no | yes | no | `GET /v1/emails` | | `list_insights` | List the brand’s Brew Insights as the Insights page ranks them, most severe first: each finding’s insightId, title, description, severity, confidence, category, state and first and last seen times, plus when the engine last ran. Open findings by default; state "all" adds closed ones. include adds the weekly pulse, latest intelligence report, its open suggestions and the agent memo; anything cut to fit is named in truncated. A cursor is refused once the findings change; list again without it. With an insightId from a row (not a report insight key), returns that finding with its frozen metrics, evidence and detector method. Read-only and free. get_email_analytics reports raw performance. | yes | no | yes | no | `GET /v1/insights`, `GET /v1/insights/{insightId}` | | `pause_email_send` | Pause an existing gradual email send by sendId from get_email_analytics. Holds remaining deliveries; emails already delivered remain sent. Applies to gradual sends only. Use resume_email_send to continue or cancel_email_send to stop remaining deliveries permanently. | no | yes | yes | no | `POST /v1/sends/{sendId}/pause` | | `restore_email_version` | Restore a saved email version as a new latest version. Read available versions with get_email first. Existing history is preserved. Automation steps pinned to the previous latest move to it as a draft. | no | yes | no | no | `POST /v1/emails/{emailId}/restore` | | `resume_email_send` | Resume a paused email send by sendId from get_email_analytics: a gradual send its operator paused, or any send paused for its bounce or complaint rate (pauseReason bounce_rate; it is never paused for that again). Continues delivering real email to remaining recipients. On OAuth and organization connections, first obtain a confirmation request, then repeat with confirmed:true and its confirmation_id. Reuse the same idempotency_key when retrying. | no | yes | yes | yes | `POST /v1/sends/{sendId}/resume` | | `save_email_group` | Create a named email folder, or rename an existing group by groupId. Pass emailIds (up to 50) to move designs into it in the same call, one request against the rate limit; resend any notMoved with reason retry. Omit groupId only when creating. update_email_metadata moves one design. | no | yes | yes | no | `POST /v1/email-groups`, `PATCH /v1/email-groups/{groupId}` | | `search_templates` | Browse public templates by category or brand. Use semantic for relevance ranking (top 200), or query for a case-insensitive title substring or exact public ID. Pages contain metadata, preview links, and each template’s emailId (create_email takes it as referenceEmailId); a page of up to 8 shows as a gallery (the default page). Pass preview:false to list them as text. count:true returns the total for brand/category instead of rows, refreshed every 15 minutes; add groupBy brand or category for per-value counts, largest first, such as which categories a brand has. Use get_template for one template’s content. | yes | no | yes | no | `GET /v1/templates` | | `send_email` | Send one campaign or a test:true QA email. A campaign goes from a verified marketing domain to a saved audience (audienceId) or to up to 50 existing subscribed contacts (to); it never creates contacts. With an idempotency_key a retry replays instead of sending twice. On OAuth and organization connections a campaign, or a test (except, on OAuth, one to the signed-in person), returns a confirmation request first; the same call with confirmed:true and its confirmation_id sends. Recurring/event mail uses fire_trigger_event or run_automation. | no | yes | no | yes | `POST /v1/sends` | | `test_email_rendering` | Test a design’s appearance in specific inbox clients and devices. Reserves 10 credits; charges once when a screenshot is ready. Waits for clients; read any still rendering with get_email_rendering and the returned previewId. For a free general design preview use get_email. | no | no | no | yes | `POST /v1/emails/{emailId}/client-previews` | | `update_email_metadata` | Rename a design, set its inbox subject or language, or move it to an existing group atomically; groupId:null ungroups. Free: it never generates content, charges credits, creates a version or shows a preview. Shares the 20/min email-edit limit: to move several designs, use save_email_group with emailIds. edit_email changes the design itself. | no | yes | yes | no | `PATCH /v1/emails/{emailId}` | ### Automations | Tool | What it does | Read-only | Destructive | Idempotent | Open world | HTTP equivalent | | - | - | - | - | - | - | - | | `cancel_audience_run` | Permanently cancel a manual-audience run by audienceRunId from list_automation_runs. Stops remaining steps; delivered emails remain sent. A retry with the same idempotency_key replays the first answer; canceling a run that already completed, failed or was canceled returns RUN_NOT_CANCELLABLE and changes nothing. Event and test runs use cancel_automation_run. | no | yes | yes | no | `POST /v1/automations/audience-runs/{audienceRunId}/cancel` | | `cancel_automation_run` | Cancel one running event or test run by automationRunId from list_automation_runs or test_automation. Returns canceled with the status it was in; delivered emails remain sent. Use cancel_audience_run for manual-audience runs, or save_automation to change a flow. | no | yes | yes | no | `POST /v1/automations/runs/{automationRunId}/cancel` | | `check_trigger` | Check whether a trigger can fire now and which published automations consume it. A trigger no published automation listens for is ready: false with a NO_PUBLISHED_AUTOMATION entry in blockers, not an error; publish one before firing. An integration trigger also returns delivery: whether Brew has received its event yet (Shopify sends a topic only to a webhook made for it); it never changes ready. Include payload to validate that example against its contract. A Brew-event (unsubscribe) trigger answers TRIGGER_NOT_FIREABLE: Brew starts it itself. Nothing fires or changes. | yes | no | yes | no | `GET /v1/automations/triggers/{triggerEventId}/readiness`, `POST /v1/automations/triggers/{triggerEventId}/contract/validate` | | `delete_automation` | Use this when permanently removing an automation: its versions, event and test run history and layout go, and contacts mid-flow stop. Unfinished manual-audience runs (scheduled, queued, running or paused) are cancelled and kept as history. The designs it references stay, and already-delivered emails are not unsent. Idempotent. On OAuth and organization connections it returns a confirmation request first; the same call with confirmed:true and its confirmation_id deletes. | no | yes | yes | no | `DELETE /v1/automations/{automationId}` | | `delete_trigger` | Use this when removing an unused trigger. Fails while any automation, published or draft, is wired to it; unpublishing is not enough. Delete those with delete_automation, or re-point each to another trigger with save_automation and republish a published one, then retry. Idempotent. On OAuth and organization connections it returns a confirmation request first; the same call with confirmed:true and its confirmation_id deletes. | no | yes | yes | no | `DELETE /v1/automations/triggers/{triggerEventId}` | | `ensure_brew_event_trigger` | Get or create the brand’s unsubscribe trigger: scope domain with a domainId from list_domains (unsubscribes from that domain’s emails) or scope all (from every email). Brew starts it itself on every unsubscribe from an email link or the mail app’s button, so fire_trigger_event refuses it. Wire it with save_automation; the contact just opted out of marketing, so send only what they need, such as confirming the unsubscribe, from a transactional domain. | no | no | yes | no | `POST /v1/automations/triggers/brew-events` | | `fire_trigger_event` | Use this when starting published event automations from an app/event payload. Do not use `send_email` (one-off campaign) or `run_automation` (manual-audience launch). Requires a published automation listening for the trigger. With an `idempotency_key`, a retry replays the original runs instead of firing twice. On OAuth and organization connections it returns a confirmation request first; the same call with confirmed:true and its confirmation_id fires. A new payload email becomes a contact; a contact who unsubscribed is refused (RECIPIENT_UNSUBSCRIBED) and nothing is sent. A Brew-event (unsubscribe) trigger is refused (TRIGGER_NOT_FIREABLE): try its automation with test_automation. | no | yes | no | yes | `POST /v1/automations/triggers/{triggerEventId}/fire` | | `get_automation` | Get an automation by automationId, including its creator, live publisher, canonical link and optional graph or versions. Include analytics:\{from?,to?} for performance. Use list_automation_runs for execution logs. | yes | no | yes | no | `GET /v1/automations/{automationId}`, `GET /v1/analytics/automations` | | `get_flow` | Show one public email sequence by its slug from list_flows: up to 12 steps with subjects, day offsets, previews and emailId references for create_email. `include: ["html"]` adds step content. An unknown slug returns FLOW_NOT_FOUND. | yes | no | yes | no | `GET /v1/flows/{slug}` | | `get_trigger_contract` | Read a trigger’s payload contract before integration. Request format ts, zod, jsonschema or skill for generated code/docs. Use set_trigger_contract to change it. | yes | no | yes | no | `GET /v1/automations/triggers/{triggerEventId}/contract` | | `infer_payload_contract` | Infer typed fields and uncertainty notes from the required example event payload. Nothing is saved. Review the draft, then persist it with set_trigger_contract before integrating the trigger. | yes | no | yes | no | `POST /v1/payload-contracts/infer` | | `list_automation_runs` | Inspect run.kind execution for automation executions or audience for manual-audience launches. Pass automationRunId or audienceRunId to read one run (reading a running test run waits up to 24 seconds for it to finish, then returns it as queued or running); include logs on an execution for its node logs. Each kind has its own IDs and pagination cursor. | yes | no | yes | no | `GET /v1/automations/runs`, `GET /v1/automations/runs/{automationRunId}`, `GET /v1/automations/audience-runs`, `GET /v1/automations/audience-runs/{audienceRunId}` | | `list_automations` | List saved automations with their IDs, creator, publication state, and Open-in-Brew links; search finds them by name. Use get_automation for graph or version details. Include analytics:\{from?,to?} for performance. list_automation_runs retrieves logs. | yes | no | yes | no | `GET /v1/automations`, `GET /v1/analytics/automations` | | `list_flows` | Browse public brand email sequences by brand, category, type or semantic relevance. Text only: each page lists its flows with their slug, email count and span, and total counts every flow the query matches, so limit 1 answers how many there are. Use get_flow with a slug to see one sequence’s emails. Use search_templates for single public designs or list_automations for your saved automations. | yes | no | yes | no | `GET /v1/flows` | | `list_trigger_events` | Read past trigger fires, their match state and the runs they started; pass triggerInstanceId for one fire. Brew records one for each unsubscribe that starts an unsubscribe trigger. Fire payloads are not stored. list_automation_runs reads execution logs; get_email_analytics reads email engagement. | yes | no | yes | no | `GET /v1/automations/trigger-instances`, `GET /v1/automations/trigger-instances/{triggerInstanceId}` | | `list_triggers` | List automation trigger definitions or read one triggerEventId. include:\["skill"] returns its integration brief. Use list_trigger_events for past fires. get_trigger_contract retrieves its payload schema. | yes | no | yes | no | `GET /v1/automations/triggers`, `GET /v1/automations/triggers/{triggerEventId}` | | `pause_audience_run` | Pause a running manual-audience run by audienceRunId from list_automation_runs. Stops progress at the next step boundary; deliveries already in progress may finish. Pausing a run its operator already paused returns paused and changes nothing; a run held at the plan limit is refused because it resumes on its own, so cancel it to stop it. Use resume_audience_run to continue or cancel_audience_run to stop it permanently. Event and test runs use cancel_automation_run. | no | yes | yes | no | `POST /v1/automations/audience-runs/{audienceRunId}/pause` | | `resume_audience_run` | Resume an operator-paused manual-audience run, or retry a failed run from its first undelivered step, by audienceRunId. Continues real email delivery; completed steps are skipped and partially delivered steps are refused to avoid duplicates. A plan-limit hold resumes automatically and cannot be resumed here. On OAuth and organization connections, first obtain a confirmation request, then repeat with confirmed:true and its confirmation_id. Reuse the same idempotency_key when retrying. | no | yes | yes | yes | `POST /v1/automations/audience-runs/{audienceRunId}/resume` | | `run_automation` | Launch a manual-audience automation. dryRun previews without sending; scheduledAt/gradualSend control timing; with an idempotency_key a retry replays instead of launching twice. On OAuth and organization connections a real launch returns a confirmation request first; the same call with confirmed:true and its confirmation_id launches. Event-triggered flows use fire_trigger_event. send_email delivers a one-off campaign. | no | yes | no | yes | `POST /v1/automations/{automationId}/run` | | `save_automation` | Create an automation graph, or edit an existing automationId. Setting paused:false resumes pending workflows and can continue real email delivery. State changes are explicit: published, paused, or stopInFlight (with published:false; permanently stops contacts mid-flow). On OAuth and organization connections publishing, resuming (paused:false) or stopInFlight returns a confirmation request first; the same call with confirmed:true and its confirmation_id applies it. dryRun validates without saving; test_automation exercises the flow. | no | yes | no | yes | `POST /v1/automations`, `PATCH /v1/automations/{automationId}` | | `save_trigger` | Define an event for automations, or update its existing triggerEventId. Keep the required recipient email field in the payload schema. Fire a real event with fire_trigger_event. | no | yes | no | no | `POST /v1/automations/triggers`, `PATCH /v1/automations/triggers/{triggerEventId}` | | `set_trigger_contract` | Set a trigger payload contract. Keep a required top-level email string. Version changes only when behavior changes; enable enforcement explicitly after testing. | no | yes | yes | no | `PUT /v1/automations/triggers/{triggerEventId}/contract` | | `test_automation` | Test a draft or published automation. Omit testRecipient to send nothing. On OAuth and organization connections a test to a testRecipient (except, on OAuth, the signed-in person) returns a confirmation request first; the same call with confirmed:true and its confirmation_id runs it. scenario (omit for a smoke test) simulates timed engagement and forces percentage branches; payload drives field conditions; contact.\ ones read the stored contact unless payload sets it; a test never creates or edits a contact. On a Brew-event (unsubscribe) trigger, omit payload for Brew’s sample event; payload fields override it. Returns the finished run with its coverage; one run cannot prove every path. | no | yes | no | yes | `POST /v1/automations/{automationId}/test` | ### Contacts and audiences | Tool | What it does | Read-only | Destructive | Idempotent | Open world | HTTP equivalent | | - | - | - | - | - | - | - | | `create_audience` | Create a saved contact segment from filters, or copy one with sourceAudienceId (and an optional name for the copy). Contacts are not duplicated. Use create_audience_from_events for a frozen engagement-event cohort. | no | no | no | no | `POST /v1/audiences` | | `create_audience_from_events` | Save a frozen contact cohort from engagement events. Poll list_audiences with the returned audienceId and include:\["build"] until ready before sending. create_audience creates a live filter instead. | no | no | no | no | `POST /v1/audiences/from-events` | | `create_contact_field` | Define a contact field and its type before writing values through update_contact, import_contacts or import_contacts_csv. | no | no | yes | no | `POST /v1/fields` | | `delete_audience` | Use this when removing a saved audience. Does not delete the contacts in it. Idempotent. On OAuth and organization connections it returns a confirmation request first; the same call with confirmed:true and its confirmation_id deletes. | no | yes | yes | no | `DELETE /v1/audiences/{audienceId}` | | `delete_contact_field` | Use this when removing a custom field and its value from every contact. The values cannot be recovered, and audience filters on the field then see no value. On OAuth and organization connections it returns a confirmation request first; the same call with confirmed:true and its confirmation_id deletes. Cannot delete core system fields. Idempotent. | no | yes | yes | no | `DELETE /v1/fields/{fieldName}` | | `delete_contacts` | Permanently delete one or more contacts by email. Pass a nonempty emails array; already missing contacts are safe to retry. On OAuth and organization connections it returns a confirmation request first; the same call with confirmed:true and its confirmation_id deletes. | no | yes | yes | no | `DELETE /v1/contacts/{email}`, `POST /v1/contacts/batch-delete` | | `import_contacts` | Add or update up to 1000 contacts from JSON rows (email, firstName, lastName, subscribed, customFields, consent). Missing contacts are created subscribed unless a row says subscribed:false; existing ones are updated (onConflict:"skip" leaves them unchanged), and re-subscribing an opt-out is skipped with a RESUBSCRIBE_SKIPPED warning. A missing, invalid or repeated address fails its row. Listed in Import History under fileName; returns importId. dryRun:true returns the same counts and writes nothing. Free unless validate:true (2 credits per address). Use import_contacts_csv for CSV text and update_contact for one contact. | no | yes | no | yes | `POST /v1/contacts/import` | | `import_contacts_csv` | Import up to 1000 CSV rows. Headers map by name; mapping overrides columns. Creates missing contacts subscribed unless the row opts out; updates existing ones (onConflict:"skip" leaves them unchanged), never re-subscribing an opt-out (RESUBSCRIBE_SKIPPED). Invalid subscription values fail their row. Missing/invalid emails and earlier duplicates are skipped. Brew-managed columns warn CSV_COLUMN_IGNORED. Listed in Import History under fileName; returns importId. dryRun:true previews and writes nothing. Free unless validate:true: inline \<=100 submitted rows cost 2 credits per submitted row; larger background validation costs 2 credits per checked address. Use import_contacts for JSON. | no | yes | no | yes | `POST /v1/contacts/import-csv` | | `list_audiences` | List saved contact segments with their member counts (search narrows them by name), or fetch one audienceId. A listed audience's `count` is its saved member total, recounted before the list answers when contacts changed since that count or it is a day old; an audience that cannot be recounted (still building, unusable filters, a failed or timed-out count) keeps its saved total. Only that one-audience read takes include: count recomputes the size a send targets, build adds an event snapshot’s build status. search_contacts retrieves the members. | yes | no | yes | no | `GET /v1/audiences`, `GET /v1/audiences/{audienceId}` | | `list_contact_fields` | List the brand’s contact field definitions and types before filtering or updating custom contact data. create_contact_field adds a definition. | yes | no | yes | no | `GET /v1/fields` | | `search_contacts` | Read-only query over the brand’s own contacts. Returns personal data: rows carry email, name, subscription and suppression state, validation status and custom fields; response_format "detailed" returns the full row. Default 10 rows per page, max 25. A search that is one whole email address returns only that contact; other text matches any of its words. With count:true returns the exact total instead; groupBy or bucket adds per-value breakdowns. include \["openProfile"] adds open-time profiles (up to 10 per page). Never creates, modifies or deletes contacts. Use list_contact_fields for field names; create_audience saves a reusable segment. | yes | no | yes | no | `POST /v1/contacts/search` | | `update_audience` | Rename a saved audience, replace its filter, or add/remove specific contacts by email (addEmails/removeEmails). For a separate copy, use create_audience with sourceAudienceId. | no | yes | yes | no | `PATCH /v1/audiences/{audienceId}` | | `update_contact` | Update an existing contact by email with a partial fields map; a missing contact is refused (CONTACT_NOT_FOUND) and nothing is created. Custom fields must already exist; create_contact_field adds one. Supports null clearing. subscribed:false unsubscribes; true never re-subscribes an opt-out (RESUBSCRIBE_NOT_ALLOWED). updated names only fields whose value changed; warnings flags an ambiguous date read month/day (DATE_ORDER_ASSUMED). validate:true checks deliverability for 2 credits per address. | no | yes | no | yes | MCP only | | `validate_contacts` | Check deliverability for up to 100 addresses at 2 credits per address, saving verdicts on matching contacts without creating new ones. update_contact can also validate after saving. | no | yes | no | yes | `POST /v1/contacts/validate` | ### Domains | Tool | What it does | Read-only | Destructive | Idempotent | Open world | HTTP equivalent | | - | - | - | - | - | - | - | | `add_domain_unsubscribes` | Add addresses to one marketing domain's unsubscribe list so that domain stops sending to them: `emails` (up to 1,000) or `csv` (CSV text, up to 10,000 rows), not both. Known contacts still receive mail from the brand's other marketing domains; an address with no contact is created already unsubscribed everywhere. Idempotent. Both return the same counts. Taking an address off the list happens in the Brew app, not over MCP. | no | yes | yes | no | `POST /v1/domains/{domainId}/unsubscribes`, `POST /v1/domains/{domainId}/unsubscribes/import` | | `create_domain` | Register a sending domain and return DNS records for verify_domain. A new domain is marketing; an authorized reclaim of an unverified domain keeps the purpose it had, can move it from another brand and clears sender defaults. If it becomes sendable during registration, an eligible initial measurement sends real email to fixed Brew seed inboxes. Transactional domains are set up in the Brew app. | no | yes | yes | yes | `POST /v1/domains` | | `delete_domain` | Use this when removing a sending domain. Idempotent. Campaigns cannot send from a deleted domain. On OAuth and organization connections it returns a confirmation request first; the same call with confirmed:true and its confirmation_id deletes. | no | yes | yes | no | `DELETE /v1/domains/{domainId}` | | `get_domain_health` | Diagnose sending-domain DNS, authentication, reputation and deliverability. Start here; create_inbox_placement_test measures where a specific email lands. include \["scoreHistory"] adds up to 50 saved score snapshots, newest first; \["scoreRuns"] adds the last 5 automated score runs. | yes | no | yes | no | `GET /v1/domains/{domainId}/health` | | `list_domains` | List sending domains, DNS records, verification, and sending purpose. Choose a verified marketing domain for campaigns. Use verify_domain only while a domain is not sendable. get_domain_health diagnoses DNS and reputation. | yes | no | yes | no | `GET /v1/domains` | | `update_domain` | Change a domain's default sender name, from address or reply-to; this never changes sending purpose, which is set in the Brew app. An eligible verified domain without an initial automatic measurement queues one, sending real email to fixed Brew seed inboxes. verify_domain rechecks DNS. | no | yes | yes | yes | `PATCH /v1/domains/{domainId}` | | `verify_domain` | Recheck DNS after adding records from create_domain; a sendable domain is refreshed. Persists verification and tracking state and can disable or restore provider tracking, queue an initial measurement that sends to Brew seed inboxes, and hold or release existing campaigns. Releasing a domain hold resumes delivery to remaining recipients. On OAuth and organization connections, a domain with held campaigns first returns a confirmation request; repeat with confirmed:true and its confirmation_id. get_domain_health diagnoses without these changes. | no | yes | yes | yes | `POST /v1/domains/{domainId}/verify` | ### Brand | Tool | What it does | Read-only | Destructive | Idempotent | Open world | HTTP equivalent | | - | - | - | - | - | - | - | | `create_brand` (organization connections only) | Create a brand by extracting its website. Organization connections only. Poll get_brand with the returned brandId as brand_id until ready is true before designing. | no | no | no | yes | `POST /v1/brands` | | `get_brand` | Read a brand: its saved name, tagline and links (always returned), status, ready and extraction progress. While a brand is extracting, call it again until ready is true before designing. include adds the design system, image style and logos. list_brands discovers brands. | yes | no | yes | no | `GET /v1/brand` | | `list_brands` | List brands this connection can access. Organization connections choose a returned brandId for brand_id on scoped tools; brand connections see only their bound brand. | yes | no | yes | no | `GET /v1/brands` | | `update_brand` | Update identity fields such as brandName, description and contact details by partial merge. emailDesign and imageStyle replace their Markdown artifacts in full. Omitted fields stay unchanged; colors and logos are not writable identity fields. | no | yes | yes | no | `PATCH /v1/brand` | ### Images and media | Tool | What it does | Read-only | Destructive | Idempotent | Open world | HTTP equivalent | | - | - | - | - | - | - | - | | `add_image` | Add an image to the brand library. Free. imageUrl hosts one public URL; imageUrls imports up to 100 in the background; uploadId finishes a local-file upload, and repeating that call returns the same image. search_brand_images finds an image the brand already has; create_email and edit_email make new imagery inside a design. | no | no | no | yes | `POST /v1/content/add-image` | | `create_image_upload` | Open a single-use upload for one local image file. Free. Returns uploadId and uploadUrl, which takes the file's raw bytes as an HTTP POST body for 15 minutes; add_image with that uploadId then puts the image in the brand library. For a client that can send the file itself; a public image URL goes straight to add_image as imageUrl. PNG, JPEG, GIF, WebP, AVIF, TIFF or SVG; 20 MB max, SVG 2 MB. | no | no | no | no | `POST /v1/content/image-uploads` | | `delete_brand_image` | Delete one image from the brand library, as Delete image on the Assets page does. Pass the assetId from search_brand_images; one image per call. The image leaves the library and image search, but its file stays hosted, so emails already using its URL keep rendering. Logos are refused; manage them on the Assets page. An assetId not in the library returns deleted: false. Idempotent. Free. Use add_image to add an image. On OAuth and organization connections it returns a confirmation request first; the same call with confirmed:true and its confirmation_id deletes. | no | yes | yes | no | `DELETE /v1/brand/images/{assetId}` | | `render_html_image` | Render HTML into a hosted PNG for 1 credit. Use get_email for an existing design preview or test_email_rendering for inbox-client screenshots. | no | no | no | yes | `POST /v1/content/html-to-png` | | `search_brand_images` | List the brand’s logos and brand images (from the site or uploaded), free; sort newest or oldest. Pass q for semantic search over brand images, also free. For a hero or photo, use kind brand. Imagery made with Brew stays inside the designs that use it; create_email and edit_email make new imagery. add_image adds a URL or an uploaded file; delete_brand_image removes one by assetId. | yes | no | yes | no | `GET /v1/brand/images` | ### Account and discovery | Tool | What it does | Read-only | Destructive | Idempotent | Open world | HTTP equivalent | | - | - | - | - | - | - | - | | `get_brew_capabilities` | Discover this connection’s scope and available tools. Filter by topic or tool for focused help and schemas; detailed adds a paginated HTTP API catalog. The default is a compact overview, so call only when guidance is needed. | yes | no | yes | no | MCP only | | `get_chat_artifacts` | Read a selected Brew chat’s title, link and referenced email designs, automations and triggers by chatId. Use after a chat handoff or selecting a chat with list_chats. Organization connections require the owning brand_id. Load a referenced design with get_email before editing it. Returns artifacts only; no conversation messages. | yes | no | yes | no | `GET /v1/chats/{chatId}` | | `get_usage` | Use this when the user asks about their plan, AI credits or monthly send allowance, or after a credit or send-limit error. Organization scope; no `brand_id`. It does not report test, run, send or generation progress: read those with list_automation_runs or get_email. | yes | no | yes | no | `GET /v1/usage` | | `list_chats` | Find Brew chats in the connected brand, newest first. Returns chatId, title, updatedAt and a link, with a pagination cursor. Use get_chat_artifacts to read a selected chat’s referenced designs and automations. Conversation messages and snippets are excluded. | yes | no | yes | no | `GET /v1/chats` | | `list_integrations` | List connected or available integrations. A human connects providers in Brew Settings; this read does not begin OAuth. | yes | no | yes | no | `GET /v1/integrations` | | `list_notifications` | List the brand’s Brew notifications, newest first, as the app’s bell shows them: generations, sends, imports, domain checks and score runs finishing or failing, plus comment mentions addressed to you on a personal connection. Each row has its notificationId, type, status, title, subtitle, a link and the ids it concerns (chatId, emailId, domainId). Rows outside this connection’s access are left out, so a type it cannot see is an empty page; billing alerts reach organization admins only. Read-only and free; nothing is marked read. Follow a chat with get_chat_artifacts. | yes | no | yes | no | `GET /v1/notifications` | | `report_tool_issue` | Use this when the user asks to report a problem with a Brew tool. Files a technical diagnostic report about one failed call for Brew support: the tool name, its status and error code, a Brew request ID if the user has one, and a short description of what went wrong (no conversation text). Free. Returns a flareId support can look the report up by. Product feedback goes to submit_feedback. | no | no | no | no | MCP only | | `submit_feedback` | Use this when the user asks to send the Brew team a problem, a feature request, a question or praise. Sends their own message to the Brew inbox, with an optional title and issue type. Do not include conversation history or unrelated context. The message carries no secrets, API keys, tokens or recipient addresses. Technical diagnostics for failed tool calls go to report_tool_issue. | no | yes | no | yes | MCP only | ## Resources Attach a resource to give your agent context before it calls tools. Each resource uses the connection's permissions. Brand context resources are available on brand connections; organization connections offer the public gallery resources and can request brand context through tools with `brand_id`. | Resource | Context | Connection | | - | - | - | | `brew://templates` | Ten public template summaries with reference IDs and preview links. | Brand or organization | | `brew://flows` | The first 100 public email sequences, with slugs, email counts, time spans, and the `total`. Page through the rest with `list_flows`. | Brand or organization | | `brew://brand` | Brand identity and voice, email design document, image style, and logos, plus extraction readiness. | Brand | | `brew://emails` | The connected brand's newest email designs with preview links. | Brand | | `brew://audiences` | Saved audiences for the connected brand, each with a cached `count` that can lag. For a fresh size, call `list_audiences` with the `audienceId` and `include: ["count"]`. | Brand | `brew://brand` returns the brand's saved `identity` (name, tagline, description, links) with `emailDesign`, `imageStyle`, and `logos`. For the same context through a tool, use `get_brand({ include: ["emailDesign", "imageStyle", "logos"] })`. A plain `get_brand` already returns the identity. ## Conventions ### `response_format` Only two tools take `response_format`, because only their results come in two shapes. Every other tool returns one shape and refuses the field as an invalid argument. | Tool | `concise` *(default)* | `detailed` | | - | - | - | | `search_contacts` | Each row has the address, name, subscription and suppression state, validation status, and custom fields (plus `openProfile` when you `include` it). | The full contact row, adding import, consent, per-domain opt-out, validation-provider, and timestamp details. | | `get_brew_capabilities` | The overview alone. | Also `http_api`, a paginated catalog of HTTP endpoints; continue it with `http_cursor`. | The HTTP API, SDK, and CLI always return the full contact row. Every result carries its record in `structuredContent`, and every tool publishes that record's shape as its `outputSchema` in `tools/list`, so a client can validate a result and read its fields without guessing. ### `idempotency_key` Write tools that can be retried accept an optional `idempotency_key`: a repeat call with the same key replays the original result instead of acting twice. Use a fresh UUID per intended action. See [Safe Retries](/api-reference/mcp/authentication-and-scoping#safe-retries-idempotency). ### `include` Expansions are opt-in. Every tool that takes `include` takes an array of the expansion names its input schema lists (`include: ["html"]` on `get_email`, `include: ["emailDesign", "logos"]` on `get_brand`). A string is refused. ### Previews Email and image tools attach Brew's stored preview where your client can show it in the transcript, plus an Open in Brew link, and the result's text says which previews the client shows. Markdown images are left out: some clients turn them into a "Show Image" button instead of the design. `preview: false` returns text only. ### Confirmation On OAuth and organization connections, a call that emails people or removes contact data returns a confirmation request first: campaigns, tests to someone else, automation launches and trigger fires, publishing or resuming an automation, resuming a send, deleting contacts or a contact field, and verifying a domain that has campaigns held on it. After the user approves, the same call with `confirmed: true` and the request's `confirmation_id` runs it. See [Confirmation](/api-reference/mcp/authentication-and-scoping#confirmation). ### Limit Errors When a call hits a plan limit (`INSUFFICIENT_CREDITS`, `SEND_QUOTA_EXCEEDED`, `BRAND_LIMIT_REACHED`, or an audience run held at the send allowance), the MCP error states the limit and when it resets. It does not suggest upgrading. `get_usage` shows the limit, the balance, and the reset date (`period.end`). The brand limit does not reset; deleting an unused brand frees a slot. The HTTP API keeps its own suggestion text. ### Result Size Results are sized to fit a model's context: * A list page comes back whole or not at all. When a page is too large, the call returns `RESPONSE_TOO_LARGE` with no rows and names what to lower (the `limit`, or an `include` expansion). Rows are never trimmed behind a cursor. `list_insights` is the one exception: it trims instead of refusing. * List pages are smaller than the HTTP API's, and each tool's `limit` states its bounds. [MCP Page Sizes](/api-reference/api/pagination#mcp-page-sizes) owns the numbers and the `list_insights` trimming rule. * A single record comes back whole in `structuredContent`. Its text summary may be shortened, keeping the identifiers and next steps. A record past the hard cap returns `RESPONSE_TOO_LARGE` too. * A write always returns its outcome. An oversized result is compacted in place (long strings and arrays shortened), keeping every field's type. ## Email Language Every design carries a `lang`: the language its copy is written in, as an ISO 639-1 code or `zh-Hans` / `zh-Hant`. Brew reads it after each content change unless a caller set it, and renders it as the HTML document's `lang` (and `dir` for right-to-left languages) on every send and export, and in the HTML `get_email` returns. * `get_email` returns `lang` on the design once Brew has read it. * `create_email` accepts `lang` to name the language up front. Omit it and Brew detects it from the finished body. * `update_email_metadata` accepts `lang` to set or correct it. Like the other metadata fields it is free and creates no version. A value you set is kept: Brew stops re-detecting it after later edits. Pass `lang: null` to clear it, and Brew reads the language from the email again. ## Chat Artifacts and Feedback `list_chats` returns chat titles, links and timestamps. Select a chat and use `get_chat_artifacts` for its referenced email designs, automations and triggers. These tools do not return previous messages, conversation snippets, channel context or the model used in the chat. `import_contacts` (JSON rows) and `import_contacts_csv` (CSV text) create missing contacts, subscribed unless a row opts out, and update existing ones. Both take `consent`, `validate` and `fileName`, record the batch in Import History, and return its `importId`. `onConflict: "skip"` leaves existing contacts unchanged, and `dryRun: true` returns the same counts without writing anything. `update_contact` updates one existing contact and cannot create one. Contact field values must match the declared field type; use `list_contact_fields` to read those definitions. When you ask to send feedback, `submit_feedback` takes your message, an optional title and an issue type. Brew redacts secrets and addresses and sends those fields to Notra's Brew inbox. `report_tool_issue` records a requested technical issue for Brew support and returns a support reference. Neither automatically attaches conversation history. Ordinary tool results keep diagnostic identifiers on the server. Read our [Privacy Policy](/legal/privacy-policy) for data recipients, retention, public asset handling and deletion controls. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # MCP Workflows Source: https://docs.brew.new/api-reference/mcp/workflows Use Brew MCP tools to send an email, build a segment, publish an automation, and analyze results with guided workflows for your assistant. `get_brew_capabilities` lists the current tools and guided workflows. Filter it by topic, such as `automation`, for a workflow's full steps. Clients that support MCP prompts can invoke the named workflows below. These recipes assume a brand connection. Organization connections also pass `brand_id` on brand-scoped tools. ## Configure a Brand and Domain `configure_brand` works on either connection scope: 1. `get_brand` with `include: ["emailDesign", "imageStyle"]` reads the current brand, its saved name and tagline included. Wait for extraction to finish before designing or sending. 2. Use `update_brand` for requested identity changes. `emailDesign` and `imageStyle` replace full Markdown documents, so read them first and preserve unrelated sections. 3. `list_domains` to reuse the intended sendable domain. Use `create_domain` only when the requested marketing domain is absent. 4. Publish the returned DNS records at your registrar or DNS provider. The MCP cannot change your DNS. Then call `verify_domain`; pending records mean you need to allow propagation or fix the records. If campaigns are held on the domain, a passing check resumes them, so on OAuth and organization connections `verify_domain` first returns a confirmation request. 5. `update_domain` sets sender defaults. Live sends require `sendable: true`. For a new brand, an organization administrator can connect **All brands** even before the first brand exists. The organization-only `onboard_brand` workflow lists existing brands, calls `create_brand` only for a requested new brand, then polls `get_brand` with the returned `brandId` as `brand_id` until `ready` is true (and reports a failed extraction) before following `configure_brand`. Brand connections configure their selected brand. To extract a different brand, reconnect with organization scope. Website extraction creates a new brand; it does not re-extract an existing one. Brand logos and transactional domain setup are managed in the app. [Brand Identity](/brand/brand-identity) and [Verify Your Sending Domain](/get-started/verify-your-sending-domain) cover the app steps. ## Launch a Campaign `launch_email_campaign`: 1. `create_email` and, if needed, `edit_email`. Poll `get_email` when generation is still running. 2. `send_email` with the `emailId`, a `subject`, `test: true` and your own address as `to`. Omitting `domainId` uses Brew's test sender. Check the received email; acceptance by the send tool does not prove inbox delivery. 3. `list_domains` with `sendableOnly: true` and `sendingPurpose: "marketing"`; choose the intended sender. 4. `list_audiences` to choose an opted-in audience. Include `["count"]` with its `audienceId` to review membership. 5. On OAuth or an organization connection, call `send_email` with `emailId`, `subject`, `audienceId`, `domainId`, and an `idempotency_key`. 6. Show the returned confirmation preview. After approval, repeat the exact call with `confirmed: true` and its `confirmation_id`. 7. `get_email_analytics` with `report: { kind: "sends", sendId }` to follow the send. Add `scheduledAt` for a future send. Keep the same retry key for the same intended action. Brand API-key connections execute directly, so review the target before the first live call. The [confirmation contract](/api-reference/mcp/authentication-and-scoping#confirmation) owns the full behavior. ## Build a Segment and Send `build_segment_and_send`: 1. `search_contacts` and `list_contact_fields` to inspect the available fields. 2. `create_audience` with a name and `filters: { filters: [...], logicalOperator: "and" }`. 3. Review the returned member count, then follow the send workflow above. Saved audiences infer omitted filter types from the field registry. Date ranges need `type: "date"`. [Create Audiences](/audience/create-audiences) owns filter semantics. ### Import or Update Contacts Before Segmenting `import_contacts` (JSON rows) and `import_contacts_csv` (CSV text) add missing contacts and update existing ones, up to 1,000 rows per call; inspect row errors and retry only the failed rows after fixing them. Each call is one batch in [Import History](/audience/add-contacts#import-history): pass `fileName` to name it, and filter on the returned `importId` to list its contacts (each keeps it until a later import touches that contact). `update_contact` changes one existing contact; a missing contact is an error there. Register missing custom fields with `create_contact_field` first, then use their declared types. Import only people who opted in and pass `consent` (usually `{ "source": "import" }`); an update does not restore an unsubscribed contact's consent. ## Set Up an Automation `set_up_automation`: 1. `save_trigger` to define the event contract; keep the `triggerEventId`. 2. `create_email` and `get_email` for ready designs. Pick a verified domain with `list_domains`. Each send node in `save_automation` needs `emailId`, `emailVersionId`, `domainId`, and `subject`. 3. `test_automation` with the `automationId` and a sample `payload` containing `email` and values for every required trigger and template field. Omit `testRecipient` to exercise the flow without sending mail. A no-delivery test still needs recipient and content values to traverse send nodes. 4. Inspect each returned run with `list_automation_runs` using `run: { kind: "execution", automationRunId, include: ["logs"] }`. Fix failures and cover branches before publishing with `save_automation` and `published: true`. Check the returned `isLive` and `liveVersion`. 5. `check_trigger` to verify readiness; `fire_trigger_event` starts live runs. 6. `list_automation_runs` with `run: { kind: "execution", automationId }` to monitor them. Publishing and firing require the confirmation flow on OAuth and organization connections. If you set `testRecipient`, the test delivers email to that address. Use the [tool schemas](/api-reference/mcp/tools) for graph inputs and test scenarios. ## Run an Automation for an Audience `run_audience_automation` guides a one-shot launch: 1. Choose a saved audience and read its current count and build readiness with `list_audiences`. 2. Reuse a suitable graph with `get_automation`, or save a draft whose trigger config has `mode: "manualAudience"` and `audienceId`. Omit the top-level `triggerEventId`; pin each send node's email version and verified domain. 3. `test_automation` with the `automationId` and a sample `payload` containing `email` and values for every required template or condition field. Omit `testRecipient` and inspect execution logs as above. A manual-audience launch uses the saved graph and does not require event-style publishing. 4. Call `run_automation` with `dryRun: true` to review the recipient count, send-node count, and exclusion warnings. 5. After approval, launch without `dryRun`, using one `idempotency_key` and the confirmation flow when required. A retry uses the same key and unchanged arguments. 6. Follow the returned `audienceRunId` with `list_automation_runs` using `run: { kind: "audience", audienceRunId }`. Use `pause_audience_run`, `resume_audience_run`, or `cancel_audience_run` when requested. Cancelling cannot undo already-delivered email. [Build an Automation](/create-emails/build-an-automation) covers the corresponding app workflow. ## Wire a Trigger from Code `wire_trigger_from_code` validates a trigger's payload and integrates the fire into your codebase. Production code fires over the REST API, not MCP. For the steps, call `get_brew_capabilities` with `topic: "automation"`. ## Analyze Performance `analyze_campaign_performance` uses `get_email_analytics` with `report.kind` set to `overview`, `sends`, or `events`. Pass a `sendId` with `sends` for one delivery job. Use `list_automations` with `analytics: {}` for automation performance. ## Personalize with a CRM MCP `personalize_with_crm` enriches contacts who already opted in: 1. Read their context from your CRM MCP. 2. Use `create_contact_field` for missing attributes, then `update_contact` with its `fields` map. 3. Build an audience, create its email, and follow the send workflow. 4. Read the results and refine the segment. [Sync a CRM into Brew over MCP](/api-reference/mcp/sync-a-crm) owns the full workflow and field mapping. [What You Can Send](/get-started/what-you-can-send) owns the consent rules. ## Improve Deliverability `improve_deliverability` diagnoses domain and delivery problems. For the steps, call `get_brew_capabilities` with `topic: "domains"`. ## Report an MCP Issue `report_mcp_issue` files one report per failed call through `report_tool_issue`, and returns a `flareId` Brew support can look up. It includes the tool that failed, its status and error code, a Brew request id if you have one, and a short summary of what went wrong. It never includes conversation text, secrets, or names, addresses, or recipient lists. Product feedback goes to `submit_feedback` instead. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Build with Brew Source: https://docs.brew.new/api-reference/overview Choose the Brew CLI, TypeScript SDK, REST API, or MCP server, then follow the right quickstart to create an email and test it in your inbox. Use the interface that fits where you work. All four act on the same Brew brands, email designs, contacts, and sends. ## Choose Your Interface | Interface | Best for | Start here | | - | - | - | | **CLI** | Terminal work, shell scripts, CI, and agents that run commands. | [CLI Quickstart](/api-reference/cli/quickstart) | | **TypeScript SDK** | Node applications and TypeScript agents. | [TypeScript Quickstart](/sdks/typescript/quickstart) | | **REST API** | Other languages and direct HTTP requests. | [Send Your First Email from Code](/api-reference/guides/send-your-first-email-from-code) | | **MCP** | Assistants that connect to remote MCP tools. | [MCP Quickstart](/api-reference/mcp/quickstart) | Finish [adding your brand](/get-started/add-your-brand) first, and [check that it is ready](/api-reference/guides/check-brand-readiness) before you generate. Each quickstart generates a design and sends a test to your own inbox. Generation uses [credits](/api-reference/api/credits). A test with Brew's default sender needs no audience or verified domain. ## Designs, Sends, and Automations * **Email design:** reusable content. Keep its `emailId` and, to pin a version, `emailVersionId`. Creating it sends nothing. * **Send:** one production delivery job, identified by `sendId`. Read it for status and engagement statistics. * **Automation:** a graph that sends designs when a trigger fires or a manual audience run starts. A test returns its recipient and completed status without creating a production send row. The [Data Model](/api-reference/api/data-model) maps the remaining entities. ## Authentication and Retries | Interface | Credential | Brand for an organization credential | Retry key | | - | - | - | - | | REST API | Bearer API key | `X-Brand-Id` header | `Idempotency-Key` header | | TypeScript SDK | Client `apiKey` | Client `brandId` or `withBrand(brandId)` | Request option `idempotencyKey` | | CLI | `brew-cli login` or `BREW_API_KEY` | `--brand` or `BREW_BRAND_ID` | `--idempotency-key` | | MCP | OAuth or API key | Tool argument `brand_id` | Tool argument `idempotency_key` | A brand credential resolves its own brand. An organization credential has no default brand. Retry keys apply only to writes whose command or schema supports them. See [API Authentication](/api-reference/api/authentication), [MCP Authentication](/api-reference/mcp/authentication-and-scoping), and [Idempotency](/api-reference/api/idempotency). HTTP and SDK calls execute authorized writes directly. The CLI gates destructive commands; `--yes` confirms an authorized action. MCP uses confirmation requests on OAuth and organization connections. Brand API-key connections execute directly. Production marketing sends need a verified marketing domain and recipients who opted in. Event-driven delivery, including receipts and password resets, uses a published automation and its trigger. See [Emails and Automations](/create-emails/emails-vs-automations) and [What You Can Send](/get-started/what-you-can-send). ## References * [CLI Commands](/api-reference/cli/commands), [SDK Resources](/sdks/typescript/resources), and [MCP Tools](/api-reference/mcp/tools) describe each interface. * [Public API v1](/api-reference/public-v1/contacts/get-contacts) owns HTTP request and response schemas. * [API Contracts](/api-reference/api/api-introduction#cross-cutting-rules) owns shared errors, permissions, pagination, and limits. * [v1 Migration](/api-reference/api/v1-migration) maps older routes and response shapes. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Automation performance Source: https://docs.brew.new/api-reference/public-v1/analytics/automation-performance /api-reference/openapi-public-v1.yaml get /v1/analytics/automations Windowed per-automation performance + scoped `totals` + the resolved `range`. Defaults to the last 30 days. Reflects LIVE runs only (test runs never contribute). Totals include every matching automation independently from the displayed row `limit`. Narrow with the `automationId` filter; bound the window with `from` / `to`. Check `truncated`: when true, scan budgets clipped the requested window and the metrics are partial. Requires the `automations` scope. # Brand overview (totals, rates, timeseries) Source: https://docs.brew.new/api-reference/public-v1/analytics/brand-overview-totals-rates-timeseries /api-reference/openapi-public-v1.yaml get /v1/analytics/overview Windowed brand overview: the exact read behind the app's Analytics metric cards and chart (same per-recipient dedup and machine open and click exclusion), so API, MCP and page numbers always agree. Defaults to the last 7 days. **Use when** you need totals, rates and a time series for the brand or for one automation, design, audience, source, domain or recipient set. For individual rows use `getEventsAnalytics`. **Input** Filters compose freely: `source` (csv of send sources), `automationId`, `emailId`, `audienceId` (csv, max 20), `triggerEventId` (csv, max 10, resolved to the automations they wire), `domain` (sending domain) and `recipient` (csv of recipient rules, same grammar as `getEventsAnalytics`). A single filter is answered from pre-aggregated rollups; any combination, and anything with `domain` or `recipient`, aggregates raw events instead: exact but capped, so watch `truncated` on wide windows. **Returns** `200 { totals, rates, buckets, granularity, timeZone, range, truncated }`; `truncated: true` means the window exceeded the scan budget, so narrow the range. Requires the `emails` scope. **Errors** `400 INVALID_REQUEST` for an inverted window or too many csv values. **See also** `getEventsAnalytics`, `getAutomationAnalytics`, `listSends` (campaign rows carry their own `stats`). # Unified events feed Source: https://docs.brew.new/api-reference/public-v1/analytics/unified-events-feed /api-reference/openapi-public-v1.yaml get /v1/analytics/events Read-only feed of the brand's analytics events (email, automation, trigger, inbound), newest first, over a `from`/`to` window that defaults to the last 7 days, except for a `sendId` or `automationRunId` read, which is bounded by that send or run. Email rows carry the send behind them (`sendId`, `emailId`), so a page joins back to `GET /v1/sends/{sendId}`. **Use when** you need per-event or per-recipient detail. For windowed totals and rates use `getAnalyticsOverview`; for one send's events in one bounded page use `GET /v1/sends/{sendId}?include=events` (`getSend`). **Input** Equality filters: `eventType`, `sendId` (not windowed unless `from`/`to` are given), `emailId`, `automationId`, `messageClass` (`marketing` or `transactional`; absent stamps count as marketing). Run scope: `automationRunId` returns one run’s events across every domain (its lifecycle rows and the deliveries it produced), newest first and not windowed unless `from`/`to` are given; only `eventType` combines with it. Recipient rules `recipient` (csv, max 10): a full address matches exactly, `@domain` matches everyone on the domain, other text matches as a substring, a `!` prefix excludes (`recipient=@clay.com,!ceo@clay.com`); includes OR together, excludes always apply. Send facets `source` (csv), `audienceId` (csv, max 20), `domain` (sending domain), `triggerEventId` (csv, max 10, resolved to the automations they wire). Any facet or recipient rule narrows the feed to email events and adds `sendSource`, `sendContext` and `messageClass` to each row (plus `triggerProvider` and `triggerTitle` on triggered rows). Machine-classified opens and clicks (scanner detonation, Apple proxy prefetch) are excluded unless `includeMachineOpens=true` or `includeMachineClicks=true` (audit only). **Grouped counts** `groupBy` (one or two csv fields: `eventType`, `emailId`, `automationId`, `sendId`, `source`, `link`, `recipientDomain`, `unsubscribeReason`) and/or `bucket` (`day`, `week` or `month`, UTC, Monday weeks) count the email events the same filters list instead of returning them: `link` with `eventType=clicked` is clicks per link, `unsubscribeReason` counts an unsubscribe once per reason it gave. The count reads the newest 20,000 events; a busier window answers `truncated: true` with `coveredFrom` (narrow `from`/`to` or add `eventType`). `count` counts events, so repeat opens each count; a group of opened, clicked or delivered events (not grouped by `link`) also carries `recipients`, each recipient counted once per message within `range`. **Returns** `200 { data: Event[], pagination: { limit, cursor, hasMore }, range }`; page with `cursor` until it is `null`. Rows carry the run join keys when stamped: `automationRunId`, `triggerInstanceId`, `audienceRunId` (plus `sendId`, `nodeId`). With `groupBy`/`bucket`: `200 { count, groups: [{ key, bucket?, count, recipients? }], otherCount, range, truncated, coveredFrom? }`, the largest 200 groups first. Requires the `emails` scope. **Errors** `400 INVALID_REQUEST` for an inverted window, an unknown `eventType`, or more than 10 recipient rules or 20 audience ids; with `groupBy`/`bucket`, for an unknown or repeated field, more than two fields, a non-email `eventType`, `cursor` or `automationRunId` (`limit` is ignored). **See also** `getAnalyticsOverview`, `listSends`, `listAutomationRuns`. # Create an API key Source: https://docs.brew.new/api-reference/public-v1/api-keys/create-an-api-key /api-reference/openapi-public-v1.yaml post /v1/api-keys Mints a new API key through an exact `org:admin` Clerk session; API-key and OAuth actors receive `403`. The plaintext `key` is returned once and only its hash plus final preview are stored. This operation intentionally does not support response replay or `Idempotency-Key`, because replay would disclose the credential again. `brandId` in the body is the NEW KEY's binding (omit for an organization-wide key) — the only v1 body field named `brandId`. Permissions default to `["all"]`. To rotate without downtime, send only `replacesKeyId`; Brew copies the active predecessor's name, scope, and permissions and leaves it active until you revoke it after switching consumers. # List API keys Source: https://docs.brew.new/api-reference/public-v1/api-keys/list-api-keys /api-reference/openapi-public-v1.yaml get /v1/api-keys Lists one cursor page of API-key metadata for the active organization. Requires an exact `org:admin` Clerk session; API-key and OAuth actors receive `403`. Organization-level — takes no `X-Brand-Id`. `brandId` on a row is the key's binding, not the request actor. Stored secrets and hashes are never returned. # Revoke an API key Source: https://docs.brew.new/api-reference/public-v1/api-keys/revoke-an-api-key /api-reference/openapi-public-v1.yaml delete /v1/api-keys/{keyId} Revokes an API key in the active organization. Requires an exact `org:admin` Clerk session; API-key and OAuth actors receive `403`. # Create an audience Source: https://docs.brew.new/api-reference/public-v1/audiences/create-an-audience /api-reference/openapi-public-v1.yaml post /v1/audiences Creates a saved audience from a name + filter set (`{ filters: [{ field, operator, value? }], logicalOperator: "and" | "or" }`). Returns `201` with the bare audience row. An `email in [...]` clause listing more than 100 addresses is converted automatically: a fresh date custom field is stamped on the listed EXISTING contacts and the stored filter becomes `customFields. is_not_empty` (a snapshot — addresses with no contact record are skipped), reported back as `emailListMaterializations`; 10,000 addresses max per clause. # Create an audience from analytics events Source: https://docs.brew.new/api-reference/public-v1/audiences/create-an-audience-from-analytics-events /api-reference/openapi-public-v1.yaml post /v1/audiences/from-events Creates a frozen audience snapshot from the same membership filters as `/events`: 1–10 canonical event types, an absolute window up to 90 days (`from` may be omitted when `sendId` is set — the window then derives from that send), optional send/email ids, multi-select automation/audience ids, recipient include/exclude rules, and the machine-click policy. `cohort.exclude` builds the COMPLEMENT instead: every member of a base audience (default: the send's audience; `"all"` = the whole brand) who did NOT match — the base's clauses are copied at build time AND the cohort field must be empty — which is how to re-send after a cancelled send (`eventTypes: ["sent"]`, the `sendId`, `exclude: {}`). Every call generates a unique date field; each matching existing contact stores its latest matching-event timestamp. Returns `201` immediately with `materializationStatus: pending` plus build progress. The audience is unavailable for campaign, smart-send, and automation delivery until the status becomes `ready`. Failed/partial/stale builds remain non-sendable and partial values are cleaned. Poll `GET /v1/audiences/{audienceId}?include=build`. # Delete an audience Source: https://docs.brew.new/api-reference/public-v1/audiences/delete-an-audience /api-reference/openapi-public-v1.yaml delete /v1/audiences/{audienceId} Deletes the audience. Idempotent — an unknown id resolves with `deleted: false`. # Duplicate an audience Source: https://docs.brew.new/api-reference/public-v1/audiences/duplicate-an-audience /api-reference/openapi-public-v1.yaml post /v1/audiences/{audienceId}/duplicate Creates a deterministic copy of the saved audience’s live filters with a server-generated “(copy)” name. Contacts are not copied; both audiences resolve against the same contact records. # Get an audience Source: https://docs.brew.new/api-reference/public-v1/audiences/get-an-audience /api-reference/openapi-public-v1.yaml get /v1/audiences/{audienceId} Reads one saved audience as the bare `Audience` row. **Use when** sizing a send, checking an audience’s filters, or polling an event-cohort build started by `createAudienceFromEvents`. **Input** `audienceId` in the path; `include=count` replaces the cached `count` with a freshly computed member total and `include=build` attaches the latest event-cohort build status (comma-separate both). **Returns** `200` with the row; `build` is present only when requested and a build exists. **Errors** `404 AUDIENCE_NOT_FOUND` for an unknown or cross-brand id; `400 INVALID_REQUEST` for an unknown `include` token. **See also** `listAudiences`, `updateAudience`, `duplicateAudience`, `createSend`. # List audiences Source: https://docs.brew.new/api-reference/public-v1/audiences/list-audiences /api-reference/openapi-public-v1.yaml get /v1/audiences Lists the brand’s saved audiences under `{ data, pagination }`. Each row carries its contact `filters`, a member `count` and ISO timestamps; an audience is the recipient target for `createSend`. **Use when** choosing the `audienceId` for a campaign or an automation launch. **Input** `limit` and `cursor`. **Returns** `200` with a page of `Audience` rows. A listed audience's `count` is its saved member total, recounted before the list answers when contacts changed since that count or it is a day old; an audience that cannot be recounted (still building, unusable filters, a failed or timed-out count) keeps its saved total. `GET /v1/audiences/{audienceId}?include=count` returns the exact total a send targets. **Errors** `400 INVALID_REQUEST` for an unknown query key. **See also** `getAudience` (live `count`, `build`), `createAudience`, `searchContacts`. # Update an audience Source: https://docs.brew.new/api-reference/public-v1/audiences/update-an-audience /api-reference/openapi-public-v1.yaml patch /v1/audiences/{audienceId} Updates `name` and/or `filters` (at least one required). Pass the latest row’s `updatedAt` as `expectedUpdatedAt` to reject stale read-modify-write edits. Returns the bare updated row. Replacement filters follow the same email-list rule as create: an `email in [...]` clause over 100 addresses is converted into a stamped custom-field snapshot (a fresh field per update), reported as `emailListMaterializations`. # Cancel a manual-audience run Source: https://docs.brew.new/api-reference/public-v1/automations/cancel-a-manual-audience-run /api-reference/openapi-public-v1.yaml post /v1/automations/audience-runs/{audienceRunId}/cancel Stops a manual-audience launch for good. Emails already sent are NOT recalled and a canceled run cannot be resumed. **Use when** a launch must not deliver its remaining steps. **Input** `audienceRunId` in the path; no body. **Returns** `200` with the run’s new `status` (`canceled`). **Errors** `409 RUN_NOT_CANCELLABLE` when the run already completed, failed or was canceled, including a repeat cancel with a new `Idempotency-Key` (a retry with the same key replays the first answer); `404 AUDIENCE_RUN_NOT_FOUND` for an unknown or cross-brand id. **See also** `pauseAudienceRun`, `resumeAudienceRun`, `cancelAutomationRun` (one event or test run). # Cancel an automation run Source: https://docs.brew.new/api-reference/public-v1/automations/cancel-an-automation-run /api-reference/openapi-public-v1.yaml post /v1/automations/runs/{automationRunId}/cancel Stops ONE run (an event execution or a test run). Marks it `canceled` (first-terminal-wins: a late completion from the dying workflow can never overwrite it), wakes a run parked on a wait node so it observes the cancel now, and terminates the durable workflow run so a step stuck retrying is freed too. **Use when** a contact must not receive the remaining steps of a journey that already started. **Input** `automationRunId` in the path; an optional `reason` for the audit trail. Nothing further is sent; emails already delivered are NOT recalled and a canceled run cannot be resumed. **Returns** `200` with the run’s new `status` and the `previousStatus` it held. **Errors** `409 RUN_NOT_CANCELLABLE` when the run already finished (`completed`, `failed` or `canceled`); `404 AUTOMATION_RUN_NOT_FOUND` for an unknown or cross-brand id. **See also** `getAutomationRun`, `cancelAudienceRun` (manual-audience launches), `updateAutomation` (`paused` / `published`). # Check a trigger is ready to fire Source: https://docs.brew.new/api-reference/public-v1/automations/check-a-trigger-is-ready-to-fire /api-reference/openapi-public-v1.yaml get /v1/automations/triggers/{triggerEventId}/readiness Reports whether a fire would start anything right now, and everything a caller needs to wire one. Runs the same credential, brand scope and permission gates a real fire hits, without firing. **Use when** wiring an external service, before sending a live event. **Returns** `200 { ready, blockers[], payloadSchema, endpoint, publishedAutomations, counts, delivery? }`. A `NO_PUBLISHED_AUTOMATION` blocker with `ready: false` means the trigger resolves and the credential passes, but nothing published listens for it yet, so a fire would start no runs. That stays a 200 because a probe has to report why a fire would not work. `delivery` appears for an integration trigger whose source sends only the events set up at its end (a Shopify shop sends a topic only to its own webhook): whether Brew has received that event, and what to set up when it has not. It never changes `ready`. **Errors** `404 TRIGGER_EVENT_NOT_FOUND` for an unknown or cross-brand id; `409 TRIGGER_NOT_FIREABLE` for a Brew event trigger, which Brew starts itself. **See also** `fireTrigger`, `getTriggerContract`, `listTriggers`. # Create a trigger Source: https://docs.brew.new/api-reference/public-v1/automations/create-a-trigger /api-reference/openapi-public-v1.yaml post /v1/automations/triggers Creates a custom trigger event definition — the contract automations subscribe to. Body carries `{ title, description?, payloadSchema }`; the server mints `triggerEventId` and hardcodes `provider: "brew_api"`. Integration triggers (clerk, stripe, shopify, …) are provisioned by the corresponding integration only. `payloadSchema.fields` MUST declare `{ key: "email", type: "string", required: true }` so downstream automations can resolve a recipient. Returns `201` with the bare trigger row. # Create an automation Source: https://docs.brew.new/api-reference/public-v1/automations/create-an-automation /api-reference/openapi-public-v1.yaml post /v1/automations Deterministic create: the body carries the full graph (`{ name, triggerEventId?, nodes, connections }`). **Use when** you have minted every design a `sendEmail` node references (`generateEmail` first). Publish afterwards with `updateAutomation` (`{ "published": true }`), or launch a manual-audience automation with `runAutomation`. **Input** Trigger binding, exactly one: an EVENT automation passes `triggerEventId`; a MANUAL-AUDIENCE automation omits it and gives the trigger node `config: { "mode": "manualAudience", "audienceId": "…" }`. Typed conditions: every filter and condition-mode split uses a non-empty `conditions` array; each condition needs `field`, `type` (`string`, `number`, `date` or `bool`) and a canonical snake_case `operator`; unary operators omit `value`, comparisons require a type-correct scalar, a non-empty array, or an exact two-value `between` tuple (see `AutomationNode`). Every `sendEmail` node carries `emailId`, `emailVersionId` and `subject` (`previewText` is optional; the design's `` is the source of truth). `domainId` is optional at create time; publishing or running requires a verified one from `listDomains`. There is no `messageClass` key: the delivery class derives from the sending domain's `sendingPurpose` (a transactional-purpose domain sends with no unsubscribe link and delivers to unsubscribed contacts), so pick the class by picking the domain. Node ids are stored as sent, except the two shapes `NODE_ID_REPLACED` reports. `dryRun: true` validates without persisting. **Returns** `201` with the bare `AutomationRow`; with `dryRun: true`, `200` with an `AutomationDryRunReport` `{ valid, blockers[], warnings[], blockingIssues[], nodeCounts }` (`blockers[]` fail publish, `warnings[]` are advisory, `blockingIssues[]` lists per-node references the bound trigger or contact catalog cannot provide, each of which also fails publish; `valid` is false when any blocker or blocking issue is present). **Errors** `400 AUTOMATION_GRAPH_INVALID` with `details.issues[]` (`kind`, `nodeId`, `message` per problem, plus `code` on a `structure` issue); `404 TRIGGER_EVENT_NOT_FOUND` for an unknown `triggerEventId`. **See also** `updateAutomation`, `testAutomation`, `runAutomation`, `createTrigger`. # Declare a trigger payload contract Source: https://docs.brew.new/api-reference/public-v1/automations/declare-a-trigger-payload-contract /api-reference/openapi-public-v1.yaml put /v1/automations/triggers/{triggerEventId}/contract Declares the stored payload contract for the trigger, changes how it is enforced, or both, in one call. `fields` and `enforcement` are both optional, so arming enforcement is `{ "enforcement": "strict" }`. While a PUBLISHED automation consumes the trigger the change must stay backward compatible (the ratchet below); loosening is always allowed. **Use when** you want generated types, a dry-run validator (`validateTriggerPayload`) and drift detection for the JSON your service fires, or when you flip `enforcement`. Draft the tree from a real payload with `inferPayloadContract`. Trigger contracts MUST keep a top-level `{ key: "email", type: "string", required: true }` field so automations can resolve a recipient. **Input** `fields` is a tree: scalars (`string`, `int`, `float`, `boolean`, `date`, `enum`), `object` nodes with `children`, `array` nodes with `children` (object elements), `itemType` (scalar elements) or neither. The tree is validated BEFORE any write: unknown-typed nodes are refused, keys are unique per level, an `object` declares at least one child, and no two top-level fields that a fire copies onto the contact fold to one contact field (`plan` and `Plan`, `team_size` and `Team Size`; rename one or set `syncToContact: false` on one). `enforcement`: `off` (advisory, the default for a new contract), `prune` (drop undeclared keys before the run), `strict` (reject a payload carrying them). A `fallbackValue` satisfies `required` in EVERY mode: a producer that omits the key never fails a fire, every recipient gets the fallback. The version bumps only when the behavioral surface changes (keys, types, required, fallbacks; not descriptions or examples). Declaring a contract never changes fire behavior by itself. Loosening is the escape hatch when `strict` rejects a drifted producer in production. **Returns** `200` with the same body a follow-up `getTriggerContract` returns plus `warnings[]` (always present, often empty): `ENFORCEMENT_LOOSENED_WHILE_PUBLISHED` when enforcement went down while published automations consume the trigger (tightening back is refused until they are unpublished or detached), and one `REQUIRED_FIELD_SATISFIED_BY_FALLBACK` per required field that declares a fallback (`field` is its dotted path). Ratchet while a published automation consumes the trigger: tighten `off→prune`, `off→strict`, `prune→strict` = `409`; loosen = `200` + warning; remove, retype or enum-narrow a field, or add a required field WITHOUT a fallback = `409`; add an optional field, widen a type, add an enum value, or add a required field WITH a fallback = `200` (+ warning per fallback). With no published consumer every change is `200`. **Errors** `409 CONTRACT_LOCKED_BY_PUBLISHED_AUTOMATIONS` for a change the ratchet refuses (`message` names the incompatibility; unpublish or detach the consumers, or make a compatible change); `404 TRIGGER_EVENT_NOT_FOUND`; `422 TRIGGER_IMMUTABLE` for a Brew event trigger, whose contract Brew owns; `400 INVALID_REQUEST` (`param: "fields"`) when the tree fails structural validation, or when a body with no `fields` targets a trigger that has no stored contract yet. **See also** `getTriggerContract`, `validateTriggerPayload`, `inferPayloadContract`, `updateAutomation` (publishing a consumer starts the ratchet). # Delete a trigger Source: https://docs.brew.new/api-reference/public-v1/automations/delete-a-trigger /api-reference/openapi-public-v1.yaml delete /v1/automations/triggers/{triggerEventId} Deletes a custom trigger. Refused with `409 TRIGGER_HAS_DEPENDENT_AUTOMATIONS` while automations still reference it (`details.referencingAutomations` lists each blocker). Idempotent — an already-gone trigger resolves with `deleted: false`. # Delete an automation Source: https://docs.brew.new/api-reference/public-v1/automations/delete-an-automation /api-reference/openapi-public-v1.yaml delete /v1/automations/{automationId} Cascade-deletes the automation: every version row, its event and test runs, and their logs. Contacts mid-flow stop. Manual-audience runs that have not finished (scheduled, queued, running or paused) are canceled and kept as history, so `listAudienceRuns` still returns them. Referenced email DESIGNS are shared resources and always survive. Idempotent — an unknown or cross-brand id resolves with `deleted: false`, never `404 AUTOMATION_NOT_FOUND`. `409 AUTOMATION_IN_PROGRESS` while the agent is still generating the automation; retry once it finishes. # Fire a trigger Source: https://docs.brew.new/api-reference/public-v1/automations/fire-a-trigger /api-reference/openapi-public-v1.yaml post /v1/automations/triggers/{triggerEventId}/fire Fires the trigger: validates the payload against the stored contract, upserts the contact it describes, then starts one run per published automation attached to the trigger. **Use when** an event in your product should start every published automation attached to this trigger. **Input** `{ payload }`, validated against the trigger’s `payloadSchema`. Unknown fields are accepted and reported in `warnings[]`. The contact derived from the payload is upserted before the fan-out with the declared top-level scalar fields the fire sent; object and array fields stay template data, and a contract `fallbackValue` is never written onto the contact. A value the contact field’s type refuses is left out and reported as a `FIELD_TYPE_MISMATCH` warning (`field`, `expectedType`, `actualType`); the rest of the contact is written and the runs still start. **Returns** `202 { triggerInstanceId, triggerEventId, status, automationRunIds[], notStarted[], publishedAutomations[], counts, warnings[], receivedAt }`. Follow a run with `getAutomationRun`, the fire itself with `getTriggerInstance`. `notStarted[]` names each automation whose run failed to start and why, so a `triggered` fire with no runs explains itself. `counts.skipped` is the recipients a suppression already covered, so `automations: 2, skipped: 2` means nothing was delivered. **Idempotency** send a stable `Idempotency-Key` header on every retry. A repeat answers `200` with `status: "replayed"` and the ORIGINAL run ids; nothing fires twice. A fire key is matched against the stored trigger receipt, so it replays for as long as the receipt is kept (90 days), not only the 24 hours of the shared response cache. Use one key per business action and never reuse it for a different fire. **Errors** `400 INVALID_PAYLOAD` when the payload does not satisfy the schema, or when `email` (or `user.email`) is not one plain address such as `jane@example.com`: a display name (`Jane `), a list or a line break is refused with `details.errors[].code: "invalid_email"`, and no contact is written; `404 TRIGGER_EVENT_NOT_FOUND` for an unknown or cross-brand id; `422 NO_PUBLISHED_AUTOMATION` when nothing published listens for the trigger; `409 IDEMPOTENCY_CONFLICT` when a key is reused with a different body; `409 TRIGGER_NOT_FIREABLE` for a Brew event trigger, which Brew starts itself (try its automation with `testAutomation`). **See also** `checkTriggerReady`, `getTriggerInstance`, `listAutomationRuns`. # Get a manual-audience run Source: https://docs.brew.new/api-reference/public-v1/automations/get-a-manual-audience-run /api-reference/openapi-public-v1.yaml get /v1/automations/audience-runs/{audienceRunId} Reads one manual-audience launch as the bare `AudienceRun` row: `status`, `approvalState`, `pauseReason` while paused, recipient totals, per-node `nodeStats`. A gradual run carries its authored ramp; the batch progress of each send step is on its own send (`nodeStats[].sendId`). **Use when** polling a launch to completion or reading its funnel. **Input** `audienceRunId` in the path. **Returns** `200` with the row. **Errors** `404 AUDIENCE_RUN_NOT_FOUND` for an unknown or cross-brand id. **See also** `listAudienceRuns`, `pauseAudienceRun`, `resumeAudienceRun`, `cancelAudienceRun`, `listSends` (`?audienceRunId=`). # Get a trigger Source: https://docs.brew.new/api-reference/public-v1/automations/get-a-trigger /api-reference/openapi-public-v1.yaml get /v1/automations/triggers/{triggerEventId} Reads one trigger as the bare row: `triggerEventId`, `title`, `provider`, `payloadSchema` and timestamps. **Use when** inspecting the payload shape before firing, or generating an integration brief for the fire endpoint. **Input** `triggerEventId` in the path (URL-encode composite integration ids); `include=skill` adds `skill`, a SKILL.md-shaped wiring brief built from the stored contract when one exists. **Returns** `200` with the row; `skill` is present only when requested. **Errors** `404 TRIGGER_EVENT_NOT_FOUND` for an unknown or cross-brand id; `400 INVALID_REQUEST` for an unknown `include` token. **See also** `listTriggers`, `getTriggerContract`, `fireTrigger`, `checkTriggerReady`. # Get a trigger instance Source: https://docs.brew.new/api-reference/public-v1/automations/get-a-trigger-instance /api-reference/openapi-public-v1.yaml get /v1/automations/trigger-instances/{triggerInstanceId} Reads one fired trigger-event instance as the bare row: its `state`, the automations it matched, the `automationRunIds` it started and the `rejectionReason` when it was refused. **Use when** following the `triggerInstanceId` a fire returned to the runs it started. **Input** `triggerInstanceId` in the path. **Returns** `200` with the row. **Errors** `404 TRIGGER_INSTANCE_NOT_FOUND` for an unknown or cross-brand id. **See also** `listTriggerInstances`, `getAutomationRun`, `listSends` (`?triggerInstanceId=`). # Get a trigger payload contract Source: https://docs.brew.new/api-reference/public-v1/automations/get-a-trigger-payload-contract /api-reference/openapi-public-v1.yaml get /v1/automations/triggers/{triggerEventId}/contract The payload contract for the trigger: the STORED contract when one has been declared (`source: "stored"`, with `contractHash`, `version`, `enforcement`), otherwise the derived one (`source: "derived_from_schema"`, built from the trigger’s flat `payloadSchema`). Contract fields form a tree: scalars (`string` | `int` | `float` | `boolean` | `date` | `enum`), `object` nodes with `children`, and `array` nodes with `children` (element object shape) or `itemType` (scalar elements). Derived contracts may carry `type: "unknown"` where no type evidence exists. Pass `?format=` for generated artifacts instead of the JSON contract. # Get an automation Source: https://docs.brew.new/api-reference/public-v1/automations/get-an-automation /api-reference/openapi-public-v1.yaml get /v1/automations/{automationId} Reads one automation as the bare row, LEAN by default (graph omitted), with `published`, `paused`, `pausedAt`, the live version it serves, its creator (`createdBy`, `createdByUserId`) and, while live, the live version’s publisher (`publishedBy`, `publishedByUserId`). **Use when** reading a flow before editing or publishing it, pinning `liveAutomationVersionId`, or inspecting its graph. **Input** `automationId` in the path; `include=graph` inlines `nodes` and `connections` and `include=versions` the lean `{ version, automationVersionId }` history (comma-separate both). **Returns** `200` with the row; the `include` fields are present only when requested. **Errors** `404 AUTOMATION_NOT_FOUND` for an unknown or cross-brand id; `400 INVALID_REQUEST` for an unknown `include` token. **See also** `listAutomations`, `updateAutomation`, `testAutomation`, `runAutomation`. # Get an automation run Source: https://docs.brew.new/api-reference/public-v1/automations/get-an-automation-run /api-reference/openapi-public-v1.yaml get /v1/automations/runs/{automationRunId} Reads one run as the bare row: the automation and version it executed (`automationVersionId` is a valid publish pin, `definitionHash` the graph fingerprint), the fire behind it (`triggerInstanceId`), `mode`, `status` and timestamps. **Use when** debugging one contact’s journey or confirming a test run finished. **Input** `automationRunId` in the path; `include=logs` inlines the newest 100 execution log rows in `orderIndex` order and sets `logsTruncated` when older rows exist. Each node status change is its own row: a node that runs has a `running` row (no `completedAt`), then its terminal `completed` or `failed` row, or `skipped` when the run is canceled while it runs; a node a branch rules out has only a `skipped` row. A node’s outcome is its last row. A run canceled between two nodes adds no row, so the node that finished keeps its outcome; the run’s `status` and `error` record the cancel. **Returns** `200` with the row; `logs` is present only when requested. **Errors** `404 AUTOMATION_RUN_NOT_FOUND` for an unknown or cross-brand id; `400 INVALID_REQUEST` for an unknown `include` token. **See also** `listAutomationRuns`, `cancelAutomationRun`, `listSends` (`?automationRunId=`), `getEventsAnalytics` (`?automationRunId=`). # Get or create an unsubscribe trigger Source: https://docs.brew.new/api-reference/public-v1/automations/get-or-create-an-unsubscribe-trigger /api-reference/openapi-public-v1.yaml post /v1/automations/triggers/brew-events Returns the brand’s trigger for one Brew event scope, creating it the first time. Brew events start automations from things that happen inside Brew. The first is `contact.unsubscribed`: a contact unsubscribed with an email’s unsubscribe link or their mail app’s one-click button (never a bounce, complaint, import or API edit). **Use when** an automation should start when a contact unsubscribes, from one marketing domain’s list or from every email the brand sends. **Input** `{ event: "contact.unsubscribed", scope: "domain", domainId }` for one marketing domain’s list (ids from `listDomains`), or `{ event: "contact.unsubscribed", scope: "all" }` for every email. An unsubscribe from all clicked in one of a domain’s emails also starts that domain’s trigger, while the contact was still on its list. **Returns** `201` with the new trigger row, or `200` with the existing one (`created: false`). Brew owns its title and payload, so the row is immutable and never fires over the API. The contact has just opted out, so an automation on this trigger sends only a message they need (such as confirming the unsubscribe) from a transactional domain, or mail from another marketing domain they are still on; publish refuses a flow none of whose emails could reach them. **Errors** `400 INVALID_REQUEST` when `domainId` is missing for `scope: "domain"` or sent for `scope: "all"`; `404 DOMAIN_NOT_FOUND` for an unknown or cross-brand domain; `422 DOMAIN_PURPOSE_NOT_ALLOWED` for a transactional domain, which owns no list; `409 TRIGGER_LIMIT_REACHED` when the brand already holds the maximum number of triggers. **See also** `createAutomation`, `fireTrigger`, `listDomains`. # Infer a payload contract from an example Source: https://docs.brew.new/api-reference/public-v1/automations/infer-a-payload-contract-from-an-example /api-reference/openapi-public-v1.yaml post /v1/payload-contracts/infer Drafts a contract from a real example payload: paste the JSON your system sends and get back typed `fields` — integers and floats split automatically, full ISO timestamps become `date`, object/array shapes are walked recursively. Every inferred field is `required: true` (relax explicitly). Spots inference cannot type (nulls, empty arrays) degrade honestly and are listed in `issues` with the offending path. Nothing is saved: review the draft, then `PUT` it to `…/triggers/{triggerEventId}/contract`. # List automation runs Source: https://docs.brew.new/api-reference/public-v1/automations/list-automation-runs /api-reference/openapi-public-v1.yaml get /v1/automations/runs Lists recent runs (event executions and test runs), newest first, under `{ data, pagination }`. Rows are lean: identity, `automationVersionId`, `definitionHash`, `triggerInstanceId`, `mode`, `status` and timestamps. **Use when** auditing what an automation did, following a fire (`triggerInstanceId`) to its runs, or watching a test run. **Input** `automationId`, `triggerEventId`, `triggerInstanceId`, `recipientEmail` (one contact's run history, matched case-insensitively), `status`, `mode` (`live` | `test`), an inclusive `from`/`to` window on `startedAt`, `limit` and `cursor` (an opaque native cursor). **Returns** `200` with a page of run rows. Each page reads a bounded slice of history, so it can hold fewer rows than `limit`, even none, while `hasMore` is true; follow `cursor` until it is `null`. **Errors** `400 INVALID_REQUEST` for an unknown query key, a reversed window or a malformed cursor. **See also** `getAutomationRun` (with `include=logs`), `cancelAutomationRun`, `listTriggerInstances`, `listSends`. # List automations Source: https://docs.brew.new/api-reference/public-v1/automations/list-automations /api-reference/openapi-public-v1.yaml get /v1/automations Lists the brand’s automations under `{ data, pagination }` as LEAN rows: identity, `name`, `version`, `published`, `paused` and live-version state, `emailIds`, `updatedAt` and attribution; the graph is omitted. **Use when** browsing automations or finding the `automationId` to update, run or inspect. **Input** `limit` and `cursor` (an opaque native cursor). **Returns** `200` with a page of lean automation rows. `createdBy` / `createdByUserId` name the creator (`createdBy: "API"` when an organization API key made it, `Former member` once a person leaves the brand, absent when the creator cannot be named); while live, `publishedBy` / `publishedByUserId` name whoever published the live version. **Errors** `400 INVALID_REQUEST` for an unknown query key or a malformed cursor. **See also** `getAutomation` (with `include=graph,versions`), `createAutomation`, `listAutomationRuns`. # List manual-audience runs Source: https://docs.brew.new/api-reference/public-v1/automations/list-manual-audience-runs /api-reference/openapi-public-v1.yaml get /v1/automations/audience-runs Lists manual-audience launches (each "Run" of a manual-audience automation), newest first, under `{ data, pagination }`: status, recipient totals and the per-node funnel. **Use when** watching launches started with `runAutomation` or auditing an automation’s manual sends. **Input** `automationId` and `status` to narrow; `limit` and `cursor`. The page is a slice of the newest 200 launches. **Returns** `200` with a page of `AudienceRun` rows. **Errors** `400 INVALID_REQUEST` for an unknown query key or status. **See also** `getAudienceRun`, `runAutomation`, `pauseAudienceRun`, `listAutomationRuns`. # List trigger instances Source: https://docs.brew.new/api-reference/public-v1/automations/list-trigger-instances /api-reference/openapi-public-v1.yaml get /v1/automations/trigger-instances Lists fired trigger-event instances, newest first, under `{ data, pagination }`: the audit log of every inbound fire, from the API (`source: "api"`), an integration webhook (`source: "integration"`), or Brew itself (`source: "brew_event"`, a contact unsubscribing). Each row links the fire to the automations it matched and the runs it started (`automationRunIds`). **Use when** confirming that fires arrived, or following a fire to its runs and sends. **Input** `triggerEventId` to narrow to one trigger; `limit` and `cursor` (an opaque native cursor). **Returns** `200` with a page of `TriggerInstance` rows. **Errors** `400 INVALID_REQUEST` for an unknown query key or a malformed cursor. **See also** `getTriggerInstance`, `fireTrigger`, `listAutomationRuns` (`?triggerInstanceId=`), `listSends` (`?triggerInstanceId=`). # List triggers Source: https://docs.brew.new/api-reference/public-v1/automations/list-triggers /api-reference/openapi-public-v1.yaml get /v1/automations/triggers Lists every trigger the brand has under `{ data, pagination }`: `provider: "brew_api"` for API-created customs, `provider: "clerk" | "stripe" | …` for integration-provisioned triggers, and `provider: "brew_event"` for the unsubscribe triggers Brew starts itself. Each row carries its `payloadSchema`. **Use when** finding the `triggerEventId` to fire, to wire an automation to, or to read the typed contract of. **Input** `limit` and `cursor`. **Returns** `200` with a page of trigger rows. **Errors** `400 INVALID_REQUEST` for an unknown query key. **See also** `getTrigger` (with `include=skill`), `createTrigger`, `fireTrigger`, `listTriggerInstances`. # Pause a manual-audience run Source: https://docs.brew.new/api-reference/public-v1/automations/pause-a-manual-audience-run /api-reference/openapi-public-v1.yaml post /v1/automations/audience-runs/{audienceRunId}/pause Holds a running manual-audience launch at its next step boundary. Delivery already in flight for the current step completes; nothing further goes out until `resumeAudienceRun`. **Use when** a launch must stop temporarily, for example to fix a downstream step. **Input** `audienceRunId` in the path; no body. **Returns** `200` with the run’s new `status` (`paused`). A run its operator already paused returns the same `200` and changes nothing. **Errors** `409 RUN_NOT_PAUSABLE` when the run is scheduled, completed, failed or canceled, or held at the plan limit (`pauseReason: plan_limit`: it resumes on its own once the monthly send allowance has room, so cancel it to stop it); `404 AUDIENCE_RUN_NOT_FOUND` for an unknown or cross-brand id. **See also** `resumeAudienceRun`, `cancelAudienceRun`, `getAudienceRun`. # Resume a manual-audience run Source: https://docs.brew.new/api-reference/public-v1/automations/resume-a-manual-audience-run /api-reference/openapi-public-v1.yaml post /v1/automations/audience-runs/{audienceRunId}/resume Continues a paused launch, or restarts a FAILED one under a fresh workflow run: it picks up at the first send step that never delivered and skips every step the failed run finished, so nothing is resent. `resumedFrom` reports which case ran. A launch held at the plan limit (`pauseReason: plan_limit`) resumes on its own once the monthly send allowance has room. **Use when** a paused launch may continue, or a failed launch should finish its remaining steps. **Input** `audienceRunId` in the path; no body. **Returns** `200` with the run’s new `status` and `resumedFrom` (`paused` or `failed`). **Errors** `409 RUN_NOT_PAUSED` when the run is neither paused nor failed (scheduled, queued, running, completed or canceled); `409 RUN_NOT_RESUMABLE` when the run is held at the plan limit, or a failed run has no undelivered send step or a send step delivered to only part of its segment; `409 RUN_IN_PROGRESS` when another run of the automation is active; `402 SEND_QUOTA_EXCEEDED` when resuming would exceed the monthly send limit; `422 AUTOMATION_NOT_READY` when a send step still to go can no longer send, such as a sender domain that is no longer verified (the message names the step); `503 RUN_STOP_FAILED` / `RUN_START_FAILED` when the workflow engine could not stop the previous run or start the new one (retry); `404 AUDIENCE_RUN_NOT_FOUND` for an unknown or cross-brand id. **See also** `pauseAudienceRun`, `cancelAudienceRun`, `getAudienceRun`. # Run a manual-audience automation Source: https://docs.brew.new/api-reference/public-v1/automations/run-a-manual-audience-automation /api-reference/openapi-public-v1.yaml post /v1/automations/{automationId}/run Launches a MANUAL-AUDIENCE automation against the audience bound to its trigger node. `dryRun: true` previews without sending; `scheduledAt` launches later, at most 1 year ahead. Percentage-based `gradualSend` delivers each send step in custom hour or calendar-day batches and supports manual pause/resume/cancel. `400` when `scheduledAt` is more than 1 year ahead, or a `gradualSend` plan exceeds 50,000 recipients, 30 batches, or 30 elapsed days. `422 AUTOMATION_NOT_RUNNABLE` for an event automation, which runs when its trigger fires. `422 AUTOMATION_NOT_READY` when the saved flow cannot launch: a step is incomplete or invalid, a send step’s sender domain is not verified, generation failed, or no usable audience is bound (the message names which). `422 EMAIL_IMAGES_MISSING` when a step would send a cdn.brew.new image that does not exist (`details.missingImages[]`). `409 AUTOMATION_IN_PROGRESS` while the agent is still generating the automation. Returns `202` with the `audienceRunId`. # Test an automation Source: https://docs.brew.new/api-reference/public-v1/automations/test-an-automation /api-reference/openapi-public-v1.yaml post /v1/automations/{automationId}/test Runs the saved automation END-TO-END through the real workflow in TEST mode — works on drafts and for both event and manual-audience automations; every node executes (filters/splits evaluate against `payload`, and `contact.` conditions read the test recipient’s contact unless `payload` supplies that field — a flat `contact.` key or a `contact` object — and the trigger’s contract keeps extra keys; wait nodes fast-forward). Pass `testRecipient` to DELIVER each send-email node’s email for real to that address (real subject/preview/sender name; verified configured sender domains are preserved, otherwise delivery uses the Brew test domain; customer addresses are never hit; the address must be a teammate with access to the brand, an address on a verified sending domain of the brand, or, for a signed-in person (not an API key), their own address or one on their company domain, else `422 TEST_RECIPIENT_NOT_ALLOWED`) — omit it for a silent dry-run with no mail. Test runs are excluded from live analytics rollups. Test deliveries never count toward the plan’s email sends. Test payloads never update real contact records. Returns `202` with the started run id; follow per-node status via `GET /v1/automations/runs/{automationRunId}?include=logs`. Optional `scenario` controls simulate timed opens/clicks at engagement-filter nodes and force left/right percentage-split choices (waits use a virtual clock; controls stay separate from `payload`, and simulated events never enter live analytics or send quotas); the run row’s `testCoverage` reports visited nodes, traversed connections, evaluated or forced decisions, uncovered paths and simulation limitations. On a Brew-event (unsubscribe) trigger, omit payload to use Brew’s sample event; supplied fields replace the sample’s. The run never creates or edits a contact. `400 INVALID_PAYLOAD` when `payload` does not match the trigger’s payload schema; `422 AUTOMATION_NOT_READY` when generation failed or a step is incomplete or invalid (the message names it); `409 AUTOMATION_IN_PROGRESS` while the agent is still generating the automation. # Update a trigger Source: https://docs.brew.new/api-reference/public-v1/automations/update-a-trigger /api-reference/openapi-public-v1.yaml patch /v1/automations/triggers/{triggerEventId} Updates one or more editable fields (`title`, `description`, `payloadSchema`). Whether a trigger fires is governed solely by `automation.published` on each wired automation — there is no per-trigger off-switch. Integration-provisioned triggers are immutable here (`422 TRIGGER_IMMUTABLE`). While a published automation uses the trigger, a `payloadSchema` change that would stop it from running (removing or retyping a field it reads, or declaring the shape of an open object or list so one of its merge tags no longer resolves) is refused with `409 CONTRACT_LOCKED_BY_PUBLISHED_AUTOMATIONS`. Returns the bare updated row. # Update or publish an automation Source: https://docs.brew.new/api-reference/public-v1/automations/update-or-publish-an-automation /api-reference/openapi-public-v1.yaml patch /v1/automations/{automationId} One endpoint, two mutually exclusive modes: update the graph (a new `automationVersionId` on the same `automationId`) or change lifecycle state (`published`, `paused`). The modes cannot be combined: update first, then `PATCH { "published": true }`. **Use when** editing a graph or changing runtime state of an automation created with `createAutomation`. Manual-audience runs are controlled with `pauseAudienceRun`, `resumeAudienceRun` and `cancelAudienceRun`, not here. **Input** Update: one or more of `name`, `description`, `nodes`, `connections`, `triggerEventId`, under the same typed condition contract as create (explicit `type`, canonical snake_case `operator`, no `value` for unary operators, type-correct values elsewhere); `dryRun: true` validates without persisting. Node ids are stored as sent, so renamed nodes keep their new ids, except the two shapes `NODE_ID_REPLACED` reports. Lifecycle: `published: true` promotes the stored latest version live (optionally pin `automationVersionId`; the graph is validated first), `published: false` unpublishes, `paused: true` or `false` freezes or resumes future send steps (`stopInFlight` also stops runs already in progress). **Returns** the bare automation row, or with `dryRun: true` a `200 AutomationDryRunReport` `{ valid, blockers[], warnings[], blockingIssues[], nodeCounts }`: `blockingIssues[]` lists per-node references the effective trigger or contact catalog cannot provide, and publish refuses every one of them, fallback or not (`fatal` says what the reference would do: `true` for filter or split conditions and triple-brace `{{{ }}}` body tokens would break the run, `false` for subject, previewText, fromName, replyTo and double-brace body tags would render empty); `valid` is false when any blocker or blocking issue is present. Updating a LIVE automation saves a draft and does not go live: the previously published version keeps serving until you republish, `published` describes the returned row, `isLive`, `liveVersion` and `liveAutomationVersionId` describe the automation, and `warnings[]` carries `DRAFT_SAVED_NOT_LIVE`. Publishing an automation whose integration trigger has not received its event on the current connection (a Shopify topic with no webhook) still succeeds, and `warnings[]` carries `TRIGGER_EVENT_NOT_RECEIVED` saying what to set up. **Errors** `404 AUTOMATION_NOT_FOUND`, `AUTOMATION_VERSION_NOT_FOUND` (pin `liveAutomationVersionId`, a `versions[]` id, or a run row's `automationVersionId`), `TRIGGER_EVENT_NOT_FOUND`; `400 AUTOMATION_GRAPH_INVALID` (`details.issues[]`); `409 AUTOMATION_VERSION_CONFLICT` (re-read, reapply, retry); `422 PUBLISH_VALIDATION_FAILED` (`details.blockers[]`; a cdn.brew.new image a step would send that does not exist is a blocker, listed in `details.missingImages[]`, and a dead icon whose real file sits elsewhere in its pack is moved there instead when the key has `emails` access), `AUTOMATION_NOT_PUBLISHED` (nothing to unpublish; with `stopInFlight: true` on a draft, also no contacts in flight to stop), `AUTOMATION_NOT_PAUSABLE` (a manual-audience automation pauses through its runs). **See also** `createAutomation`, `testAutomation`, `runAutomation`, `listAutomationRuns`. # Validate a trigger payload Source: https://docs.brew.new/api-reference/public-v1/automations/validate-a-trigger-payload /api-reference/openapi-public-v1.yaml post /v1/automations/triggers/{triggerEventId}/contract/validate Dry-runs a payload against the trigger's contract — the SAME validator the live path runs, against the stored contract when one exists (derived otherwise; `source` says which). Nothing fires, sends, or writes. An invalid payload is still a `200`: the verdict is the response — read `valid`, `errors`, `warnings`, `resolvedPayload` (fallbacks applied), and `prunedKeys`. Pass `enforcement: "prune" | "strict"` to preview a different mode than the stored one. Fire for real with `POST …/fire`. # Delete a brand image Source: https://docs.brew.new/api-reference/public-v1/brand/delete-a-brand-image /api-reference/openapi-public-v1.yaml delete /v1/brand/images/{assetId} Removes one image from the brand library and from image search, as Delete image on the Assets page does. Its file stays hosted at its URL, so emails already using it keep rendering. **Use when** an image should no longer be offered for new designs. Confirm with the user first. Free; no credits are charged. **Input** `assetId` in the path, as `getBrandImages` returns it. One image per call. **Returns** `200` with `{ assetId, deleted }`. An `assetId` not in the library resolves `deleted: false` and changes nothing, so repeating the call is safe. **Errors** `400 INVALID_REQUEST` for a logo (manage logos on the Assets page) or a malformed `assetId`. **See also** `getBrandImages`, `addImage`. # Get brand images Source: https://docs.brew.new/api-reference/public-v1/brand/get-brand-images /api-reference/openapi-public-v1.yaml get /v1/brand/images The brand’s asset library, as the Assets page shows it: logos, brand images (from the site or uploaded, including the social preview and site screenshot) and images made with Brew. Omit `?q=` to BROWSE it, newest first or `?sort=oldest`. Pass `?q=` for SEMANTIC search over brand and generated images (the query is embedded + vector-searched), in relevance order. Both are free. `?kind=logo|brand|generated` narrows either mode; logos are not searchable. Each row carries `assetId` (the id the app opens at `/assets?image=`), `kind`, `url` and what is known: description, dimensions, category, page, when it was added, and a logo’s variant. (`GET /v1/brand` returns the brand `identity`, and the smaller `emailDesign` / `imageStyle` / `logos` sub-resources embed with `?include=…`; images stay separate because they paginate.) # Get the brand bound to this API key Source: https://docs.brew.new/api-reference/public-v1/brand/get-the-brand-bound-to-this-api-key /api-reference/openapi-public-v1.yaml get /v1/brand Returns the bare brand row for the single brand bound to the API key. Check `ready` (`status === "completed"`) before calling `POST /v1/emails`, which returns `422 BRAND_NOT_READY` until brand extraction finishes. `identity` is always returned: the brand name and tagline saved in Brew (`identity.brandName`, `identity.tagline`), plus its description, contact details and links. `domain` is the website the brand was extracted from, not its name. Embed the design context in the same call with `?include=emailDesign,imageStyle,logos` (comma-separated). `emailDesign` / `imageStyle` are the markdown design system the email agent follows; `logos` is the CDN logo set. `include=identity` is still accepted and changes nothing. The paginated image library is a separate read (`GET /v1/brand/images`). # Update brand identity + design system Source: https://docs.brew.new/api-reference/public-v1/brand/update-brand-identity-+-design-system /api-reference/openapi-public-v1.yaml patch /v1/brand Partial update of the writable design artifacts in one call. `identity` shallow-merges the provided fields; `emailDesign` / `imageStyle` replace the markdown design-system documents the email agent follows. Provide at least one. Returns the brand in the `GET /v1/brand` shape: `identity` always, plus the markdown documents the call wrote. # Create a brand and start its extraction Source: https://docs.brew.new/api-reference/public-v1/brands/create-a-brand-and-start-its-extraction /api-reference/openapi-public-v1.yaml post /v1/brands Starts an asynchronous brand extraction that crawls the site and builds the design system. Returns `201` immediately with `status: "extracting"` — poll `GET /v1/brands/{brandId}` until `ready` is `true` (typically 1–3 minutes) before calling `POST /v1/emails`, which returns `422 BRAND_NOT_READY` until then. Requires an ORGANIZATION-scoped credential (`403 ORG_SCOPE_REQUIRED` otherwise) and the `brands` scope, which is NOT implied by `emails`. Extraction requires a non-empty credit balance but is not itself charged to your credits. # Get one brand’s lifecycle state Source: https://docs.brew.new/api-reference/public-v1/brands/get-one-brand’s-lifecycle-state /api-reference/openapi-public-v1.yaml get /v1/brands/{brandId} The polling endpoint for `POST /v1/brands`. Reports `status`, `progress` and `phase` while extracting, and `error` when extraction failed. Terminal states are `completed` and `failed`. For the brand’s DESIGN CONTEXT (identity, markdown design system, logos) use `GET /v1/brand` instead. # List the brands this credential can reach Source: https://docs.brew.new/api-reference/public-v1/brands/list-the-brands-this-credential-can-reach /api-reference/openapi-public-v1.yaml get /v1/brands Organization-scoped credentials see every brand in the organization; a brand-scoped credential sees exactly the one brand it is bound to. This is how an organization-scoped credential discovers the ids it passes in `X-Brand-Id` on every other endpoint. # Get chat context Source: https://docs.brew.new/api-reference/public-v1/chats/get-chat-context /api-reference/openapi-public-v1.yaml get /v1/chats/{chatId} Read a brand-scoped digest of a Brew chat for resuming the conversation in an external agent: the emails + automations it created/referenced (latest version, with preview), the trigger events it touched, and a trimmed tail of the transcript. Read-only and free. `404 CHAT_NOT_FOUND` for an unknown id OR a chat owned by a different brand (the two are indistinguishable). # List chats Source: https://docs.brew.new/api-reference/public-v1/chats/list-chats /api-reference/openapi-public-v1.yaml get /v1/chats Lists the brand's Brew chats, most recently active first, under `{ data, pagination }`, as the app's chat list shows them: `chatId`, `title`, the opening prompt, Brew's latest reply, `status` (still streaming or not), `origin` (the chat app it started in; null for the Brew web app) and a link. No transcript and no participants. Free. **Use when** finding a chat to resume, or seeing what was worked on recently. **Input** `limit` and `cursor` (an opaque native cursor). **Returns** `200` with a page of `ChatListRow` rows. **Errors** `400 INVALID_REQUEST` for an unknown query key or a malformed cursor. **See also** `getChatContext` (one chat, with its artifacts and recent messages). # Create a contact field Source: https://docs.brew.new/api-reference/public-v1/contact-fields/create-a-contact-field /api-reference/openapi-public-v1.yaml post /v1/fields Creates a custom field definition (`{ fieldName, fieldType: "string" | "number" | "date" | "bool" }`). A `number` field holds values up to 9007199254740991 (2^53 - 1) in magnitude, the largest integer it stores exactly; a contact write with a larger JSON number is refused (in a `string` field too, since it arrives already rounded), so send 64-bit ids and counters as JSON strings to a `string` field. Returns `201` with the bare definition. (Contact upserts also auto-create unknown fields — explicit creation is for pinning the type up front.) # Delete a contact field Source: https://docs.brew.new/api-reference/public-v1/contact-fields/delete-a-contact-field /api-reference/openapi-public-v1.yaml delete /v1/fields/{fieldName} Deletes a custom field and clears its value from every contact. The values cannot be recovered, and a field created later with the same name starts empty. **Use when** a field and its values should go. To change a field's type, delete it, create it again with the new type and re-import the values. Check saved audiences first: afterwards a filter on the field sees no value, so `is_empty` and `not_exists` match every contact. **Input** `fieldName` in the path. **Returns** `200` with `{ fieldName, deleted }`. A name with no custom field resolves `deleted: false` and clears nothing, so repeating the call is safe. The three legacy consent fields (`marketingConsentSource`, `marketingConsentCapturedAt`, `marketingConsentPolicyVersion`) lose only the definition: their values stay, because they still serve as consent evidence. **Errors** `422 CORE_FIELD_IMMUTABLE` for a core column. `409 AUDIENCE_BUILD_ACTIVE` for the hidden field of an event-derived audience that is still building; retry once the build finishes. **See also** `listContactFields`, `getContactField`, `createContactField`. # Get a contact field Source: https://docs.brew.new/api-reference/public-v1/contact-fields/get-a-contact-field /api-reference/openapi-public-v1.yaml get /v1/fields/{fieldName} Reads one contact field definition (a core column or a custom field) as the bare row: `fieldName`, `fieldType` and its filter/sort/search flags. **Use when** confirming a merge-tag key or a filter field exists before using it. **Input** `fieldName` in the path. **Returns** `200` with the row. **Errors** `404 FIELD_NOT_FOUND` when no definition carries that name. **See also** `listContactFields`, `createContactField`, `deleteContactField`. # List contact fields Source: https://docs.brew.new/api-reference/public-v1/contact-fields/list-contact-fields /api-reference/openapi-public-v1.yaml get /v1/fields Lists core contact columns and custom field definitions under `{ data, pagination }`. Use the field names in audience filters, contact search, and `{{ field | fallback }}` merge tags. Add `?include=coverage` to decorate each row with fill stats — the % of contacts holding a non-empty value plus the most common values (sampled; `approximate: true` on large populations) — and optionally `audienceId` to scope those stats to one saved audience. Check coverage before personalizing on a field so most recipients see a real value, not the fallback. # Batch-delete contacts Source: https://docs.brew.new/api-reference/public-v1/contacts/batch-delete-contacts /api-reference/openapi-public-v1.yaml post /v1/contacts/batch-delete Deletes up to 1000 contacts by email. Returns the deleted count plus `notFound[]` for emails that had no contact. Addresses are lookup keys, not re-validated: any address a contact was stored under matches, and one that matches nothing lands in `notFound[]` instead of failing the batch. # Bulk-import contacts from CSV Source: https://docs.brew.new/api-reference/public-v1/contacts/bulk-import-contacts-from-csv /api-reference/openapi-public-v1.yaml post /v1/contacts/import-csv Parse a raw CSV string and upsert the rows as contacts (≤ 1000). By default each column header maps to the custom field its name folds to, the same camelCase name `POST /v1/contacts` stores (`Plan` → `plan`, `Team Size` → `teamSize`); `email` is required. A header that spells a core field, ignoring case, spaces, `_` and `-`, or whose field key equals it (`First.Name`), maps to it: `Email`, `First Name`, `Last Name` and `Subscribed` fill `email`, `firstName`, `lastName` and `subscribed`. Pass `mapping` to remap single columns; the columns it leaves out keep their default mapping, `""` leaves a column out, and a key that names no column is a `400`. Two columns that land on one field (`plan,Plan`: names fold as on `POST /v1/contacts`; `First Name,firstName`; `email,Email`) are a `422 FIELD_NAME_COLLISION` before any row is read: map one to another name or leave it out with `""`. `mapping` applies first: a core field it fills is read only from the columns it maps there, and an unlisted column whose default would fill the same field is left out with a `CSV_COLUMN_IGNORED` warning (with `mapping: { Consent: "subscribed" }`, a row whose `Subscribed` is `false` and `Consent` is `true` follows `Consent`). Then every column still filling `subscribed` is read, and an opt-out in any of them wins (`Subscribed,Subscribed?`). A column whose name (its header, or the name `mapping` gives it) has no ASCII letter or digit (`名前`, `#`) lands on the existing field labeled with that name, else on a new `column` field labeled with it, N its 1-based column position (`column2v2` when another field or column already holds `column2`). Two columns given one such name are a `422 FIELD_NAME_COLLISION`, and a blank name leaves its column out, as `""` does. Rows with a missing/invalid email are SKIPPED (counted in `summary.skipped`), not errored; disposable-domain rows are imported with `validationStatus: "risky"` (deliverable but flagged). Returns the same `{ summary, fieldsCreated, errors, warnings }` as batch-create plus `importId` — `207` when some rows fail. The batch is listed in Import History under `fileName` (optional), and each contact it writes carries `importId` until a later import touches it (filter on it to list them; deleting the import in the app removes the contacts it created). For rows you already hold as JSON, use `POST /v1/contacts/import`. CSV cells are text: a column mapped onto an EXISTING field is coerced to that field's type (dates → epoch ms, `1,234` → 1234, `yes`/`no` → booleans), and a cell that cannot be coerced (`$49` in a number column) fails ITS row with a per-row `errors[]` entry (`code: FIELD_TYPE_MISMATCH`, `field`) while the other rows still land. A converted cell adds a `warnings[]` entry (`code: FIELD_TYPE_COERCED`, `field`, `from`, `to`); a date written to a `date` field is not reported. An undeclared column is created as a `string` field unless every value is an ISO date (→ `date`); predeclare `number` / `bool` columns with `POST /v1/fields`. A column whose field Brew manages (`Created At`, `Validation Status`) is not imported and adds a `warnings[]` entry (`code: CSV_COLUMN_IGNORED`, `field` names the column). A date column is read in ONE day/month order: the order its own dates prove (a day over 12 anywhere in the column, `13/04/2026`), else `dateOrder` (`day_first` reads `03/04/2026` as 3 April, `month_first` as 4 March), else month/day with a `warnings[]` entry (`code: DATE_ORDER_ASSUMED`, `field`). Dotted dates (`03.04.2026`) are day-first. ISO (`2026-04-03`), Unix seconds or milliseconds, month names (`3 Apr 2026`), year-first (`2026/04/03`) and compact (`20260403`) dates need no order. Convert to `YYYY-MM-DD` to be unambiguous. A `subscribed` column reads true/false and ESP status words (`unsubscribed`, `cleaned`, `blocklisted`, `transactional`, `active`, …). An opt-out unsubscribes the contact, new or existing (with `onConflict: "skip"` an existing contact is left unchanged, and its `CONTACT_EXISTS_SKIPPED` warning says so). A word that is not a subscription status (`maybe`) fails its row (`code: FIELD_TYPE_MISMATCH`, `field: subscribed`) instead of importing the contact subscribed. A subscribed value only applies to new contacts: a row that asks to re-subscribe a contact who opted out keeps its other fields and adds a `warnings[]` entry (`code: RESUBSCRIBE_SKIPPED`, `email`). Two opt-in modes. `dryRun: true` returns the response this import would return (`summary`, `errors`, row `warnings`, `fieldsCreated` as fields it would create) with `dryRun: true` and no `importId`, and writes nothing: no contacts, field definitions or Import History entry; `validate` is not run and nothing is charged. Insert vs update is decided by the same address match the write uses, so a real run right after returns the same counts. `onConflict: "skip"` only creates missing contacts: each existing contact is left unchanged (an opt-out row included), counted in `summary.skipped` with a `CONTACT_EXISTS_SKIPPED` warning naming its `row`. Either way `inserted + updated + failed + skipped = total`. A dry run cannot foresee failures that only happen while writing (a concurrent change, a database refusal), so the real run can still fail where the preview succeeded. With `validate: true`, inline checks are still metered per submitted row, rows `skip` left alone included; a request that leaves no address to check is not charged. # Bulk-import contacts from JSON Source: https://docs.brew.new/api-reference/public-v1/contacts/bulk-import-contacts-from-json /api-reference/openapi-public-v1.yaml post /v1/contacts/import Create or update up to 1000 contacts from JSON rows and record them as one Import History batch: the JSON twin of `POST /v1/contacts/import-csv`. Rows take the batch-create shape (`email`, `firstName`, `lastName`, `subscribed`, `customFields`, `consent`) and follow its rules: a missing or invalid email, or an address repeated in the batch, fails its row (`errors[]`, `207`) while the others land. New contacts are subscribed unless the row says `subscribed: false`; re-subscribing a contact who opted out keeps its other fields and adds a `RESUBSCRIBE_SKIPPED` warning. The batch is listed in Import History under `fileName` (optional), and each contact it writes carries the returned `importId` until a later import touches it (filter on it to list them; deleting the import in the app removes the contacts it created). `POST /v1/contacts` with `contacts[]` writes the same rows without an Import History entry, for recurring syncs. Two opt-in modes. `dryRun: true` returns the response this import would return (`summary`, `errors`, row `warnings`, `fieldsCreated` as fields it would create) with `dryRun: true` and no `importId`, and writes nothing: no contacts, field definitions or Import History entry; `validate` is not run and nothing is charged. Insert vs update is decided by the same address match the write uses, so a real run right after returns the same counts. `onConflict: "skip"` only creates missing contacts: each existing contact is left unchanged (an opt-out row included), counted in `summary.skipped` with a `CONTACT_EXISTS_SKIPPED` warning naming its `row`. Either way `inserted + updated + failed + skipped = total`. A dry run cannot foresee failures that only happen while writing (a concurrent change, a database refusal), so the real run can still fail where the preview succeeded. With `validate: true`, inline checks are still metered per submitted row, rows `skip` left alone included; a request that leaves no address to check is not charged. # Create or update contacts Source: https://docs.brew.new/api-reference/public-v1/contacts/create-or-update-contacts /api-reference/openapi-public-v1.yaml post /v1/contacts Upserts a single contact OR a batch (`{ contacts: [...] }`, up to 1000 rows). Unknown custom fields auto-create field definitions on the brand, typed from the batch (native booleans/numbers, ISO-date strings → `date`, anything else `string`). `fieldsCreated` names only the definitions this request created: when two requests create the same new field at once, the first definition wins and the values in the other request are coerced or refused against it, exactly as if it had been sent second. Create the field first with `POST /v1/fields` to pin its type. Custom-field names are folded to one key: words split at spaces, `_`, `-` and a lower-to-upper letter change, then joined camelCase (`Plan`, `PLAN` and `plan` are the field `plan`; `team_size` and `Team Size` are `teamSize`). A key written under its folded name adds a `FIELD_NAME_NORMALIZED` warning (`original`, `normalized`). Two keys that fold to one field (`plan` and `Plan`) would lose one value, so they are a `422 FIELD_NAME_COLLISION` on a single upsert (nothing written) and a per-row `errors[]` entry (`code: FIELD_NAME_COLLISION`) in a batch. Custom-field values are coerced to the definition's type (dates → epoch ms, `"1,234"` → 1234, `yes`/`no` → booleans). A value that cannot be coerced (`"$49"` in a number field) is a `409 FIELD_TYPE_MISMATCH` on a single upsert and a per-row `errors[]` entry (`code: FIELD_TYPE_MISMATCH`, `field`) in a batch — the other rows still land. A value that was converted adds one `warnings[]` entry per field (`code: FIELD_TYPE_COERCED`, `field`, `from`, `to`); a date written to a `date` field is not reported. A `customFields` key is never stored under a core field name. One whose loss would change the contact (`subscribed`, `First Name`, `consent`, a suppression flag or domain opt-out, or an `email` naming another address) is a `422 CORE_FIELD_IMMUTABLE` on a single upsert (nothing written) and a per-row `errors[]` entry (`code: CORE_FIELD_IMMUTABLE`, `field`) in a batch; send `firstName`, `lastName`, `subscribed` and `consent` at the top level. A key naming a field Brew manages (`createdAt`, `validationStatus`) is dropped with a `warnings[]` entry (`code: CORE_FIELD_IGNORED`, `field`) and the contact is still written, and an `email` key repeating the contact address is ignored. Dates: a JSON number is epoch milliseconds. A string may be ISO (`2026-04-03`, with or without a time and offset), a Unix timestamp in seconds (10 digits) or milliseconds (13), a month name (`3 Apr 2026`, `April 3, 2026`, `03-Apr-26`), year-first (`2026/04/03`), compact (`20260403`), month and year read as the 1st (`2026-04`), dotted day-first (`03.04.2026`), or a slash or dash date. A slash or dash date with a day over 12 reads that way (`13/04/2026` is 13 April). One that reads either way (`03/04/2026`) follows the day/month order the batch's other dates in that field prove, else month/day, with a `warnings[]` entry (`code: DATE_ORDER_ASSUMED`, `field`). Send `YYYY-MM-DD` to be unambiguous. Optional `consent: { source: "api" | "form" | "import", capturedAt?, policyVersion?, evidence? }` records marketing consent provenance on the contact (per row, or once at batch level as the default). It never changes `subscribed`. An inline marketing send later needs the contact to be subscribed, and warns when no record exists. `subscribed: false` unsubscribes the contact, new or existing. `subscribed: true` only applies to a NEW contact: Brew never re-subscribes a contact who opted out, so a single upsert asking for it is a `422 RESUBSCRIBE_NOT_ALLOWED` (nothing written), and a batch row keeps its other fields and adds a `warnings[]` entry (`code: RESUBSCRIBE_SKIPPED`, `email`). Single: `201` with `{ contact, created, fieldsCreated, warnings }`. Batch: `200` with `{ summary, fieldsCreated, errors, warnings }` — or `207` when some rows failed (per-row errors in `errors[]`). # Delete a contact Source: https://docs.brew.new/api-reference/public-v1/contacts/delete-a-contact /api-reference/openapi-public-v1.yaml delete /v1/contacts/{email} Deletes the contact. Idempotent — an unknown email resolves with `deleted: false`. For bulk deletion use `POST /v1/contacts/batch-delete`. # Get a contact Source: https://docs.brew.new/api-reference/public-v1/contacts/get-a-contact /api-reference/openapi-public-v1.yaml get /v1/contacts/{email} Reads one contact as the bare `Contact` row: core columns, `subscribed`, `consent`, validation state and `customFields`. **Use when** checking whether an address exists, reading its consent record, or inspecting its custom fields before a send. **Input** `email` in the path (URL-encoded; matched case-insensitively). `include=openProfile` attaches `openProfile`: the smart-send open-time profile, 48 UTC half-hour open counts (`histogram`), `totalOpens`, `lastOpenedAt`, and once there is enough history `bestOpenMinuteUtc`, `bestSendMinuteUtc` and `confidence`; `null` when the contact has no opens folded yet. It is not bot detection: machine opens cannot be told apart in it (per-event classification is on `getEventsAnalytics`). It needs the `emails` scope as well as `contacts`. **Returns** `200` with the row. **Errors** `404 CONTACT_NOT_FOUND` when no contact carries that address; `403 INSUFFICIENT_PERMISSIONS` when `include=openProfile` is asked for without the `emails` scope; `400 INVALID_REQUEST` for an unknown `include` token. **See also** `listContacts`, `updateContact`, `deleteContact`, `upsertContacts`. # Get contacts Source: https://docs.brew.new/api-reference/public-v1/contacts/get-contacts /api-reference/openapi-public-v1.yaml post /v1/contacts/search The single "Get Contacts" read. Structured search over the brand’s contacts: free-text `search`, `filters` (`{ field, operator, value }` combined with `logic: "and" | "or" | "none"`; the allowed operators depend on the field’s type — see the `operator` schema — and an unsupported pairing is a `400`, never a dropped clause), `sort` + `order`, and cursor pagination. Returns `{ data, pagination }`. `search` with a whole email address matches only that contact, like `filters: [{ field: "email", operator: "equals", value: "…" }]` or `GET /v1/contacts/{email}`. Any other `search` text matches the contacts whose email, first or last name contains any of its words, which can include other contacts, in `sort` order, so act on a contact found by its address. Omit every filter to list everything. Pass an optional `audienceId` to scope the search to a saved audience’s members — its stored filter set is evaluated as one unit with its own `logicalOperator` (an OR audience stays an OR) and then ANDed with `filters`, so the page is exactly who a send to that audience reaches (an unknown / cross-brand id, or an audience a send would refuse → `400`). Set `count: true` to get `{ count }` instead of a page. `include: ["openProfile"]` attaches each returned contact’s smart-send open-time profile (`openProfile`, as on `getContact`; `null` when they have no opens yet). Each row costs one profile read, so a page then holds at most 10 contacts (`pagination.limit` reports the size read); it needs the `emails` scope as well (`403 INSUFFICIENT_PERMISSIONS` without it) and is refused with `count: true`. # List contacts Source: https://docs.brew.new/api-reference/public-v1/contacts/list-contacts /api-reference/openapi-public-v1.yaml get /v1/contacts Lists the brand’s contacts under `{ data, pagination }`, newest first by default. **Use when** paging through contacts, running a free-text search, or reading one saved audience’s members. Typed filter clauses and counts are `searchContacts`. **Input** `search` (a whole email address matches only that contact, with its `+` encoded as `%2B`; other text matches any of its words in email, first and last name), `audienceId` (only that saved audience’s members), `sort` (any core column or custom field, default `createdAt`) and `order`, `limit` and `cursor`. **Returns** `200` with a page of `Contact` rows. **Errors** `400 INVALID_REQUEST` for an unknown `audienceId`, an unsupported `sort` field or an invalid cursor. **See also** `getContact`, `searchContacts`, `upsertContacts`, `listContactFields`. # Update a contact Source: https://docs.brew.new/api-reference/public-v1/contacts/update-a-contact /api-reference/openapi-public-v1.yaml patch /v1/contacts/{email} Patches fields on the contact (`{ fields: { : } }` — core columns or custom fields) and/or records marketing consent provenance (`{ consent: { source, capturedAt?, policyVersion?, evidence? } }`, never re-subscribing an opt-out). Send one or both. Returns `{ contact, updated, warnings }`: `updated` lists the fields whose stored value changed (`consent` included), and is empty when every value sent matched what was stored (nothing is written then). `warnings` carries the same `DATE_ORDER_ASSUMED` and `FIELD_TYPE_COERCED` caveats a single upsert reports: an ambiguous date such as `03/04/2026` reads month/day, so send `YYYY-MM-DD`. A JSON number past 9007199254740991 (2^53 - 1) arrives already rounded, so a `number` or `string` field refuses it with `409 FIELD_TYPE_MISMATCH`; send large ids as JSON strings to a `string` field. `fields.subscribed: false` unsubscribes; `true` on a contact who opted out is a `422 RESUBSCRIBE_NOT_ALLOWED` (they re-subscribe through their own action, or from their contact page in the Brew app). Two `fields` keys that name one field (`plan` and `Plan`, `customFields.plan` and `plan`) are a `422 FIELD_NAME_COLLISION`, nothing written. # Validate email deliverability Source: https://docs.brew.new/api-reference/public-v1/contacts/validate-email-deliverability /api-reference/openapi-public-v1.yaml post /v1/contacts/validate Batch deliverability check (up to 100 addresses) — run BEFORE importing or sending. Each address is classified `valid` (safe), `risky` (deliverable but flagged — e.g. role account, disposable, catch-all), or `invalid` (undeliverable / do-not-send), with a machine-readable `reason` and a `didYouMean` typo correction when applicable. Partial outages retain the legacy `status: risky` with `checkOutcome: unavailable` (not a completed risky verdict) and preserve the stored verdict. `persistence` reports matched, modified and failed update-only writes; validation never grants subscription or clears suppression. Cost: 2 credits PER ADDRESS (`X-Credit-Cost` = 2 × the number of addresses), charged ONLY on success — if the check cannot complete for the whole batch, the call returns `503` (transient outages are retryable; configuration failures need support) and is NOT billed. # Add image Source: https://docs.brew.new/api-reference/public-v1/content/add-image /api-reference/openapi-public-v1.yaml post /v1/content/add-image Adds an image to the brand image library: fetches or reads it, converts it, stores it, and vector-indexes it so the email agent can find it. Free; no credits are charged. **Use when** a public image URL, a batch of them, or a local file should be reusable in designs and searches. **Input** exactly one of `imageUrl` (one public URL, synchronous), `imageUrls` (1 to 100 public URLs, a durable background import) or `uploadId` (a local file whose bytes were sent to the `uploadUrl` from `createImageUpload`, synchronous). **Returns** `200` with `{ url, width, height, aspectRatio, assetId }` for `imageUrl` and `uploadId`; `202` with `{ accepted, skipped, runId }` for `imageUrls`. An image whose size could not be measured answers `width` and `height` `0` and `aspectRatio` `unknown`. Repeating an `uploadId` call returns the same answer for 24 hours, even if the image was deleted since. **Errors** `422 CONTENT_OPERATION_FAILED` when the image cannot be fetched, decoded or saved (for an upload: bytes that are not PNG, JPEG, GIF, WebP, AVIF, TIFF or SVG). For `uploadId`: `404 UPLOAD_NOT_FOUND` (unknown, expired or another brand), `409 UPLOAD_NOT_RECEIVED` (the bytes were never sent), `409 UPLOAD_IN_PROGRESS` (another call is converting it; retry shortly) and `413 PAYLOAD_TOO_LARGE` (over 20 MB, or an SVG over 2 MB). **See also** `createImageUpload`, `getBrandImages`, `deleteBrandImage`. # Create an image upload Source: https://docs.brew.new/api-reference/public-v1/content/create-an-image-upload /api-reference/openapi-public-v1.yaml post /v1/content/image-uploads Opens a single-use upload for one local image file. POST the file's raw bytes to the returned `uploadUrl`, then call `addImage` with the `uploadId` to put it in the brand library. The bytes go straight to storage, so files up to 20 MB fit even though a JSON body is capped far lower. Free; no credits are charged. **Use when** the image is a file on your machine rather than a public URL (a public URL goes straight to `addImage` as `imageUrl`). **Input** `fileName`, `contentType` (`image/png`, `image/jpeg`, `image/gif`, `image/webp`, `image/avif`, `image/tiff` or `image/svg+xml`) and `size` in bytes (at most 20,000,000; 2,097,152 for SVG). **Returns** `201` with `{ uploadId, uploadUrl, expiresAt, maxBytes }`. Within 15 minutes, send the bytes: `curl -X POST --data-binary @logo.png ""` answers `200` with `{ uploadId, status: "uploaded", size, expiresAt }`; call `addImage` before that `expiresAt` (15 minutes from when the bytes land) (`404 UPLOAD_NOT_FOUND` for an unknown or expired URL, `413 PAYLOAD_TOO_LARGE` over `maxBytes`). The URL carries its own credential; keep it private. Sending again never replaces the first file. **Errors** `400 INVALID_REQUEST` for an unsupported `contentType` or a `size` over the cap; `429 RATE_LIMITED` also when the brand already has 20 uploads open (its message says so, and `Retry-After` is when the oldest expires). **See also** `addImage`, `getBrandImages`. # Generate a GIF Source: https://docs.brew.new/api-reference/public-v1/content/generate-a-gif /api-reference/openapi-public-v1.yaml post /v1/content/gif Produces an animated GIF, routed by the `from` discriminator: `prompt` generates one from text, `image` animates a public source image (both with GPT Image 2.6), and `video` converts a source MP4. For `prompt` and `image` sources, aspect ratio is one of `16:9`, `9:16`, `1:1` (default `16:9`, 768×432 / 432×768 / 640×640), `frameCount` is 2–16 (default 9) and `fps` sets playback speed (default 5, so 9 frames loop in 1.8s). An `image` source the model cannot read, or a request it refuses, returns `422 CONTENT_OPERATION_FAILED`. For `video`, use width and fps for conversion. Returns CDN-hosted `gifUrl` (plus `altText`, `width`/`height` and timing metadata for the AI sources). Credit-metered (fixed cost: prompt 20, image 10, video 10). # Generate an image Source: https://docs.brew.new/api-reference/public-v1/content/generate-an-image /api-reference/openapi-public-v1.yaml post /v1/content/generate-image Generates an image via the Brew AI image pipeline. `text-to-image` (default) creates from a prompt; `image-editing` edits `image1` (required) guided by the prompt. Returns a CDN-hosted URL, and saves the image to the brand’s generated images (`GET /v1/brand/images?kind=generated`). Usage-metered: charges the actual image gateway cost (no fixed price). # Render HTML to a PNG Source: https://docs.brew.new/api-reference/public-v1/content/render-html-to-a-png /api-reference/openapi-public-v1.yaml post /v1/content/html-to-png Renders an HTML document to a PNG screenshot hosted on the CDN. Credit-metered (fixed cost). # Transform an image Source: https://docs.brew.new/api-reference/public-v1/content/transform-an-image /api-reference/openapi-public-v1.yaml post /v1/content/transform Deterministic image transform routed by the `operation` discriminator: `optimize` rehosts a palette PNG (resize ≤1200px), `resize` produces exact dimensions via the vision-guided fal pipeline (Sharp cover-crop fallback), `remove_background` returns a transparent PNG cutout (Bria RMBG 2.0). Returns the CDN-hosted `url` + dimensions. Credit-metered (fixed cost: optimize 1, resize 2, remove_background 1). # Add a domain Source: https://docs.brew.new/api-reference/public-v1/domains/add-a-domain /api-reference/openapi-public-v1.yaml post /v1/domains Registers a sending domain with the provider. Optional `sendingPurpose` is `marketing` (default; campaigns, audience sends, automations) or `transactional` (event-triggered automation mail — no unsubscribe link required, merely-unsubscribed contacts still receive it). Returns `201` with the bare row in `status: "pending"` plus the DNS `records` to publish. Once the records are live, call `POST /v1/domains/{domainId}/verify` until `sendable: true`. # Add addresses to a domain's unsubscribe list Source: https://docs.brew.new/api-reference/public-v1/domains/add-addresses-to-a-domains-unsubscribe-list /api-reference/openapi-public-v1.yaml post /v1/domains/{domainId}/unsubscribes Suppresses up to 1,000 addresses from THIS marketing domain's mail. An existing contact is suppressed for this host only — sends from OTHER marketing domains still reach it; set `subscribed: false` on the contact for a brand-wide opt-out. An address with no contact is created already globally unsubscribed, so every marketing domain skips it (`summary.created`). Addresses already on the list count under `alreadyUnsubscribed`, never errored (idempotent); malformed ones are reported in `invalid` and skipped. # Delete a domain Source: https://docs.brew.new/api-reference/public-v1/domains/delete-a-domain /api-reference/openapi-public-v1.yaml delete /v1/domains/{domainId} Removes the domain from the provider and deletes the local row. Idempotent — an unknown id resolves with `deleted: false`. # Export a domain's unsubscribe list Source: https://docs.brew.new/api-reference/public-v1/domains/export-a-domains-unsubscribe-list /api-reference/openapi-public-v1.yaml get /v1/domains/{domainId}/unsubscribes/export The whole list as CSV text (`Email,Scope,Unsubscribed At,Source,Send ID`) inside the JSON envelope — the v1 transport is JSON-only. Capped at 50,000 rows or ~4 MB of CSV, whichever comes first, so the response stays under the platform body limit (`truncated: true` beyond; narrow with `?scope=`). # Get a domain Source: https://docs.brew.new/api-reference/public-v1/domains/get-a-domain /api-reference/openapi-public-v1.yaml get /v1/domains/{domainId} Reads one sending domain as the bare `Domain` row: verification `status`, DNS `records`, `sendable`, `sendingPurpose` and the `openTracking`/`clickTracking` flags. Sender defaults are write-only here: the row does not echo them. **Use when** polling verification after `verifyDomain`, or confirming a domain before a send. **Input** `domainId` in the path. **Returns** `200` with the row. **Errors** `404 DOMAIN_NOT_FOUND` for an unknown or cross-brand id. **See also** `listDomains`, `verifyDomain`, `getDomainHealth`, `updateDomain`. # Get domain health Source: https://docs.brew.new/api-reference/public-v1/domains/get-domain-health /api-reference/openapi-public-v1.yaml get /v1/domains/{domainId}/health The domain's deliverability health in one FREE read: a `verdict` (`healthy` / `at_risk` / `critical`) with actionable `signals`, DNS/auth state incl. DMARC, active percentage-based gradual sends, sampled bounce/complaint activity from campaign and automation sends, workspace reputation, and inbox-placement history. No bounce or complaint threshold is attached to a gradual-send configuration. `include=scoreHistory` adds `scoreHistory`: up to 50 saved score snapshots, newest first (score, grade, confidence, the event that saved it, and each pillar's score and weight); only snapshots saved under this brand count, searched among the domain's newest 500, so a domain that moved between brands can show fewer. `include=scoreRuns` adds `scoreRuns`: the last 5 automated domain score runs (the 5-variant seed check), each with its status in the shared run vocabulary, the score it ended on, the credits it cost and every variant's placement test. # Import a CSV into a domain's unsubscribe list Source: https://docs.brew.new/api-reference/public-v1/domains/import-a-csv-into-a-domains-unsubscribe-list /api-reference/openapi-public-v1.yaml post /v1/domains/{domainId}/unsubscribes/import Migrates an unsubscribe list (another ESP's export) into THIS marketing domain's list. `csv` is the file text: an `email` header — or any column of addresses, or one headerless column; pass `column` to name the header when detection fails (`400` otherwise). Synchronous and bounded: 10,000 rows per call (`truncated: true` when the file carried more — split it across calls) and 2,000,000 characters (a longer `csv` is rejected as `400 INVALID_REQUEST`). Idempotent per address. An address with no contact row is created already globally unsubscribed, exactly as `POST /v1/domains/{domainId}/unsubscribes` does, so every marketing domain skips it. The contact CSV importer's `subscribed` column is the BRAND-WIDE flag — use this endpoint for per-domain opt-outs. # List a domain's unsubscribes Source: https://docs.brew.new/api-reference/public-v1/domains/list-a-domains-unsubscribes /api-reference/openapi-public-v1.yaml get /v1/domains/{domainId}/unsubscribes Every MARKETING sending domain is its own unsubscribe list, keyed by the domain's host inside the brand's contacts. Returns one page (`{ data, pagination }`, newest first). Each row carries `scope`: `domain` (on this host's list), `all` (the brand-wide opt-out — `subscribed: false` on the contact, which blocks every marketing send) or `both`. `?scope=` narrows; `?q=` searches by address. Transactional domains own no list → `422 DOMAIN_PURPOSE_NOT_ALLOWED`. # List domains Source: https://docs.brew.new/api-reference/public-v1/domains/list-domains /api-reference/openapi-public-v1.yaml get /v1/domains Lists the brand’s sending domains under `{ data, pagination }`: ALL lifecycle states by default, so a caller mid-verification can read `pending` rows and their DNS `records`. **Use when** picking the `domainId` for `createSend` or a sendEmail node, or reading DNS records to publish. **Input** `sendableOnly=true` keeps only verified, send-ready domains (the set valid for sends and automation `sendEmail` nodes); `sendingPurpose` keeps one purpose (campaigns and audience sends require `marketing`; automation sendEmail nodes accept both); `limit` and `cursor`. **Returns** `200` with a page of `Domain` rows. **Errors** `400 INVALID_REQUEST` for an unknown query key or purpose. **See also** `getDomain`, `addDomain`, `verifyDomain`, `getDomainHealth`. # Remove an address from a domain's unsubscribe list Source: https://docs.brew.new/api-reference/public-v1/domains/remove-an-address-from-a-domains-unsubscribe-list /api-reference/openapi-public-v1.yaml delete /v1/domains/{domainId}/unsubscribes/{email} Takes one address off THIS domain's list (resubscribes it to this host only). Idempotent — `removed: false` when the address was not on the list. Never clears the brand-wide opt-out: `globallyUnsubscribed: true` means every marketing send still skips the contact until `PATCH /v1/contacts/{email}` sets `subscribed: true`. URL-encode the address. # Update domain settings Source: https://docs.brew.new/api-reference/public-v1/domains/update-domain-settings /api-reference/openapi-public-v1.yaml patch /v1/domains/{domainId} Updates sender defaults (`defaultSenderName`, `defaultFromEmail`, `defaultReplyToEmail`) and/or `sendingPurpose` — at least one required. `defaultFromEmail` is the sender MAILBOX (the text before `@`) — the host is always this domain, so a full address is accepted and reduced to its local part; `defaultReplyToEmail`, by contrast, is a whole address. Live gates fail closed if a campaign still points at a transactional domain. Verification is its own action: `POST /v1/domains/{domainId}/verify`. Returns the bare updated row. # Verify a domain Source: https://docs.brew.new/api-reference/public-v1/domains/verify-a-domain /api-reference/openapi-public-v1.yaml post /v1/domains/{domainId}/verify Re-checks the DNS records with the provider and refreshes the row. Empty body. Safe to poll — keep calling until `sendable: true` (DNS propagation can take minutes to hours). Returns the bare refreshed row. # Audit an email Source: https://docs.brew.new/api-reference/public-v1/emails/audit-an-email /api-reference/openapi-public-v1.yaml post /v1/emails/audit Audits an email for production readiness in parallel: links, images, compliance, loaded size, client support, accessibility and judged copy, plus markup checks. **Use when** a design is about to ship, or to score imported HTML or JSX before a send. A saved design is addressed by `emailId` and rendered exactly as a send renders it. **Input** exactly one of `emailHtml`, `emailJsx` (React Email, rendered by Brew) or `emailId` (+ optional `emailVersionId`), each up to 5,000,000 UTF-8 bytes (the JSON body up to 6 MiB); optional `subject` and `previewText` (each up to 1,000 characters; an omitted subject is not judged, an omitted preview is extracted from the authored preheader, an explicit empty string stays empty); optional `sendingPurpose` (when omitted, the audit infers it from the content and reports it as `inferred`, or as defaulted to marketing when unsure). **Returns** `200` with a stable versioned `{ findings, checks, metrics, summary, completion }`: every check, up to 100 normalized findings (each with optional `evidence`: an HTTP status, the clients that drop a feature, or a judgment probability), exact totals. `completion.status: 'complete'` carries a 0 to 100 score and costs 5 credits (`X-Credit-Cost: 5`); `'partial'` (a required lane was unavailable) has `score: null`, never establishes readiness, costs 0 credits (`X-Credit-Cost: 0`) and releases the idempotency key so the same key can retry. **Errors** `429 RATE_LIMITED` with `Retry-After` when admission is exhausted: 6 requests per minute per credential or session and 20 per minute across the organization (shared by public API, MCP and agent calls), and at most 4 audits concurrently per organization and 16 globally; a capacity rejection never runs or charges the audit. `404 EMAIL_NOT_FOUND` or `EMAIL_VERSION_NOT_FOUND` when a stored design is named and does not exist; `422 CONTENT_OPERATION_FAILED` when the HTML cannot be processed. **See also** `previewEmailAcrossClients`, `createInboxPlacementTest`. # Cancel a send Source: https://docs.brew.new/api-reference/public-v1/emails/cancel-a-send /api-reference/openapi-public-v1.yaml post /v1/sends/{sendId}/cancel Cancels a scheduled or queued send before it goes out, or STOPS any in-flight campaign send. A campaign that is `running` or `paused` is canceled the same way the in-app Stop button does it: the remaining recipients are never delivered while already-sent ones stay sent (every shape re-checks liveness at regular points mid-flight — smart per time bucket, gradual and plain blast at bounded chunk intervals — so a small tail may still deliver after the cancel lands). Idempotent — a send already `canceled` returns `200`. A send already `completed`, `partially_completed` or `failed`, or a non-campaign (automation) send, returns `409 SEND_NOT_CANCELLABLE`. Brand-scoped: an unknown / cross-brand `sendId` is `404`. # Clone an email design Source: https://docs.brew.new/api-reference/public-v1/emails/clone-an-email-design /api-reference/openapi-public-v1.yaml post /v1/emails/{emailId}/clone Creates a NEW design by copying the persisted source snapshot exactly. This is a deterministic database fork: it does not invoke an AI agent, reinterpret markup, re-host assets, or regenerate the preview. Omit `emailVersionId` to clone the current latest row, or pass a version id from `GET /v1/emails/{emailId}?include=versions` to clone that exact historical snapshot. Optional `groupId` (`grp_…` or `ungrouped`) or `groupName` (resolve-or-create) — not both; omit to inherit the source group. Unknown `groupId` → `404 EMAIL_GROUP_NOT_FOUND`. The clone receives fresh design/version ids and the `title` you pass (else `Copy of …`) while JSX, rendered HTML, and the preview image remain identical; rename it any time with `PATCH /v1/emails/{emailId} { title }`. # Create an authenticated email canvas embed session Source: https://docs.brew.new/api-reference/public-v1/emails/create-an-authenticated-email-canvas-embed-session /api-reference/openapi-public-v1.yaml post /v1/canvas/sessions Create a short-lived grant for exactly one group or email. Call from your backend after authenticating your user and authorizing the target. Credentials are returned once; response replay is disabled. API keys remain server-side. # Create an email group Source: https://docs.brew.new/api-reference/public-v1/emails/create-an-email-group /api-reference/openapi-public-v1.yaml post /v1/email-groups Creates a named email folder. Returns `201` with `{ groupId, groupName, emailCount }`. Pass `emailIds` (up to 50) to move existing designs in, in the same transaction as the create; the response then adds `moved` and `notMoved` (`not_found`, `generating`, `not_movable`, `folder_full` or `retry`; resend `retry` ids in a follow-up `PATCH`). Reserved names (`Ungrouped` / `ungrouped` / `__ungrouped__`) are `400`. Duplicate names are `409 EMAIL_GROUP_NAME_CONFLICT`. Pass the returned `groupId` as `groupId` on create/import/clone. # Delete an email design Source: https://docs.brew.new/api-reference/public-v1/emails/delete-an-email-design /api-reference/openapi-public-v1.yaml delete /v1/emails/{emailId} Hard-deletes every version of the design. Idempotent — a miss resolves with `deleted: false` plus a `reason` instead of a 404: `already_deleted` (this id was hard-deleted earlier; `deletedAt` carries when) or `not_found` (no such design on this brand, including cross-brand ids). An `already_deleted` response means the design is gone — do not retry. # Delete an email group Source: https://docs.brew.new/api-reference/public-v1/emails/delete-an-email-group /api-reference/openapi-public-v1.yaml delete /v1/email-groups/{groupId} Deletes a named folder. Member emails move to Ungrouped. Ungrouped cannot be deleted (`400`). Idempotent — an unknown / cross-brand id resolves with `{ deleted: false }`. # Edit an email design Source: https://docs.brew.new/api-reference/public-v1/emails/edit-an-email-design /api-reference/openapi-public-v1.yaml patch /v1/emails/{emailId} Updates a design: an AI edit (`prompt`), its envelope (`title`, `subjectLine`, `lang`, `groupId`), or both in one call. At least one of the five is required. A design renames and moves between groups here exactly like an audience, trigger, automation or group renames through its own PATCH. **Use when** changing an existing design: rewording or restyling it with a prompt, renaming it (a clone starts as `Copy of …`), setting the inbox subject the design carries by default, or filing it in another group. **Input** `prompt` runs the Brew email agent against the current latest version (or the `emailVersionId` pin, optionally grounded by `contentUrls`) and writes a new `version: "latest"` row on the same `emailId` (the previous head becomes a numeric historical version); usage-metered by actual token spend. `title` renames the design (its canvas name, 1 to 200 characters), `subjectLine` sets the default inbox subject, `lang` sets the language of the copy (kept from then on; Brew stops re-detecting it) and `groupId` moves it into an existing group (`null` = Ungrouped); any of them without `prompt` is ONE atomic in-place patch (no AI run, no new version, free). With `prompt`, the rename and move land first so the new version inherits them and the subject is applied to the new head. `emailVersionId` requires `prompt`. **Returns** `200` with the generated-email shape: the NEW head after a prompt edit, or the CURRENT head after an envelope patch (with its `title`, `subjectLine` and `group` after the patch); a text response when the agent answered in prose. **Automations** a prompt edit moves every automation `sendEmail` step pinned to the previous latest version onto the new one, in a new unpublished automation version (while a Brew agent is still building that automation, its in-progress draft is updated in place instead); the published version keeps its pin until the next publish. Steps pinned to an older version do not move. An envelope patch writes no version and moves nothing. **Errors** `404 EMAIL_NOT_FOUND`, `EMAIL_VERSION_NOT_FOUND` (a pin that is not one of this design's versions), `EMAIL_GROUP_NOT_FOUND` (a `groupId` that is not one of this brand's groups); `409 EMAIL_IN_PROGRESS` while the design is still generating (or a concurrent edit moved the head between read and patch); `409 EMAIL_RESULT_UNAVAILABLE` when the edit was saved but its completed result could not be returned (read the saved `emailVersionId` from `error.details`; do not repeat the edit); `422 BRAND_NOT_READY` until the brand has finished extracting; `502 EMAIL_GENERATION_FAILED` when the agent run fails (retry later); `400 INVALID_REQUEST` for a body with none of the four fields, or `emailVersionId` without `prompt`. **See also** `cloneEmail` (name the copy with `title`), `restoreEmailVersion`, `listEmails`. # Export a design to an ESP Source: https://docs.brew.new/api-reference/public-v1/emails/export-a-design-to-an-esp /api-reference/openapi-public-v1.yaml post /v1/emails/{emailId}/export Export a finished email DESIGN to a connected third-party ESP (Braze, Brevo, HubSpot, Klaviyo, Loops, Mailchimp, Mailjet, Iterable, Postmark, OneSignal, Mailgun, SendGrid) as a reusable TEMPLATE. This is NOT a Brew send — it creates a template in the destination platform and does NOT deliver to recipients, and is unrelated to Brew sending domains or audiences. The `provider` must already be connected for the brand (connect ESPs in the Brew app). The exported HTML is automatically made ESP-portable; Loops converts supported content to LMX and creates an editable campaign draft to review before sending. Brevo and Mailjet need `senderEmail` when the account has more than one active sender (with exactly one, it is selected automatically). Pass `dryRun: true` to validate the design, brand ownership, and ESP connection without creating a template. Free (no credits). # Generate an email design Source: https://docs.brew.new/api-reference/public-v1/emails/generate-an-email-design /api-reference/openapi-public-v1.yaml post /v1/emails Generates a new design through the Brew email agent. Designs are pure: no send state, no type. Sending happens later with `createSend`, or a `sendEmail` node in an automation references the returned `emailId` and `emailVersionId`. Usage-metered: the agent's actual token usage is billed. **Use when** you have a brief and want Brew to author on brand. For existing markup use `importEmail`; for a Figma frame use `importFigmaDesign`. **Input** `prompt`; optional `category` (steers the design treatment only: transactional categories get receipt or reset conventions, while delivery for those flows is a triggered automation on a transactional-purpose domain), `contentUrls`, `referenceEmailId`, `title` (the canvas name, 1 to 200 characters; omit and Brew derives one from the subject line or the prompt), `subjectLine` (the design-default inbox subject; `createSend` still takes a per-send `subject`), `lang` (the language of the copy, ISO 639-1; omit and Brew detects it from the finished body), and `groupId` (`grp_…` or `ungrouped`) or `groupName` (resolve or create), not both; omit to land Ungrouped. Supports `Idempotency-Key`. **Returns** `201 { emailId, emailVersionId, html, previewImage?, group, subjectLine?, title? }` when a design was persisted, or `200 { response }` when the agent answered in prose without writing a design. **Errors** `404 REFERENCE_EMAIL_NOT_FOUND` for an unknown `referenceEmailId`; `404 EMAIL_GROUP_NOT_FOUND` for an unknown `groupId`; `422 BRAND_NOT_READY` while the brand is still extracting; `502 EMAIL_GENERATION_FAILED` when the agent could not produce a design; `409 EMAIL_RESULT_UNAVAILABLE` when the design was saved but its completed result could not be returned (read the saved `emailVersionId` from `error.details`; do not repeat generation); `402 INSUFFICIENT_CREDITS` on an empty balance. **See also** `editEmail`, `importEmail`, `createSend`. # Get an email design Source: https://docs.brew.new/api-reference/public-v1/emails/get-an-email-design /api-reference/openapi-public-v1.yaml get /v1/emails/{emailId} Reads one design as the bare `EmailDetail` row: `emailId`, the `emailVersionId` (the pin for `POST /v1/sends` and sendEmail nodes), `title`, `status`, `previewStatus`, `subjectLine`, `previewText`, `lang`, `previewImage`, `updatedAt`, `group` and `createdBy` / `createdByUserId` (the design’s creator, shared by every version), plus `errorMessage` when a generation failed. **Use when** inspecting a design before sending it, pinning a version, polling a generation you started, or pulling rendered HTML or version history. **Input** `emailId` in the path. By default the row is the current head; `emailVersionId` reads a saved version and `runId` (returned by a create or edit) reads the version that run produced; pass one or neither, never both. `include=html` adds the selected version’s rendered HTML once it is `ready`, `include=versions` the lean `{ version, emailVersionId }` history, `include=text` the visible body text a reader sees (merge tags kept; `textTruncated` past 20,000 characters), and `include=links` each link destination once with its first visible text and `count` (`linksTruncated` past 200); comma-separate any of them. **Returns** `200` with the row; the `include` fields are present only when requested. A run that never saved a version reads as `failed` with the reason, and the design keeps its last saved version. **Errors** `404 EMAIL_NOT_FOUND` for an unknown or cross-brand id; `404 EMAIL_VERSION_NOT_FOUND` for a version or run this design does not have; `409 EMAIL_RUN_AMBIGUOUS` when a legacy run matches more than one version (read it by `emailVersionId`); `503 SERVICE_UNAVAILABLE` when storage is briefly unreachable (retry the same read); `400 INVALID_REQUEST` for an unknown `include` token or both selectors. **See also** `listEmails`, `editEmail`, `createSend`, `restoreEmailVersion`. # Get an email group Source: https://docs.brew.new/api-reference/public-v1/emails/get-an-email-group /api-reference/openapi-public-v1.yaml get /v1/email-groups/{groupId} Reads one email folder as the bare `EmailGroupSummary` (`groupId`, `groupName`, `emailCount`, plus `createdByUserId` when a person created it, and `createdBy` when they can be named). **Use when** confirming a group before filing designs under it, or reading the `ungrouped` catalog row. **Input** `groupId` in the path: a `grp_*` id or the literal `ungrouped`. **Returns** `200` with the row. **Errors** `404 EMAIL_GROUP_NOT_FOUND` for an unknown or cross-brand id; `400 INVALID_REQUEST` for a non-public Ungrouped sentinel. **See also** `listEmailGroups`, `updateEmailGroup`, `deleteEmailGroup`. # Get inbox placement test results Source: https://docs.brew.new/api-reference/public-v1/emails/get-inbox-placement-test-results /api-reference/openapi-public-v1.yaml get /v1/emails/{emailId}/inbox-placement-tests/{testId} Reads one inbox-placement (seed) test as the bare test resource. Free. **Use when** polling a test started with `createInboxPlacementTest`. **Input** `emailId` and `testId` in the path. While `status` is `running` (`phase` `sending`, then `collecting`) the read refreshes from the provider (re-poll about every 30 seconds until `status` is `completed`, `partially_completed` or `failed`). **Returns** `200` with, per provider, inbox, spam and missing tallies with folder or tab `categories` and actual `folders` (Gmail Promotions, Yahoo bulk, gmx spamverdacht), each provider's own SPF, DKIM and DMARC verdicts (`byProvider[].authentication`), Microsoft filter telemetry (`microsoftFilter`; an SCL of 5 or higher lands in Junk), `spoofingDetected`, `headers` (one-click unsubscribe, plain-text part), a `spamFilter` content verdict with the triggered rules, and `diagnosis[]` per-provider findings with concrete remediation. **Errors** `404 EMAIL_NOT_FOUND` when the design, or the test under it, is not in the brand. **See also** `listInboxPlacementTests`, `createInboxPlacementTest`, `getDomainHealth`. # Import a Figma frame Source: https://docs.brew.new/api-reference/public-v1/emails/import-a-figma-frame /api-reference/openapi-public-v1.yaml post /v1/emails/figma Deterministically converts one selected Figma frame into a new editable Brew email design. No model runs and no credits are charged. `figmaUrl` must be a Figma frame link containing `node-id`. The API-key brand must already have Figma connected in Brew Integrations, and that connected account must be able to read the file. Set `format` to `jsx` (default) for React Email JSX or `html` for rendered email HTML. The requested representation is returned in `content`; the persisted design is identified by `emailId` and `emailVersionId`. Optional `groupId` (`grp_…` or `ungrouped`) or `groupName` (resolve-or-create) — not both; omit to land Ungrouped. Unknown `groupId` → `404 EMAIL_GROUP_NOT_FOUND`. # Import an email Source: https://docs.brew.new/api-reference/public-v1/emails/import-an-email /api-reference/openapi-public-v1.yaml post /v1/emails/import Converts existing markup into a new, fully editable Brew design. Source structure is preserved and every discoverable safe public resource is rehosted; when rehosting fails a validated public URL is kept with a warning, and private, malformed and blocked references are stripped. Free: a deterministic compiler with no model and no credits. **Use when** you already have HTML, MJML, React Email JSX or a saved `.eml` message. To author from a brief use `generateEmail`; for a Figma frame use `importFigmaDesign`. **Input** `content` (the raw source as a string) and `format`: `html` (a document or fragment), `mjml`, `jsx` (a module with a default-exported component or a bare `` element; static values, `PreviewProps` and local sub-components fold; `new Date()` and `Date.now()` with no arguments read the clock once at import and are saved as fixed text with a `current_time_frozen` warning, and `process.env.X` reads as `undefined`; anything else executable is rejected with the offending line) or `eml` (the HTML body is imported, inline `cid:` images are rehosted, other attachments are dropped, and the Subject becomes the title). HTML, MJML and EML land as source-preserved designs with an editable projection; JSX lands as a native React Email design. Optional `baseUrl` resolves relative image paths; optional `title` and `subjectLine` (the design-default inbox subject; an EML Subject is the default); optional `groupId` (`grp_…` or `ungrouped`) or `groupName` (resolve or create), not both; omit to land Ungrouped. Limits: 5,000,000 UTF-8 bytes, 256 remote resources, 8 concurrent fetches, 10 MB per resource, 50 MB aggregate downloads, 128 distinct inline SVG images and 8 seconds of inline SVG rendering (past either, the rest are dropped with a warning). **Returns** `201 { emailId, emailVersionId, html, previewImage?, assetReport, group, subjectLine? }`. Each source element with content that a design could not keep is listed once in `assetReport.warnings` as `{ code: "element_dropped", location: "markup", host: "" }`: inline `svg`, `math` and `canvas`, and `button`, `select`, `textarea` or table `caption` holding text are left out of the editable projection (the original source keeps them); `audio`, `video`, `iframe`, `object` and `embed` are removed from both, with `audio`/`video` fallback content kept. Email clients block SVG images, so an SVG image, hosted or inline (`data:image/svg+xml` in a `src` or `background` attribute or a CSS `url()`), becomes a hosted PNG: twice the pixel box its `` sets (the SVG fitted as its `preserveAspectRatio` says), otherwise its own size so the layout holds. An inline one that will not render is removed (in JSX, its `src`) and listed as `element_dropped` with host `svg`; a hosted one that will not render, or whose URL has a `#` fragment, stays an SVG. Source words the editable design does not carry are named once as `{ code: "text_dropped", location: "markup", host: "" }`; version 1 keeps the exact source. JSX clock reads are named as `{ code: "current_time_frozen", location: "module", host: "Date.now() (line 10)" }` (the first 20). **Errors** `400 INVALID_REQUEST` (naming the field in `param`) when `title`, `subjectLine` or `content` holds an unpaired surrogate (half of an emoji); `422 EMAIL_IMPORT_FAILED` when the markup cannot be compiled into a design or its editable model is over the size budget, with nothing persisted; `502 EMAIL_IMPORT_PERSISTENCE_FAILED` when the markup converted but the design could not be stored (nothing was created; the message carries the request id to give support); `404 EMAIL_GROUP_NOT_FOUND` for an unknown `groupId`; `413 PAYLOAD_TOO_LARGE` over the byte cap; `422 BRAND_NOT_READY` while the brand is still extracting. **See also** `generateEmail`, `importFigmaDesign`, `auditEmail`. # List email comments Source: https://docs.brew.new/api-reference/public-v1/emails/list-email-comments /api-reference/openapi-public-v1.yaml get /v1/emails/{emailId}/comments Lists one design's open comment threads, newest activity first, under `{ data, pagination }`, as the canvas pins show them: `commentId`, `target` (whole email or one element), the 12 most recent `participants` with `participantCount`, `messageCount`, the latest message preview and a link to the thread. People are `{ userId, name }`; resolving deletes a thread. Free. **Use when** reading what teammates asked for on a design before editing it. **Input** `emailId` in the path; `limit` and `cursor`. `include=messages` adds each thread's newest messages (author, body, mentions), oldest first, and caps the page at 3 threads sharing a fixed size budget. A thread with older messages returns `messagesCursor`: send it back with that thread's `commentId` to read the next older slice (the whole budget, at least one message), until it comes back null. `commentId` alone reads one thread. **Returns** `200` with a page of `EmailCommentThread` rows. A design with no threads is an empty page. **Errors** `400 INVALID_REQUEST` for an unknown query key, an unknown `include` token, a malformed cursor, a `messagesCursor` without its `commentId` or from another thread, or `cursor` with `commentId`. `404 EMAIL_NOT_FOUND` for an `emailId` the brand does not have: unknown, malformed or another brand’s design, one identical error as `getEmail` answers. `404 COMMENT_NOT_FOUND` for a `commentId` that is not an open thread on that design (resolving deletes a thread, so a resolved one is the same case). **See also** `getEmail`. # List email designs Source: https://docs.brew.new/api-reference/public-v1/emails/list-email-designs /api-reference/openapi-public-v1.yaml get /v1/emails Lists the brand’s designs, newest first on the `sortBy` timestamp, as `{ data, pagination }`. Each row carries `emailId`, the latest `emailVersionId`, `title`, `status`, `previewImage` (when captured), `updatedAt`, `group` (`{ groupId, groupName }` or `null` when Ungrouped) and its creator. **Use when** browsing designs or finding the `emailId` to send, edit or inspect. One design with its HTML or version history is `getEmail`. **Input** `status` (`generating`, `ready`, `failed`), `groupId` (`grp_…` or `ungrouped`), `sortBy` (`updatedAt` default, or `createdAt`) with an inclusive `from`/`to` ISO 8601 window on that timestamp, `limit` and `cursor`. **Returns** `200` with a page of `EmailSummary` rows and a `pagination` envelope (`cursor` is `null` on the last page). `createdBy` is the creator exactly as the Brew emails list shows it: a person’s name (`Former member` once they leave the brand), `API` or `MCP` for a credential with no person, or the two joined (`Name · MCP`); `createdByUserId` is that person’s stable user id. `createdBy` is absent when the creator cannot be named, with `createdByUserId` still present. **Errors** `400 INVALID_REQUEST` for an unknown query key, an invalid status or a reversed window. **See also** `getEmail`, `listEmailGroups`, `listTemplates` (the public gallery). # List email groups Source: https://docs.brew.new/api-reference/public-v1/emails/list-email-groups /api-reference/openapi-public-v1.yaml get /v1/email-groups Lists the brand’s email folders under `{ data, pagination }`. Named groups use `grp_*` ids; Ungrouped is always included as `{ groupId: "ungrouped", groupName: "Ungrouped" }`. `emailCount` is capped at 100. A named group a person created carries `createdByUserId` and, when they can be named, `createdBy` (their name or "Former member"); older and org-key groups have neither. **Use when** picking the `groupId` to file a design under or to filter `listEmails` by. **Input** `limit` and `cursor`. **Returns** `200` with a page of `EmailGroupSummary` rows. **Errors** `400 INVALID_REQUEST` for an unknown query key. **See also** `getEmailGroup`, `createEmailGroup`, `listEmails` (`?groupId=`). # List inbox placement tests Source: https://docs.brew.new/api-reference/public-v1/emails/list-inbox-placement-tests /api-reference/openapi-public-v1.yaml get /v1/emails/{emailId}/inbox-placement-tests Lists a design's recent inbox-placement (seed) tests, newest first, under `{ data, pagination }` as lean persisted snapshots: `testId`, `status`, subject and preview, `seedCount` and the `overall` placement bucket. Free; no provider poll. **Use when** comparing subject, preview and version variants side by side, or finding the `testId` to poll. **Input** `emailId` in the path; `limit` and `cursor`. **Returns** `200` with a page of lean test rows. **Errors** `400 INVALID_REQUEST` for an unknown query key. **See also** `getInboxPlacementTest`, `createInboxPlacementTest`. # Pause a gradual send Source: https://docs.brew.new/api-reference/public-v1/emails/pause-a-gradual-send /api-reference/openapi-public-v1.yaml post /v1/sends/{sendId}/pause Manually pauses an in-flight GRADUAL (domain-warmup) send. The ramp stops before its next chunk and holds its current batch until `POST /v1/sends/{sendId}/resume` (or a cancel). A send its operator already paused returns the same 200 and changes nothing; any other send that is not a `running` gradual send (including one held at the plan limit or for its domain) returns `409 SEND_NOT_PAUSABLE`. Brand-scoped: an unknown / cross-brand `sendId` is `404`. # Preview across clients & devices Source: https://docs.brew.new/api-reference/public-v1/emails/preview-across-clients-&-devices /api-reference/openapi-public-v1.yaml post /v1/emails/{emailId}/client-previews Starts a durable rendering job for the selected email version across real email clients, including Gmail, Outlook, Apple Mail, iOS, and dark-mode variants. Omit emailVersionId to pin the current version at admission. Pass supported client IDs or send {} for the default spread. Returns previewId and per-client progress immediately. Read GET /v1/emails/client-previews/{previewId} to resume; polling never creates another provider test. Reserves 10 credits at admission and settles once when useful output exists. If the job produces no usable image, the reservation is released. Failed clients include individual reasons and retryability; a partial result retains all successful full-size links. # Read a saved email audit Source: https://docs.brew.new/api-reference/public-v1/emails/read-a-saved-email-audit /api-reference/openapi-public-v1.yaml get /v1/emails/audits/{auditId} Returns a bounded page of the normalized audit findings, including finding IDs, rule IDs, targets, remediation, and the audited content hash. Reading pages is free and never reruns the audit. Continue using pagination.cursor. Reports are retained for seven days; the report’s expiresAt is the separate audit-attestation expiry. Completion and coverage fields identify incomplete analysis or representative-only findings. # Read email rendering progress Source: https://docs.brew.new/api-reference/public-v1/emails/read-email-rendering-progress /api-reference/openapi-public-v1.yaml get /v1/emails/client-previews/{previewId} Reads the existing rendering job and per-client results without submitting another provider test or charging again. Returns successful full-size image links, pending or failed clients with reasons and retryability, expiry, and credit reservation status. Poll the same previewId after nextPollAfterMs while the job is `queued` or `running`. # Refresh a canvas session Source: https://docs.brew.new/api-reference/public-v1/emails/refresh-a-canvas-session /api-reference/openapi-public-v1.yaml post /v1/canvas/sessions/{sessionId}/refresh Issue a new bootstrap credential without changing the target or external user. Requires the original issuing authority. Response replay is disabled. # Restore a historical version Source: https://docs.brew.new/api-reference/public-v1/emails/restore-a-historical-version /api-reference/openapi-public-v1.yaml post /v1/emails/{emailId}/restore Non-destructive restore: clones the numbered version into a NEW `latest` row (demoting the current head) and returns the same generated-email shape as an edit, including the fresh `emailVersionId`. Like a prompt edit, it moves every automation `sendEmail` step pinned to the previous latest version onto the new one, in a new unpublished automation version; the published version keeps its pin until the next publish, and steps pinned to an older version do not move. To keep a step on a design that will change, clone the email and pin the clone, and leave the clone unedited: a prompt edit or restore of the clone moves the step the same way, and a manual canvas edit changes the content of the pinned version in place, published automations included. # Resume a paused send Source: https://docs.brew.new/api-reference/public-v1/emails/resume-a-paused-send /api-reference/openapi-public-v1.yaml post /v1/sends/{sendId}/resume Resumes a manually paused GRADUAL send, or any campaign paused for its bounce or complaint rate (`pauseReason: bounce_rate`; such a send is never paused for it again). The send picks the resume up at its next hold check (seconds after a short pause, up to an hour after a long one); a ramp re-spreads its unsent tail and shifts later batches so missed intervals do not compress into a burst. A send held at the plan limit resumes on its own once the plan allowance is available; any other send returns `409 SEND_NOT_RESUMABLE`. Brand-scoped: an unknown / cross-brand `sendId` is `404`. # Revoke a canvas session Source: https://docs.brew.new/api-reference/public-v1/emails/revoke-a-canvas-session /api-reference/openapi-public-v1.yaml delete /v1/canvas/sessions/{sessionId} Stop reads and writes through an existing session, including active subscriptions. # Run an inbox placement test Source: https://docs.brew.new/api-reference/public-v1/emails/run-an-inbox-placement-test /api-reference/openapi-public-v1.yaml post /v1/emails/{emailId}/inbox-placement-tests Test where the design’s latest version LANDS — inbox vs spam vs missing — across real mailbox providers (Gmail, Outlook, Yahoo, Apple, …). Brew provisions a Mailgun seed list and sends the email to the seed addresses through your REAL send pipeline on a VERIFIED sending `domainId`, so the result reflects that domain’s true deliverability plus SPF/DKIM/DMARC. Returns immediately with a `testId`, `status: "running"` and `phase: "sending"`. Results accrue over a few minutes — poll `GET /v1/emails/{emailId}/inbox-placement-tests/{testId}` until `status` is `completed`, `partially_completed` or `failed`. This performs a real (small) send to the seeds IN ADDITION to the FIXED 10-credit test fee (`X-Credit-Cost: 10`), charged only on a 2xx. Requires a verified sending domain. # Send an email Source: https://docs.brew.new/api-reference/public-v1/emails/send-an-email /api-reference/openapi-public-v1.yaml post /v1/sends Sends an email design. Polymorphic on `test`: a campaign send mints a new `Send` (the unit of delivery and analytics) and delivers to a saved audience or an inline list through a verified domain; `test: true` delivers one synchronous QA copy to a single address and writes no send row. **Use when** a design is ready to go out. For per-recipient event-driven delivery, publish an automation and fire its trigger (`fireTrigger`). **Input** Campaign (`test` omitted or `false`): `emailId` (optionally pinned to `emailVersionId`), a verified `domainId`, `subject`, and exactly one of `audienceId` (a saved audience, or `"all"` for every contact in the brand) or `to` (one address or an array of up to 50). Optional `from` (`{ email, name? }`, an address on the send domain), `previewText`, `replyTo`, `scheduledAt`, one delivery mode (`gradualSend`, or `smartSend: true` for Intelligent Send: each recipient with past opens or clicks gets it at the upcoming hour, within 24 hours, their own history makes them most likely to open, and the rest right away; it composes with `scheduledAt`), and `consent` provenance (`source`, optional `capturedAt`, `policyVersion`, `evidence`) for inline recipients that are not yet contacts: each is created as a subscribed contact carrying that record. An existing opt-out is never re-subscribed. Inline recipients face the same unsubscribe and suppression gate and per-recipient quota as audience sends. Test (`test: true`): `emailId`, `subject`, one `to` address, optional `emailVersionId`, `previewText`, `replyTo`, `domainId` (a verified org-owned domain; otherwise the Brew default sender, and an unverified or foreign domain is rejected, never downgraded), `from` (`{ email, name? }`, an address on that domain), `variables` (example values for `{{ var | fallback }}` merge tags; a value wins over the fallback) and `payload` (template data; nested JSON renders via Liquid as `trigger.*`); the subject carries a `[TEST]` prefix. A test reaches only a teammate with access to the brand, an address on a verified sending domain of the brand, or, for a signed-in person (not an API key), their own address or one on their company domain; anyone else is `422 TEST_RECIPIENT_NOT_ALLOWED` (`details.recipients`). The same design can be sent unlimited times; every campaign call mints a new send. **Returns** campaign `202 { status: 'queued' | 'scheduled', sendId, scheduledAt?, warnings? }` (poll `getSend`; `warnings[]` carries one `CONSENT_RECORD_MISSING` per inline recipient that is a subscribed contact with no consent record, and one `RECIPIENTS_EXCLUDED` with the counts when unsubscribed, suppressed, undeliverable or permission-less recipients will be skipped); test `200 { status: 'completed', recipient }`. **Errors** `400 INVALID_REQUEST` (`param: subject`) when `subject` has a line break or runs over 1000 characters (993 on a test send, for the `[TEST]` prefix), judged on the text every recipient receives; `404 EMAIL_NOT_FOUND`, `DOMAIN_NOT_FOUND`, `AUDIENCE_NOT_FOUND` (a resource in another brand also surfaces as `404`); `422 EMAIL_NOT_READY`, `DOMAIN_NOT_READY`, `DOMAIN_PURPOSE_NOT_ALLOWED`, `LIQUID_RENDER_ERROR`, `TEST_RECIPIENT_NOT_ALLOWED`; `422 CONSENT_REQUIRED` when an inline marketing recipient has no contact record with marketing consent and no `consent` was supplied (`details.recipients`); `422 RECIPIENT_UNSUBSCRIBED` when an inline recipient is an existing contact who opted out (`details.recipients`, never re-subscribed); `422 NO_ELIGIBLE_RECIPIENTS` when an immediate send would reach nobody because every contact it targets is excluded (`details.eligibility` = `{ total, eligible, excluded: { unsubscribed, suppressed, invalidEmail, consentRequired? } }`, each address counted once; no send is created, while a scheduled send is accepted instead); `422 EMAIL_IMAGES_MISSING` when the email shows a cdn.brew.new image that does not exist (`details.missingImages[]`; a dead icon whose real file sits elsewhere in its pack is moved there instead when the key has `emails` access); `402 SEND_QUOTA_EXCEEDED` when the plan's monthly volume would be exceeded (no `Retry-After`). **See also** `listSends`, `cancelSend`, `fireTrigger`. # Update an email group Source: https://docs.brew.new/api-reference/public-v1/emails/update-an-email-group /api-reference/openapi-public-v1.yaml patch /v1/email-groups/{groupId} Renames a named folder (`name`), moves existing designs into it (`emailIds`, up to 50, one request against the rate limit), or both, in one transaction. A move adds `moved` and `notMoved` (`not_found`, `generating`, `not_movable`, `folder_full` or `retry`; resend `retry` ids) to the response. Ungrouped is not a target (`400`). Unknown / cross-brand ids are `404`. Duplicate names are `409 EMAIL_GROUP_NAME_CONFLICT`. # Liveness probe Source: https://docs.brew.new/api-reference/public-v1/health/liveness-probe /api-reference/openapi-public-v1.yaml get /v1/health No auth, no rate limit — a public liveness surface a dependent service (e.g. the Brew MCP server) can poll. Returns `{ status: "ok", version }`. # Get an insight Source: https://docs.brew.new/api-reference/public-v1/insights/get-an-insight /api-reference/openapi-public-v1.yaml get /v1/insights/{insightId} One finding in full, as its page in Brew reads it: the list row’s fields plus `rationale`, `closedReason`, `closedAt`, `lastActedAt`, `churnCount`, the frozen `metrics`, `evidence` links, its `subject`, the detector’s `method` (what it measures, how, against what, and what resolves it), `generatedBy` (the engine run that produced it and what that run could not see) and `freshness`. **Use when** explaining why a finding exists or what would resolve it. `metrics` were frozen when the finding was computed and are the only numbers to quote about it. **Input** `insightId` in the path, as a `listInsights` row carries it. **Returns** `200` with the finding. Read-only and free. **Errors** `404 INSIGHT_NOT_FOUND` for an unknown, malformed or over-long id OR a finding of another brand: one identical error, so the cases are indistinguishable. **See also** `listInsights`. # List insights Source: https://docs.brew.new/api-reference/public-v1/insights/list-insights /api-reference/openapi-public-v1.yaml get /v1/insights The brand’s Brew Insights as the Insights page ranks them, most severe first and then by score, under `{ data, pagination, freshness }`. Each row is one deterministic finding of the insight engine; the engine keeps at most 200 findings in view. **Use when** reporting what Brew found about the brand’s email: deliverability problems, campaigns that under- or over-performed, timing, audience and automation opportunities. **Input** `state` (`open`, the default: active findings and snoozes that have ended; or `all`, which adds resolved, cleared, dismissed and stale findings), `severity` to read one severity (up to 200 of its own, however many more severe findings exist), `limit`/`cursor` to page. A `cursor` belongs to the walk that returned it: it continues only the same `state` and `severity`, and only while the findings it already returned are still the rows before it. A finding added, removed or moved further down is served when its page comes, so a walk returns each finding of the list as it stands at its last page exactly once. `include` adds the intelligence layer the page shows beside the findings: `pulse` (the last 7 days against the 7 before), `report` (the latest report the analysis agent published), `suggestions` (its proposed and launched suggestions, up to 25) and `memo` (the agent’s memory across runs). **Returns** `200`. Each row carries `insightId`, `title`, `description` (the detector’s headline), `severity`, `confidence`, `kind`, `category`, `detectorId`, `state`, `firstSeenAt`, `lastSeenAt`, `recurrenceCount`, an optional `action` and the finding’s `url` in Brew. `freshness` is on every page: `dataAsOf` is how current the data behind the findings is, and `latestAttempt.status: failed` means they may be stale. An expansion that does not exist yet answers `null`. Read-only and free. **Errors** `400 INVALID_REQUEST` for an unknown query key, value or `include` token, or a malformed `cursor`. Also `400 INVALID_REQUEST` with `param: cursor` when the findings changed since the cursor was issued (one it already returned left the list or moved, or a new finding ranks among them; the engine re-ran, or a finding was snoozed, dismissed or changed state): read again from the first page, without `cursor`. A cursor issued for another `state` or `severity` is refused the same way. **See also** `getInsight`, `getAnalyticsOverview`. # List integrations Source: https://docs.brew.new/api-reference/public-v1/integrations/list-integrations /api-reference/openapi-public-v1.yaml get /v1/integrations Returns the product integration catalog for the brand in scope under `{ data, pagination }`, with a `connected` flag per provider. Canonical providers also expose active, ready installation counts and readiness per capability. Connecting is a human Settings hop at `/integrations/{provider}`; never paste a connect URL into model output. Brand-scoped (`X-Brand-Id` on an org credential). No permission scope. # Machine-readable API catalog Source: https://docs.brew.new/api-reference/public-v1/meta/machine-readable-api-catalog /api-reference/openapi-public-v1.yaml get /v1/help No auth, no rate limit — a structured-JSON catalog an MCP server (or any agent) can parse to self-discover how to use Brew: auth, permission scopes, rate limits, flat credit costs, the error envelope, and the full endpoint list (derived from this same OpenAPI document, so it never drifts). Returns a generic JSON object; read the live response for the concrete shape. # List notifications Source: https://docs.brew.new/api-reference/public-v1/notifications/list-notifications /api-reference/openapi-public-v1.yaml get /v1/notifications Lists the brand's notifications, newest first, under `{ data, pagination }`, as the app's bell shows them: generations, sends, imports, domain checks and score runs finishing or failing, plus comment mentions and replies. Each row has `type`, `status`, `title`, `subtitle`, a `url` into the app and the ids it concerns (`chatId`, `emailId`, `domainId`). Reading marks nothing read. Free. **Access** each row is shown only when the credential may read its feature, scopes included, so an empty page can mean nothing happened or that this credential cannot see that kind of row (a `type` it cannot see is an empty page, not an error). By type: - `chat_stream`, `preview_email`: the `emails` scope. - `email_sent`, `email_scheduled`, `email_send_failed`, `gradual_send_paused`, `gradual_send_completed`, `send_review_rejected`: `sends` (`emails` implies it). - `domain_status`, `domain_score_run`: `domains` (`emails` implies it). - `import_job`, `validation_job`: `contacts`. - `automation_pause_window_closed`: `automations`. - `brand_extracted`, `brand_image_import`, `integration_attention` (a connected integration such as Stripe needs a reconnect, moved to another brand, or lost a permission): every credential on the brand. - `api_key_created`: the `all` scope (a signed-in member, or a key or connection holding `all`). - `send_limit_reached`, `trial_ending`, `trial_expired`, `payment_failed`: organization admins only (a signed-in admin, an admin’s organization-wide connection, or an organization-wide key holding `all`); never a brand key. - `comment_mention`, `comment_reply` (`isPersonal: true`): only the person addressed, signed in or on a personal connection; never an API key. **Use when** checking what finished or failed since you last looked. **Input** `type` keeps one notification type; `limit` and `cursor` (an opaque native cursor; a page can hold fewer rows than `limit` while `hasMore` is true). **Returns** `200` with a page of `Notification` rows; `notificationId` (`ntf_…`) is stable for the row’s life. **Errors** `400 INVALID_REQUEST` for an unknown query key or `type`, or a malformed cursor. **See also** `getChatContext`, `getEmail`, `getDomainHealth`. # Get a send Source: https://docs.brew.new/api-reference/public-v1/sends/get-a-send /api-reference/openapi-public-v1.yaml get /v1/sends/{sendId} Reads one send (campaign or automation) as the bare `Send` row: identity and join keys, the sender and subject snapshot, `status`, `approvalState`, delivery accounting, gradual-send progress and lifetime `stats`. **Use when** polling a send accepted by `createSend`, or inspecting one automation delivery. **Input** `sendId` in the path; `include=events` attaches a bounded first page of the send’s analytics events (recipient, type, click URL). **Returns** `200` with the row; `events` is present only when requested. **Errors** `404 SEND_NOT_FOUND` for an unknown or cross-brand id; `400 INVALID_REQUEST` for an unknown `include` token. **See also** `listSends`, `cancelSend`, `pauseSend`, `resumeSend`, `getEventsAnalytics` (`?sendId=`). # List sends Source: https://docs.brew.new/api-reference/public-v1/sends/list-sends /api-reference/openapi-public-v1.yaml get /v1/sends Lists sends, newest first, under `{ data, pagination }`. A send is the unit of delivery and analytics: one design delivered to a target through one domain. Rows carry the sender and subject snapshot, `status`, delivery accounting and, once delivered, lifetime `stats`. **Use when** auditing what a design was sent to, reading campaign performance, or joining an automation run to its deliveries (`listAutomationRuns`, then `?automationRunId=` here, then `getEventsAnalytics` with the same id). **Input** the default list is campaign sends: `emailId` narrows to one design; `status`, `messageClass` (`marketing` or `transactional`) and an inclusive `from`/`to` window on `updatedAt` filter it. A join filter (`automationId`, `automationRunId`, `audienceRunId` or `triggerInstanceId`) switches to the automation grain, one row per recipient; `kind=automation` is implied and per-recipient rows are never listed brand-wide. `limit` and `cursor` page (an opaque native cursor; a `triggerInstanceId` read merges the runs of one fire into a single bounded page). `status`, `messageClass` and `from`/`to` are applied while the sends are read, so a filtered page fills to `limit`. Each page scans a bounded number of sends, so when matches are rare a page can still hold fewer rows than `limit`, even none, while `hasMore` is true: keep paging until `hasMore` is false. A cursor works only with the filters it was issued under. **Returns** `200` with a page of `Send` rows. **Errors** `404 AUTOMATION_RUN_NOT_FOUND` or `AUDIENCE_RUN_NOT_FOUND` when a join filter names a run outside the brand; `400 INVALID_REQUEST` for `kind=campaign` with a join filter, `emailId` with a join filter, `kind=automation` without one, or a malformed cursor or one issued under other filters. **See also** `getSend` (`?include=events`), `createSend`, `getEventsAnalytics`, `getAnalyticsOverview`. # Get a flow Source: https://docs.brew.new/api-reference/public-v1/templates/get-a-flow /api-reference/openapi-public-v1.yaml get /v1/flows/{slug} One public flow as the bare row, with `anchor` (what day 0 means) and every step’s `subject`, `previewText`, `dayOffset`, `delayDays`, `category`, `previewImage` and `emailId`. Organization-wide. **Use when** reading a sequence in full before remixing it, or fetching each step’s rendered body. **Input** `slug` in the path: the brand domain from a `listFlows` card (case-insensitive). `include=html` adds each step’s rendered HTML, best-effort per step: a step whose body is no longer servable comes back without `html` rather than failing the flow. **Returns** `200` with the flow. A step’s `emailId` is a template reference: pass it as `referenceEmailId` on `POST /v1/emails`; for the body itself use `include=html` here (`GET /v1/templates` lists the gallery and takes no id). **Errors** `404 FLOW_NOT_FOUND` when the flow is unknown, private, or a step’s template was taken down (the anonymous read fails closed as a whole). **See also** `listFlows`, `generateEmail`. # Get a public template Source: https://docs.brew.new/api-reference/public-v1/templates/get-a-public-template /api-reference/openapi-public-v1.yaml get /v1/templates/{templateId} Returns metadata, preview and canonical links, and referenceEmailId for one public template. Add include=html to inspect its rendered content. Large HTML is returned as a downloadable content.url instead of truncated JSON. # List flows Source: https://docs.brew.new/api-reference/public-v1/templates/list-flows /api-reference/openapi-public-v1.yaml get /v1/flows Lists public email flows, one brand’s real onboarding or newsletter sequence with the day each email landed, as cards under `{ data, pagination, total }`. Organization-wide: the same bounded corpus the gallery shows (a few hundred flows), paged with `limit`/`cursor`. **Use when** studying how real brands sequence email to plan or remix an automation, or finding the `slug` to read one flow in full. **Input** `brand` (exact domain), `category`, `type` (`signup` | `newsletter`), `sort` (`newest` | `emails` | `span` | `remixes`), or `semantic` for relevance-ranked search (then `sort` is ignored). **Returns** `200` with flow cards and `total`, the number of flows the query matches across every page (filters narrow it; `semantic` only orders it), so one `limit=1` call counts them. `isTotalExact` is false when the read was cut at 500 flows (the newest, or the 500 nearest a `semantic` query; filters apply after it), and `total` is then a floor. A card never carries `anchor` or `steps`; every card carries the `slug` that `getFlow` takes. A flow holds at most 12 steps: capture keeps the first 12 and cuts the tail, so `emailCount: 12` means twelve **or more** were sent. **Errors** `400 INVALID_REQUEST` for an unknown query key or value; `503 SERVICE_UNAVAILABLE` when `semantic` search cannot run (no index, or its kill switch); retry without `semantic`. **See also** `getFlow`, `listTemplates`. # List templates Source: https://docs.brew.new/api-reference/public-v1/templates/list-templates /api-reference/openapi-public-v1.yaml get /v1/templates Lists public templates under { data, pagination }. The default full representation includes HTML. Set representation=summary for metadata, previewImage, viewUrl, and referenceEmailId without HTML. Supports exact brand and category filters and a group filter (a browse group: every category in it); query matches title text or an exact template identifier. semantic ranks up to 200 matches using vector search; query additionally filters those matches when both are supplied. Browse defaults to 50 full rows or 20 summary rows. Brand and category match case-insensitively. Continue with pagination.cursor, including after an empty filtered page with hasMore=true. Templates are organization-wide references; pass referenceEmailId to POST /v1/emails to remix one. Set count=true for { count }, the number of templates matching brand, category and group (refreshed every 15 minutes), instead of rows; add groupBy=brand, groupBy=category or groupBy=group for per-value counts, largest first, 100 groups a page with the same pagination.cursor (count does not combine with semantic or query). # Get usage Source: https://docs.brew.new/api-reference/public-v1/usage/get-usage /api-reference/openapi-public-v1.yaml get /v1/usage Returns the org usage snapshot: current plan, AI credit balance (limit/used/remaining — `null` = unlimited), monthly email-send quota (`remaining` = `limit` − `used` − `reserved`, where `reserved` is held by sends still delivering), and the billing-period window. Check it before a credit-metered call. Billing belongs to the ORGANIZATION, so this needs an organization-scoped credential: a key bound to one brand gets `403 ORG_SCOPE_REQUIRED` no matter which scopes it holds. # Create webhook Source: https://docs.brew.new/api-reference/public-v1/webhooks/create-webhook /api-reference/openapi-public-v1.yaml post /v1/webhooks Create a signed HTTPS notification endpoint for one authorized brand. The initial signing secret is returned once. **Use when** you want to subscribe a receiver to supported email events. Supply an Idempotency-Key for this mutation. **Returns** The created endpoint and its signing secret. **Errors** `ACCOUNT_SUSPENDED`, `API_KEY_REVOKED`, `AUTHENTICATION_REQUIRED`, `BRAND_ID_REQUIRED`, `BRAND_NOT_FOUND`, `BRAND_SCOPE_MISMATCH`, `IDEMPOTENCY_CONFLICT`, `IDEMPOTENCY_IN_PROGRESS`, `INSUFFICIENT_PERMISSIONS`, `INSUFFICIENT_ROLE`, `INTERNAL_ERROR`, `INVALID_API_KEY`, `INVALID_REQUEST`, `NOT_FOUND`, `PAYLOAD_TOO_LARGE`, `RATE_LIMITED`, `SERVICE_UNAVAILABLE`. # Delete webhook Source: https://docs.brew.new/api-reference/public-v1/webhooks/delete-webhook /api-reference/openapi-public-v1.yaml delete /v1/webhooks/{webhookId} Delete an endpoint within the authorized brand and stop its pending deliveries. **Use when** you want to permanently remove a receiver. **Returns** The deleted endpoint ID and deletion confirmation. **Errors** `ACCOUNT_SUSPENDED`, `API_KEY_REVOKED`, `AUTHENTICATION_REQUIRED`, `BRAND_ID_REQUIRED`, `BRAND_NOT_FOUND`, `BRAND_SCOPE_MISMATCH`, `INSUFFICIENT_PERMISSIONS`, `INSUFFICIENT_ROLE`, `INTERNAL_ERROR`, `INVALID_API_KEY`, `INVALID_REQUEST`, `NOT_FOUND`, `RATE_LIMITED`, `SERVICE_UNAVAILABLE`. # Get webhook Source: https://docs.brew.new/api-reference/public-v1/webhooks/get-webhook /api-reference/openapi-public-v1.yaml get /v1/webhooks/{webhookId} Read one notification endpoint within the authorized brand. Signing secrets are excluded. **Use when** you know an endpoint ID and need its current configuration. **Returns** The endpoint URL, subscriptions, status and metadata. **Errors** `ACCOUNT_SUSPENDED`, `API_KEY_REVOKED`, `AUTHENTICATION_REQUIRED`, `BRAND_ID_REQUIRED`, `BRAND_NOT_FOUND`, `BRAND_SCOPE_MISMATCH`, `INSUFFICIENT_PERMISSIONS`, `INSUFFICIENT_ROLE`, `INTERNAL_ERROR`, `INVALID_API_KEY`, `INVALID_REQUEST`, `NOT_FOUND`, `RATE_LIMITED`, `SERVICE_UNAVAILABLE`. # List webhook attempts Source: https://docs.brew.new/api-reference/public-v1/webhooks/list-webhook-attempts /api-reference/openapi-public-v1.yaml get /v1/webhooks/{webhookId}/events/{eventId}/attempts List delivery attempts for one endpoint event, including receiver responses. **Use when** you need to diagnose receiver failures or inspect retry history. **Returns** A page of attempts with status, response, duration and continuation cursor. **Errors** `ACCOUNT_SUSPENDED`, `API_KEY_REVOKED`, `AUTHENTICATION_REQUIRED`, `BRAND_ID_REQUIRED`, `BRAND_NOT_FOUND`, `BRAND_SCOPE_MISMATCH`, `INSUFFICIENT_PERMISSIONS`, `INSUFFICIENT_ROLE`, `INTERNAL_ERROR`, `INVALID_API_KEY`, `INVALID_REQUEST`, `NOT_FOUND`, `RATE_LIMITED`, `SERVICE_UNAVAILABLE`. # List webhook events Source: https://docs.brew.new/api-reference/public-v1/webhooks/list-webhook-events /api-reference/openapi-public-v1.yaml get /v1/webhooks/{webhookId}/events List retained event deliveries to one endpoint within the authorized brand. Expired payloads may be absent. **Use when** you need to inspect delivery status, payloads or the next retry time. **Returns** A page of delivery records and an opaque continuation cursor. **Errors** `ACCOUNT_SUSPENDED`, `API_KEY_REVOKED`, `AUTHENTICATION_REQUIRED`, `BRAND_ID_REQUIRED`, `BRAND_NOT_FOUND`, `BRAND_SCOPE_MISMATCH`, `INSUFFICIENT_PERMISSIONS`, `INSUFFICIENT_ROLE`, `INTERNAL_ERROR`, `INVALID_API_KEY`, `INVALID_REQUEST`, `NOT_FOUND`, `RATE_LIMITED`, `SERVICE_UNAVAILABLE`. # List webhooks Source: https://docs.brew.new/api-reference/public-v1/webhooks/list-webhooks /api-reference/openapi-public-v1.yaml get /v1/webhooks List notification endpoints for the authorized brand. Signing secrets are never included. **Use when** you need to inspect endpoint configuration or paginate endpoints. **Returns** A page of endpoints and an opaque continuation cursor. **Errors** `ACCOUNT_SUSPENDED`, `API_KEY_REVOKED`, `AUTHENTICATION_REQUIRED`, `BRAND_ID_REQUIRED`, `BRAND_NOT_FOUND`, `BRAND_SCOPE_MISMATCH`, `INSUFFICIENT_PERMISSIONS`, `INSUFFICIENT_ROLE`, `INTERNAL_ERROR`, `INVALID_API_KEY`, `INVALID_REQUEST`, `NOT_FOUND`, `RATE_LIMITED`, `SERVICE_UNAVAILABLE`. # Replay webhook event Source: https://docs.brew.new/api-reference/public-v1/webhooks/replay-webhook-event /api-reference/openapi-public-v1.yaml post /v1/webhooks/{webhookId}/events/{eventId}/replay Request another delivery of a retained webhook notification with the same event identity. This never sends another email. **Use when** you have repaired a receiver and need the notification delivered again. Supply an Idempotency-Key. **Returns** An accepted delivery request; inspect delivery history for the result. **Errors** `ACCOUNT_SUSPENDED`, `API_KEY_REVOKED`, `AUTHENTICATION_REQUIRED`, `BRAND_ID_REQUIRED`, `BRAND_NOT_FOUND`, `BRAND_SCOPE_MISMATCH`, `IDEMPOTENCY_CONFLICT`, `IDEMPOTENCY_IN_PROGRESS`, `INSUFFICIENT_PERMISSIONS`, `INSUFFICIENT_ROLE`, `INTERNAL_ERROR`, `INVALID_API_KEY`, `INVALID_REQUEST`, `NOT_FOUND`, `PAYLOAD_TOO_LARGE`, `RATE_LIMITED`, `SERVICE_UNAVAILABLE`. # Rotate webhook secret Source: https://docs.brew.new/api-reference/public-v1/webhooks/rotate-webhook-secret /api-reference/openapi-public-v1.yaml post /v1/webhooks/{webhookId}/rotate-secret Rotate an endpoint signing secret. The provider keeps the previous secret valid during its rotation grace period. **Use when** you are replacing receiver credentials. Supply an Idempotency-Key and update your receiver with the returned secret. **Returns** The new signing secret. **Errors** `ACCOUNT_SUSPENDED`, `API_KEY_REVOKED`, `AUTHENTICATION_REQUIRED`, `BRAND_ID_REQUIRED`, `BRAND_NOT_FOUND`, `BRAND_SCOPE_MISMATCH`, `IDEMPOTENCY_CONFLICT`, `IDEMPOTENCY_IN_PROGRESS`, `INSUFFICIENT_PERMISSIONS`, `INSUFFICIENT_ROLE`, `INTERNAL_ERROR`, `INVALID_API_KEY`, `INVALID_REQUEST`, `NOT_FOUND`, `PAYLOAD_TOO_LARGE`, `RATE_LIMITED`, `SERVICE_UNAVAILABLE`. # Test webhook Source: https://docs.brew.new/api-reference/public-v1/webhooks/test-webhook /api-reference/openapi-public-v1.yaml post /v1/webhooks/{webhookId}/test Queue a signed synthetic email event to one endpoint. The payload is marked as a test and no email is sent. **Use when** you need to verify your receiver and signature handling. Supply an Idempotency-Key. **Returns** An accepted test request; inspect delivery history for the result. **Errors** `ACCOUNT_SUSPENDED`, `API_KEY_REVOKED`, `AUTHENTICATION_REQUIRED`, `BRAND_ID_REQUIRED`, `BRAND_NOT_FOUND`, `BRAND_SCOPE_MISMATCH`, `IDEMPOTENCY_CONFLICT`, `IDEMPOTENCY_IN_PROGRESS`, `INSUFFICIENT_PERMISSIONS`, `INSUFFICIENT_ROLE`, `INTERNAL_ERROR`, `INVALID_API_KEY`, `INVALID_REQUEST`, `NOT_FOUND`, `PAYLOAD_TOO_LARGE`, `RATE_LIMITED`, `SERVICE_UNAVAILABLE`. # Update webhook Source: https://docs.brew.new/api-reference/public-v1/webhooks/update-webhook /api-reference/openapi-public-v1.yaml patch /v1/webhooks/{webhookId} Update an endpoint URL, event subscriptions, description or enabled status within the authorized brand. **Use when** you need to change receiver configuration or pause delivery. **Returns** The updated endpoint without its signing secret. **Errors** `ACCOUNT_SUSPENDED`, `API_KEY_REVOKED`, `AUTHENTICATION_REQUIRED`, `BRAND_ID_REQUIRED`, `BRAND_NOT_FOUND`, `BRAND_SCOPE_MISMATCH`, `INSUFFICIENT_PERMISSIONS`, `INSUFFICIENT_ROLE`, `INTERNAL_ERROR`, `INVALID_API_KEY`, `INVALID_REQUEST`, `NOT_FOUND`, `PAYLOAD_TOO_LARGE`, `RATE_LIMITED`, `SERVICE_UNAVAILABLE`. # Add Contacts Source: https://docs.brew.new/audience/add-contacts Bring opted-in contacts into Brew by CSV upload, manual entry, a connected integration, or the API, with optional validation as they arrive. There are four ways to add contacts to Brew. Use whichever fits your workflow. | Method | Best for | | - | - | | **CSV upload** | One-time imports, migration from another platform, bulk additions | | **Add manually** | A handful of contacts you want to add by hand | | **Sync from integrations** | Continuous sync from Clerk, Stripe, Shopify, or another connected source | | **API** | Programmatic add/update from your backend | Open the Audience tab in the sidebar, then click **Add contacts** in the top right to choose a method. Moving from another platform? The migration guides cover contacts, consent, and suppressions for [Mailchimp](/migrations/mailchimp), [Klaviyo](/migrations/klaviyo), [Postmark](/migrations/postmark), [Brevo](/migrations/brevo), [Customer.io](/migrations/customerio), and [Loops](/migrations/loops). > [!WARNING] > > Every marketing recipient must have opted in to hear from you. Importing or syncing contact data into Brew is not permission to email it. See [What You Can Send](/get-started/what-you-can-send). ## CSV Upload The fastest way to import a lot of contacts at once. Brew handles deduplication and partial updates automatically, and can [validate every address](/audience/validate-contacts) as it's imported if you opt in. **1. Prepare your CSV** Required column: * `Email`, the contact's email address Recommended: * `First Name` * `Last Name` Optional: * `Subscribed`. `true` or `false`. Defaults to `true` if missing. * Any custom property you've created in Brew Dates are safest as `YYYY-MM-DD`. See [date formats](/audience/manage-contacts#custom-properties) for everything Brew reads. **2. Open the import screen** **Audience → Add contacts → CSV Upload**. **3. Upload your CSV** Drag and drop, or click to browse. Wait for it to process. **4. Map columns to Brew properties** For each CSV column, confirm the mapping is right. Unrecognized columns become new custom properties, named in camelCase: a `push source` column becomes `pushSource`, and `Plan` becomes `plan`. Use that name in merge tags and filters ([how names fold](/audience/manage-contacts#property-names)). For a date column, the row shows the order its dates are read in. When every date could be either (`03/04/2026` is 3 April or 4 March), pick the reading that matches your file. A column with a day over 12 anywhere is detected for you. **5. Review and import** Tick **These contacts consent to marketing emails** to confirm they agreed to receive your marketing email. Brew records consent once for the whole file, dated the day you import. To deliverability-check every address as it's ingested, tick the [validation checkbox](/audience/validate-contacts) (2 credits per address). Then click the import button, which shows your count, such as **Import 120 contacts**. Contacts process in the background, so you can navigate away. ### Updating Existing Contacts CSV upload also updates contacts that already exist. > [accordion] Matching > > Brew matches on email address. If the email exists, the row updates the existing contact. If not, a new contact is created. > [accordion] Partial updates > > Empty cells **don't overwrite** existing data. Only cells with values update the corresponding property. > [accordion] Subscription status > > * If the `Subscribed` column is missing, new contacts are subscribed by default and existing contacts keep their status. > * To import unsubscribed contacts, include `Subscribed` with `false` (or a status exported from another email platform, such as `unsubscribed` or `cleaned`). This also unsubscribes contacts that already exist, so the import tells you how many before you confirm. > * The importer **never re-subscribes** contacts who have previously unsubscribed. ### Common Issues > [accordion] Duplicate contacts > > If your CSV has duplicate emails, Brew processes them in order: the last row wins. Deduplicate before uploading to avoid surprises. > [accordion] Invalid email formats > > Emails must be in a valid format (such as `name@domain.com`). Invalid emails are flagged at the review step and skipped. > [accordion] Encoding issues > > Make sure your CSV is UTF-8 encoded. Garbled characters in the column-mapping screen mean the file isn't UTF-8, so re-export it. > [accordion] Dates in the wrong month > > A date like `03/04/2026` can be read day first or month first. Check the order shown on the date column at the mapping step, or convert dates to `YYYY-MM-DD` before uploading. > > When importing over the API, the CLI or MCP (`import_contacts_csv`), pass `dateOrder` (`day_first` or `month_first`). See [date formats](/audience/manage-contacts#custom-properties). > [accordion] Large files > > Very large CSVs can take several minutes. Split huge files into smaller batches if you want easier tracking. ### Import History Past imports appear below the upload area on the CSV Upload page, with the date, count, and any errors. The list includes every import: app uploads, and batches sent over the API, SDK, CLI, MCP, or Brew chat. A batch appears under its `fileName`; the CLI sends the file's name. Unnamed batches appear as **API**, **MCP**, or **Brew chat** imports. Each contact an import writes keeps its `importId` until a later import touches it. Named batches also set `csvFileName`. **View contacts** opens the audience filtered to that import. **Delete import** removes the contacts it created. Contacts it only updated remain. ## Add Manually For a few contacts at a time, go to **Audience → Add contacts → Add manually** and enter the email and optional properties. The form has the same [validation checkbox](/audience/validate-contacts) as the CSV import. Tick it and the address is checked as it's saved. ## Sync from Integrations Connecting an [event-source integration](/integrations/integrations#trigger-automations-from-events) keeps contacts flowing into Brew automatically. Every webhook the provider sends does two things at once: * It fires every **Live** automation whose trigger matches the event. * It upserts the contact into your audience with provider-namespaced custom fields. Use those fields in filters and [merge tags](/create-emails/merge-tags). | Integration | What gets synced | | - | - | | [Clerk](/integrations/import/clerk) | `clerkUserId`, `clerkOrganizationId`, `clerkSubscriptionStatus`, `clerkPlanName`, `clerkIsTrialing`, `clerkSignedUpAt`, `clerkLastSignInAt`, `clerkWaitlistStatus` | | [Stripe](/integrations/import/stripe) | `stripeCustomerId`, `stripeSubscriptionStatus`, `stripeSubscriptionPlan`, `stripeLifetimeValueCents`, `stripeRenewsAt`, `stripeTrialEnd`, `stripeDelinquent`, plus one-click backfill of every historic customer | | [Stytch](/integrations/import/stytch) | `stytchProject` (Consumer or B2B), `stytchUserId`, `stytchMemberId`, `stytchOrganizationId`, `stytchOrgRole`, `stytchAccountStatus` | | [Supabase](/integrations/import/supabase) | `supabaseUserId`, `supabasePhone`, `supabaseRole`, `supabaseAccountStatus`, `supabaseEmailVerifiedAt`, `supabasePhoneVerifiedAt`, `supabaseLastSignInAt` | | [WorkOS](/integrations/import/workos) | `workosUserId`, `workosEmailVerified`, `workosOrganizationId`, `workosOrgRole`, `workosDirectoryUserId`, `workosDirectoryId`, `workosAccountStatus` | | [Shopify](/integrations/import/shopify) | `shopifyCustomerId`, `shopifyShopDomain`, `shopifyTags`, `shopifyAccountStatus`, `shopifyLastOrderId`, `shopifyLastOrderTotal`, `shopifyLastOrderAt`, `shopifyLastFulfillmentStatus` | | [RevenueCat](/integrations/import/revenuecat) | `revenuecatAppUserId`, `revenuecatStore`, `revenuecatEnvironment`, `revenuecatSubscriptionStatus`, `revenuecatProductId`, `revenuecatLastPurchaseAt` | Fields show on the contact in camelCase, such as `clerkUserId`. Contact search also accepts other spellings, such as `clerk_user_id`. A saved audience filter needs the exact key: another spelling saves without a warning but matches no one. Custom field definitions are auto-created on first write, typed from the values in that write. New fields show up filterable in the audience UI with no extra setup. Later writes convert their values to the field's type (with a `FIELD_TYPE_COERCED` warning over the API) or refuse the value with `FIELD_TYPE_MISMATCH`. That also holds when two writes create the same new field at the same moment: the first definition wins and the other write is converted or refused against it. To pin a type up front, create the field first (`POST /v1/fields`, or `create_contact_field` over MCP). Send large numeric ids, such as 64-bit database or CRM ids, as JSON strings to a `string` field. A JSON number above 9007199254740991 (2^53 - 1) arrives already rounded. Brew refuses it with `FIELD_TYPE_MISMATCH`, even for a `string` field. ## API Programmatically create, update, or delete contacts from your backend. There are two ways to import a batch, both recorded in [Import History](#import-history) and both returning the batch's `importId` (a [preview](#preview-an-import-or-add-new-contacts-only) records nothing and returns none): | Format | API | SDK | CLI | MCP | | - | - | - | - | - | | CSV text | `POST /v1/contacts/import-csv` | `brew.contacts.importCsv()` | `brew-cli contacts import-csv --file contacts.csv` | `import_contacts_csv` | | JSON rows | `POST /v1/contacts/import` | `brew.contacts.import()` | `brew-cli contacts import --file contacts.json` | `import_contacts` | Both imports create missing contacts (subscribed unless a row opts out) and update existing ones, unless `onConflict` is `"skip"`. Pass `fileName` to name the batch. For recurring syncs that shouldn't appear in Import History, use `POST /v1/contacts` with a `contacts` array (`upsertMany()`, `brew-cli contacts upsert-many`). All of these take an optional `validate: true` to [check each address](/audience/validate-contacts) as it's ingested. * **Limits.** Each call takes up to 1,000 contacts or CSV rows. * **Consent.** Send `consent` with a new subscribed contact to record how they opted in: a `source` (`api`, `form`, or `import`) and, optionally, when. The app's import checkbox records `app`. * **Rows and warnings.** Counts, per-row errors, skipped and duplicate rows, and field-name warnings are in [Contact Imports](/api-reference/api/batch-operations#contact-imports). Over MCP, `import_contacts` and `import_contacts_csv` create and update contacts like their API routes; `update_contact` updates one existing contact only. ### Preview an Import, or Add New Contacts Only Both imports take two optional modes: * **`dryRun: true`** returns the response the import would return and writes nothing: no contacts, no new fields (`fieldsCreated` lists the ones it would create), no Import History batch. The response carries `dryRun: true` and no `importId`; `validate` isn't run and nothing is charged. A real run on the same data right after returns the same counts, so check `errors` and `warnings` on the preview, then import. A preview can't foresee a failure that only happens while writing, such as a concurrent change. * **`onConflict: "skip"`** creates missing contacts and leaves every existing contact unchanged, an opt-out row included. Each existing contact counts in `summary.skipped`, with a `CONTACT_EXISTS_SKIPPED` warning naming its `row`; when that row asked to unsubscribe, the warning says its opt-out was not applied. To apply opt-outs, import them with the default mode. With `validate: true`, inline checks are still metered per submitted row, skipped ones included; a call that leaves nothing to check isn't charged. The default, `"upsert"`, updates existing contacts. | | API | SDK | CLI | MCP | | - | - | - | - | - | | Preview | `"dryRun": true` | `{ dryRun: true }` | `--dry-run` | `dryRun: true` | | New contacts only | `"onConflict": "skip"` | `{ onConflict: 'skip' }` | `--on-conflict skip` | `onConflict: "skip"` | ```bash theme={null} brew-cli contacts import-csv --file contacts.csv --dry-run --on-conflict skip brew-cli contacts import-csv --file contacts.csv --on-conflict skip ``` In Brew chat, both modes apply to CSV text the agent sends. An attached CSV file imports in the background and always creates and updates. > [card] [View API documentation](/api-reference/api/api-introduction) > > Endpoints, authentication, and code examples ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Audience Hygiene Source: https://docs.brew.new/audience/audience-hygiene Keep your contact list clean and engaged so your emails reach the inbox, using validation, engagement tiers, and regular re-engagement. Audience hygiene is the practice of keeping your list valid, relevant, and engaged. For day-to-day contact management like handling bounces and suppression lists, see [Manage contacts](/audience/manage-contacts). ## How Brew Protects Your Sending Reputation Brew tracks bounce rate and spam complaint rate on every send. A domain's health read (`get_domain_health`, or `GET /v1/domains/{domainId}/health`) reports both from a sample of sends and flags a high rate. [Brew Insights](/analytics/insights) flags a send whose bounce rate is high enough for mailbox providers to act on. [What You Can Send](/get-started/what-you-can-send#what-brew-monitors) states the thresholds. They protect everyone on the platform: a single sender with poor list quality can affect shared sending infrastructure. The best way to keep bounces from happening at all is to [validate your contacts](/audience/validate-contacts) before you send. Each address comes back valid, risky, or invalid, and the verdict is saved on the contact. That page covers every way to run the check, from one click on an audience to the API. ## Build a Quality List from the Start The foundation of a healthy audience is how contacts get on it in the first place. **Be clear on your sign-up forms.** Tell people what they're signing up for and how often you'll email them. Transparency reduces unsubscribes and attracts contacts who want to hear from you. **Use CAPTCHA on sign-up forms.** Bot submissions inflate your list with invalid addresses that hurt deliverability. Three solid options: * **[Google reCAPTCHA](https://developers.google.com/recaptcha)**: multiple protection levels from invisible verification to interactive challenges, with excellent bot detection. Simple integration with most website platforms. * **[hCaptcha](https://www.hcaptcha.com/)**: privacy-focused alternative with enterprise-grade security, adjustable difficulty settings, and strong accessibility options. * **[Friendly Captcha](https://friendlycaptcha.com/)**: runs verification in the background without puzzles. Designed for strong privacy protection and compliance with global regulations. **Never purchase lists.** Brew only allows permission-based email. Purchased lists contain people who never opted in to hear from you specifically. They lead to high bounce rates, spam complaints, and account suspension. See [What you can send with Brew](/get-started/what-you-can-send) for the full policy. ## Monitor Engagement over Time Regularly check your key metrics in Analytics: * Open rate * Click rate * Bounce rate * Spam complaint rate * Unsubscribe rate A significant drop from your baseline means something needs attention: your content, your sending frequency, or your contact quality. ## Segment by Engagement Targeting engaged segments for regular sends protects your sending reputation and improves performance. [Create Audiences](/audience/create-audiences#common-audience-patterns) lists the standard tiers, from highly engaged down to inactive. Audiences in Brew are dynamic. As contacts engage or go quiet, they move in and out of segments automatically. You don't need to rebuild them. A time window like "in the last 30 days" is the exception. Engagement lives in your event history, not on the contact, so a saved filter can't express it. Build those cohorts from events instead, as described in [Engagement snapshots](/audience/create-audiences#engagement-snapshots). **To build an inactive segment:** 1. Ask your agent for the cohort, for example: ``` Create an audience of contacts who haven't opened or clicked an email in the last 90 days. ``` 2. The agent builds an engagement snapshot with `create_audience_from_events`. It uses `cohort.exclude`, so the audience holds everyone in your base audience who did *not* open or click in that window. 3. Wait until the build is ready before you send to it. 4. Name it with the date, like "Inactive 90 days: 2026-10-14". A snapshot is frozen, so build a fresh one each time. Build each tier the same way. Use your highly engaged segment as the primary audience for your regular sends. ## Re-engage Inactive Contacts Contacts who've gone quiet are worth one well-aimed attempt before you stop sending to them. **As an Email.** Send a one-off Email to your inactive segment: 1. Go to **Emails** in the sidebar and open a new chat. 2. Select your inactive audience segment. 3. Use a prompt like: ``` Create a re-engagement email with a subject line about missing the recipient, acknowledging their inactivity, reminding them of our value, and including a clear CTA to stay subscribed. ``` 4. Review and refine the output, then send. **As an Automation.** Build a 2 to 3 step re-engagement flow and run it for an [engagement snapshot](/audience/create-audiences#engagement-snapshots) of inactive contacts. Brew has no scheduled trigger, so build a fresh snapshot and run it again each cycle. See the [Lifecycle emails for SaaS and B2B](/recipes/lifecycle-emails-saas-b2b) recipe for prompts and a step-by-step walkthrough. **After the re-engagement attempt**, handle contacts based on how they responded: * **Re-engaged**: move them back into your active sending audience * **Still inactive**: exclude them from regular sends * **No response after final email**: exclude them from every send, but keep the contact Continuing to send to chronically inactive contacts hurts your metrics and your sending reputation. ## Set a Sunset Policy Decide upfront what inactive means for your business and what happens when a contact crosses that threshold. A simple policy: 1. No engagement in 90 days. Enter re-engagement flow. 2. No engagement after re-engagement flow. Exclude from regular sends. 3. No engagement in 6 months. Exclude from every send. Don't delete inactive contacts to clean the list. Exclude them with a filter instead. Deleting a contact removes its profile and activity. Brew keeps its unsubscribe and bounce restrictions, so re-adding the address doesn't make it mailable. See [Manage Contacts](/audience/manage-contacts#deleting-contacts) for what a delete removes. ## Recurring Hygiene Tasks A few things worth doing on a regular cadence: * **Before a big send**: [validate the audience](/audience/validate-contacts) you're about to send to, and pull anything that comes back invalid. * **Monthly**: check bounce rate and spam complaint rate trends. Flag anything moving toward the thresholds. * **Quarterly**: run a re-engagement campaign for contacts inactive 90 or more days. * **Every 6 months**: review your active sending audience and prune contacts who haven't engaged in over 6 months. ## Need Help? Our team is ready to support you at every step of your journey with Brew. Choose the option that works best for you: > [tab] Self-Service Tools > > > [card] Search Documentation > > > > Type in the "Ask any question" search bar at the top left to instantly find relevant documentation pages. > > > [card] [Ask ChatGPT or Claude](#top) > > > > Click here to open the **Copy page** menu at the top of this page, then send the page to ChatGPT, Claude, or your editor. > [tab] Talk to Our Team > > > [card] [Schedule a Call](https://cal.com/team/brewdotnew/brew-demo) > > > > Book time with our founders for personalized guidance on strategy, best practices, or complex implementation questions. > > > [card] Call Us Directly > > > > Need immediate assistance? Reach us at **+1-(332)-203-2145** for urgent issues or time-sensitive questions. > > > [card] Slack Channel > > > > Our preferred support channel. You'll receive an invite after signup for direct founder support and fast responses. > > > [card] [Email Support](mailto:support@brew.new) > > > > Contact us at **[support@brew.new](mailto:support@brew.new)** for detailed inquiries or if you prefer not to use Slack. # Create Audiences Source: https://docs.brew.new/audience/create-audiences Segment your contacts to send the right email to the right people. Describe the audience in plain English or build filters by hand.