# API Documentation - Ads Agents

> Ads Agents REST API documentation. Create accounts, manage campaigns, generate AI content, and automate Facebook & Instagram ads programmatically.

# API Documentation

Build, automate, and scale ad campaigns programmatically

Guide AI Agent Integration API Reference

## Overview

The Ads Agents API lets you programmatically create accounts, manage ad campaigns, generate AI content, and monitor performance across Facebook and Instagram. It's designed for both human developers and AI agents.

🔑

#### Register & Verify

Create an account with one API call. Verify via email or phone.

🤖

#### Generate Content

AI creates ad copy and images from your product description.

🚀

#### Launch Campaigns

Deploy to Facebook & Instagram with budget and targeting.

📊

#### Monitor & Optimize

Real-time analytics and AI-powered optimization.

## Quick Start (5 Minutes)

Go from zero to a running campaign in 6 API calls. Here's the complete flow:

1

#### Create your account

Register with your email. You get an API key immediately.

\# Register curl -X POST https://app.ads-agents.com/api/v1/auth/register \\ -H "Content-Type: application/json" \\ -d '{ "email": "you@company.com", "password": "yourSecurePassword", "first\_name": "Jane", "last\_name": "Smith" }' \# Response: { "user": { "id": 5, "email": "you@company.com", "first\_name": "Jane", "last\_name": "Smith", "enabled": false, "created\_at": "2026-02-27T21:45:48+0000" }, "api\_key": "aa\_live\_4b5dcbc0223e4da8...", "message": "Account created. Please verify your email." }

2

#### Verify your account

Check your email for a 6-digit code and submit it.

curl -X POST https://app.ads-agents.com/api/v1/auth/verify \\ -H "Content-Type: application/json" \\ -d '{ "email": "you@company.com", "code": "482917" }' \# Response: { "message": "Account verified successfully.", "user": { "id": 5, "email": "you@company.com", "enabled": true, ... } }

3

#### Create your business

Set up your business profile — required before creating campaigns.

curl -X POST https://app.ads-agents.com/api/v1/account/business \\ -H "Authorization: Bearer aa\_live\_4b5dcbc0223e4da8..." \\ -H "Content-Type: application/json" \\ -d '{ "name": "Acme Corp" }' \# Response: { "id": 1, "name": "Acme Corp", "message": "Business created successfully." }

4

#### Create a campaign

Set your objective, budget, ad copy, and targeting.

curl -X POST https://app.ads-agents.com/api/v1/campaigns \\ -H "Authorization: Bearer aa\_live\_4b5dcbc0223e4da8..." \\ -H "Content-Type: application/json" \\ -d '{ "name": "Summer Launch", "objective": "CONVERSIONS", "daily\_budget": 50.0, "product\_description": "Online accounting for small businesses", "message": "Simplify your books. Start free today!", "target\_url": "https://acme.com/start", "audience\_description": "Small business owners aged 25-55", "target\_location": "United States" }' \# Response: { "id": 5, "name": "Summer Launch", "status": "DRAFT", "objective": "CONVERSIONS", "daily\_budget": 50.0, ... }

5

#### Set up a webhook (optional)

Get notified when campaigns change status, metrics update, or AI suggestions arrive.

curl -X POST https://app.ads-agents.com/api/v1/webhooks \\ -H "Authorization: Bearer aa\_live\_4b5dcbc0223e4da8..." \\ -H "Content-Type: application/json" \\ -d '{ "url": "https://acme.com/hooks/ads", "events": \["campaign.created", "campaign.updated"\] }' \# Response includes a signing secret: { "id": 1, "url": "https://acme.com/hooks/ads", "events": \["campaign.created", "campaign.updated"\], "active": true, "secret": "686950eb37608aa7..." }

6

#### Subscribe & connect Facebook

Choose a plan and connect your Facebook Ads account. Both use email-based flows.

\# Subscribe (free plan activates instantly) curl -X POST https://app.ads-agents.com/api/v1/billing/subscribe \\ -H "Authorization: Bearer aa\_live\_4b5dcbc0223e4da8..." \\ -H "Content-Type: application/json" \\ -d '{ "plan\_id": 1 }' \# For paid plans, an email with a checkout link is sent \# Poll: GET /api/v1/billing/subscribe/status?token=... \# Connect Facebook (sends email with OAuth link) curl -X POST https://app.ads-agents.com/api/v1/platforms/facebook/connect \\ -H "Authorization: Bearer aa\_live\_4b5dcbc0223e4da8..." \# Poll: GET /api/v1/platforms/facebook/connect/status?token=...

**Tip:** All endpoints use the base URL `https://app.ads-agents.com/api/v1/`. Authenticate with `Authorization: Bearer aa_live_...` header.

## Authentication

All API requests require a Bearer token in the `Authorization` header:

Authorization: Bearer aa\_live\_abc123def456

API keys are issued immediately on registration. You can create additional keys, scope them, and rotate them via the `/auth/keys` endpoints.

### Key Prefixes

| Prefix | Environment | Use |
| --- | --- | --- |
| `aa_live_` | Production | Real campaigns, real spend |
| `aa_test_` | Sandbox | Testing with mock data |

### OAuth 2.0

For third-party integrations, use the OAuth 2.0 Authorization Code flow. Available scopes: `campaigns:read`, `campaigns:write`, `content:generate`, `analytics:read`, `billing:read`, `billing:write`, `webhooks:manage`, `account:read`, `account:write`.

## Base URL

\# Production https://app.ads-agents.com/api/v1 \# Sandbox https://sandbox.app.ads-agents.com/api/v1

All endpoints are versioned under `/v1`. JSON request and response bodies. Always use HTTPS.

## Registration

Creating an account is a single API call. Provide email, password, and your name.

POST /v1/auth/register { "email": "user@example.com", "password": "securePassword123", "first\_name": "Jane", "last\_name": "Smith" }

The response includes your API key immediately:

201 Created { "user": { "id": 5, "email": "user@example.com", "first\_name": "Jane", "last\_name": "Smith", "enabled": false, "created\_at": "2026-02-27T21:45:48+0000" }, "api\_key": "aa\_live\_4b5dcbc0223e4da8...", "message": "Account created. Please verify your email \\u2014 a 6-digit code has been issued." }

Already have an account? Log in to get your API key:

POST /v1/auth/login { "email": "user@example.com", "password": "securePassword123" } // Response: { "user": { "id": 5, "email": "user@example.com", "enabled": true, ... }, "api\_key": "aa\_live\_...", "scopes": \["campaigns:read", "campaigns:write", "analytics:read", ...\] }

**Important:** Store your API key securely. You can create additional keys via `POST /v1/auth/keys` and list them with `GET /v1/auth/keys`.

## Verification

A 6-digit code is sent to your email on registration. Submit it with your email to activate your account:

POST /v1/auth/verify { "email": "user@example.com", "code": "482917" } // Response: { "message": "Account verified successfully.", "user": { "id": 5, "email": "user@example.com", "first\_name": "Jane", "last\_name": "Smith", "enabled": true, "created\_at": "2026-02-27T21:45:48+0000" } }

Code expired? Request a new one:

POST /v1/auth/verify/resend { "email": "user@example.com" }

## Billing & Subscriptions

Subscribe to a plan via an email-based checkout flow. Free plans activate instantly; paid plans send a secure payment link.

### View Plans (no auth required)

GET /v1/billing/plans // Response: { "data": \[ { "id": 1, "name": "Free", "price": 0.00, "currency": "USD" }, { "id": 2, "name": "Standard", "price": 49.00, "currency": "USD" }, { "id": 3, "name": "Flexible", "price": 199.00, "currency": "USD" } \] }

### Subscribe to a Plan

POST /v1/billing/subscribe Authorization: Bearer aa\_live\_... { "plan\_id": 2 } // Free plan — activates immediately: { "status": "active", "subscription": { "plan": { "name": "Free" }, ... }, "message": "Free plan activated." } // Paid plan — sends email with checkout link: { "status": "pending", "plan": { "id": 2, "name": "Standard", "price": 49.00, "currency": "USD" }, "checkout\_url": "https://app.ads-agents.com/api/v1/billing/checkout?token=a839de34...", "token": "a839de34463e460e...", "message": "A payment link has been sent to you@company.com. Click the link to complete your Standard subscription ($49.00/mo). The link expires in 24 hours.", "expires\_at": "2026-03-01T04:15:25+0000" }

### Checkout Flow

1

#### Call subscribe

API returns a checkout URL and sends an email with a branded **"Subscribe Now"** button.

2

#### User clicks the email link

Redirects to Stripe checkout (or activates directly in demo mode).

3

#### Poll for completion

Your app polls the status endpoint to know when the subscription is active.

GET /v1/billing/subscribe/status?token=a839de34... Authorization: Bearer aa\_live\_... // Before payment: { "status": "pending", "message": "Waiting for payment to be completed." } // After payment: { "status": "active", "subscription": { "id": 2, "plan": { "name": "Standard", "price": 49.00 }, "active": true }, "message": "Subscription is active." }

### Check & Cancel

\# Current subscription status GET /v1/billing/status \# Cancel subscription POST /v1/billing/cancel \# Invoice history GET /v1/billing/invoices

## Access Levels

| Account State | API Access | What You Can Do |
| --- | --- | --- |
| **Created (unverified)** | Limited | Auth & account endpoints only |
| **Verified (Free)** | Free tier | Create business, campaigns, webhooks |
| **Standard ($49/mo)** | Full | Extended campaigns, AI content generation |
| **Flexible ($199/mo)** | Full | Unlimited campaigns, priority support |

## Create a Campaign

Campaigns are the top-level resource. Before creating a campaign, you need a verified account and a business.

### Set Up Your Business

Create a business profile (one-time):

POST /v1/account/business Authorization: Bearer aa\_live\_... { "name": "Acme Corp" } // Response: { "id": 1, "name": "Acme Corp", "message": "Business created successfully." }

### Create a Campaign

POST /v1/campaigns Authorization: Bearer aa\_live\_... { "name": "Summer Launch", "objective": "CONVERSIONS", "daily\_budget": 50.0, "product\_description": "Online accounting for small businesses", "message": "Simplify your books. Start free today!", "target\_url": "https://acme.com/start", "audience\_description": "Small business owners aged 25-55", "target\_location": "United States" } // Response: { "id": 5, "name": "Summer Launch", "status": "DRAFT", "objective": "CONVERSIONS", "product\_description": "Online accounting for small businesses", "message": "Simplify your books. Start free today!", "target\_url": "https://acme.com/start", "audience\_description": "Small business owners aged 25-55", "target\_location": "United States", "daily\_budget": 50.0, "facebook\_campaign\_id": null, "created\_at": "2026-02-27T22:02:22+0000", "updated\_at": "2026-02-27T22:02:22+0000" }

### Campaign Objectives

| Objective | Description |
| --- | --- |
| `CONVERSIONS` | Optimize for purchases, signups, or other conversions |
| `TRAFFIC` | Drive visitors to your website or landing page |
| `AWARENESS` | Maximize brand visibility and reach |
| `ENGAGEMENT` | Get more likes, comments, and shares |
| `LEADS` | Collect leads via forms |
| `APP_INSTALLS` | Drive mobile app installations |

### List & Manage Campaigns

\# List campaigns GET /v1/campaigns \# Get single campaign GET /v1/campaigns/{id} \# Update campaign PATCH /v1/campaigns/{id} \# Delete campaign DELETE /v1/campaigns/{id} \# Launch campaign (deploy to Facebook) POST /v1/campaigns/{id}/launch

### Campaign Lifecycle

DRAFT → ACTIVE → PAUSED → COMPLETED

### Campaign Object

{ "id": "camp\_8xKj2mN", "name": "Summer Sale 2025", "objective": "conversions", "status": "active", "platforms": \["facebook", "instagram"\], "budget": { "type": "daily", "amount": 50.00, "currency": "USD" }, "schedule": { "start\_date": "2025-07-01", "end\_date": "2025-07-31" }, "optimization": { "enabled": true, "strategy": "maximize\_conversions", "frequency": "hourly" }, "metrics": { "impressions": 15247, "clicks": 432, "ctr": 2.83, "conversions": 38, "spend": 48.50, "cpc": 0.11, "roas": 3.4 }, "created\_at": "2025-07-01T00:00:00Z", "updated\_at": "2025-07-15T14:30:00Z" }

## AI Content Generation

Generate ad copy and images using AI. Powered by GPT-4, Claude, Grok for text and DALL-E, Stable Diffusion for images.

### Generate Ad Copy

POST /v1/ai/generate/text { "product\_description": "Online accounting dashboard for small businesses", "target\_audience": "Small business founders aged 25-45", "tone": "professional", "variations": 5, "types": \["headline", "primary\_text", "description"\], "platform": "facebook", "language": "en" } // Response: { "id": "gen\_9xMk3nP", "status": "completed", "variations": \[ { "headline": "Transform Your Business Finances", "primary\_text": "Join 10,000+ founders tracking metrics in real time...", "description": "AI-powered financial insights for growth.", "predicted\_ctr": 2.8 }, // ... more variations \], "credits\_used": 5, "credits\_remaining": 495 }

### Generate Images

POST /v1/ai/generate/image { "prompt": "Professional business dashboard on laptop, clean modern office", "style": "photo\_realistic", "size": "1080x1080", "count": 3, "provider": "auto" } // Returns generation ID — poll /v1/ai/generations/{id} for results

### Full Variations (Text + Image)

POST /v1/ai/generate/variations { "product\_description": "Online accounting dashboard", "target\_audience": "Small business founders", "count": 10, "platform": "facebook", "include\_images": true, "tone": "professional" }

## Analytics

Monitor campaign performance in real time.

| Method | Endpoint | Description |
| --- | --- | --- |
| GET | /v1/analytics/overview | Account-level summary |
| GET | /v1/analytics/campaigns/{id} | Campaign metrics (by platform, by ad set) |
| GET | /v1/analytics/time-series | Time-series data (hourly/daily/weekly) |
| POST | /v1/analytics/reports | Generate custom reports (JSON/CSV/PDF) |
| GET | /v1/analytics/predictions | AI performance predictions |

GET /v1/analytics/campaigns/camp\_8xKj2mN?date\_from=2025-07-01&date\_to=2025-07-15 { "campaign\_id": "camp\_8xKj2mN", "campaign\_name": "Summer Sale 2025", "metrics": { "impressions": 15247, "clicks": 432, "ctr": 2.83, "conversions": 38, "spend": 48.50, "roas": 3.4 }, "by\_platform": { "facebook": { "impressions": 9148, "clicks": 259, ... }, "instagram": { "impressions": 6099, "clicks": 173, ... } } }

## Platform Connections

Connect your Facebook Ads account via a secure email-based OAuth flow. Since Facebook authorization requires a browser, the API sends a one-click connect link to your email.

### Connection Flow

1

#### Request connection

Call the connect endpoint. You'll receive a connect URL and an email with a branded button.

POST /v1/platforms/facebook/connect Authorization: Bearer aa\_live\_... // Response: { "status": "pending", "platform": "facebook", "connect\_url": "https://app.ads-agents.com/api/v1/platforms/facebook/setup?token=b7e335...", "message": "A connection link has been sent to you@company.com. Click the link to authorize Facebook access. The link expires in 1 hour.", "token": "b7e3358c4a3745a7af1b1d02d8ccba2c", "expires\_at": "2026-02-28T05:09:47+0000" }

2

#### Click the email link

The user opens their email and clicks **"Connect Facebook Ads"**. This redirects to Facebook's OAuth consent screen.

3

#### Authorize & done

After granting permissions, Facebook redirects back. The user sees a success page and can close the browser.

4

#### Poll for completion (optional)

Your app can poll the status endpoint to know when the connection is live.

GET /v1/platforms/facebook/connect/status?token=b7e335... Authorization: Bearer aa\_live\_... // Before user clicks: { "status": "pending", "platform": "facebook", "message": "Waiting for user to complete Facebook authorization." } // After successful connection: { "status": "connected", "platform": "facebook", "message": "Facebook account connected successfully." } // If token expired: { "status": "expired", "platform": "facebook", "message": "Connect token has expired. Request a new connection." }

### Manage Connections

\# List connected platforms GET /v1/platforms \# Check platform health GET /v1/platforms/{id}/status \# Disconnect a platform DELETE /v1/platforms/{id}

**Why email?** Facebook OAuth requires a browser for user consent. The email flow lets API-only integrations connect Facebook without building their own OAuth UI. The connect link is single-use and expires in 1 hour.

## Webhooks

Get real-time notifications when things happen. All payloads are signed with HMAC-SHA256.

### Available Events

| Event | Description |
| --- | --- |
| `account.verified` | Account verification completed |
| `billing.payment_completed` | Subscription payment succeeded |
| `billing.payment_failed` | Payment attempt failed |
| `campaign.created` | New campaign created |
| `campaign.launched` | Campaign deployed to platforms |
| `campaign.paused` | Campaign paused |
| `ad.optimized` | AI replaced/modified ad creative |
| `budget.reallocated` | AI shifted budget between ad sets |
| `generation.completed` | AI content generation finished |
| `alert.spend` | Spend threshold reached |
| `alert.performance` | Performance anomaly detected |

### Register a Webhook

POST /v1/webhooks { "url": "https://your-server.com/webhooks/ads-agents", "events": \["campaign.launched", "ad.optimized", "alert.performance"\] } // Response includes your signing secret — save it!

### Verify Webhook Signatures

\# The X-Webhook-Signature header contains the HMAC-SHA256 signature \# Verify it against the raw request body using your webhook secret import hmac, hashlib def verify(payload, signature, secret): expected = hmac.new(secret.encode(), payload, hashlib.sha256).hexdigest() return hmac.compare\_digest(f"sha256={expected}", signature)

## Rate Limits

| Limit | Free | Starter | Growth | Agency |
| --- | --- | --- | --- | --- |
| Requests/min | 10 | 30 | 60 | 300 |
| Requests/day | 500 | 5,000 | 10,000 | 100,000 |
| AI generations/mo | 10 | 50 | 500 | Unlimited |

Rate limit headers are included in every response:

X-RateLimit-Limit: 60 X-RateLimit-Remaining: 45 X-RateLimit-Reset: 1721052600 // Unix timestamp Retry-After: 30 // Only on 429 responses

## Error Handling

All errors return a consistent JSON structure:

{ "error": { "code": "campaign\_budget\_too\_low", "message": "Daily budget must be at least $10.00", "status": 422, "details": { "field": "budget.amount", "min\_value": 10.00 }, "request\_id": "req\_abc123" } }

### HTTP Status Codes

| Code | Meaning | When |
| --- | --- | --- |
| 200 | OK | Successful request |
| 201 | Created | Resource created |
| 204 | No Content | Successful delete |
| 400 | Bad Request | Malformed JSON |
| 401 | Unauthorized | Invalid/missing API key |
| 403 | Forbidden | Unverified or insufficient plan |
| 404 | Not Found | Resource doesn't exist |
| 409 | Conflict | Email/phone already registered |
| 422 | Validation Error | Invalid field values |
| 429 | Rate Limited | Too many requests |
| 500 | Server Error | Retry with exponential backoff |

## Pagination

List endpoints use cursor-based pagination:

GET /v1/campaigns?limit=10 { "data": \[ ... \], "pagination": { "next\_cursor": "eyJpZCI6ImNhbXBfOTk5In0", "has\_more": true, "total": 47 } } \# Next page: GET /v1/campaigns?limit=10&cursor=eyJpZCI6ImNhbXBfOTk5In0

## SDKs & Libraries

**Coming soon:** Official Python and Node.js SDKs. In the meantime, use the REST API directly or generate a client from our [OpenAPI spec](/openapi.yml).

\# Generate a Python client from the OpenAPI spec npx @openapitools/openapi-generator-cli generate \\ -i https://ads-agents.com/openapi.yml \\ -g python \\ -o ./ads-agents-python-sdk

## Building AI Agents with Ads Agents API

The Ads Agents API is built agent-first. Every action available in the dashboard can be performed programmatically, making it ideal for autonomous AI workflows. Your agent can:

-   **Create accounts** and manage the full onboarding flow
-   **Generate AI content** — ad copy, headlines, images — from natural language descriptions
-   **Launch and manage campaigns** across Facebook and Instagram
-   **Monitor performance** and make data-driven decisions
-   **React to events** via webhooks for fully autonomous operation

**Design Principles:** Deterministic JSON schemas. Machine-readable error codes. Predictable pagination. No HTML responses. Every enum is documented. Your agent never has to guess.

## Full Agent Lifecycle: Zero to Live Campaign

Here's the complete flow an AI agent follows to go from nothing to a running, optimized ad campaign:

\# Complete Agent Workflow \# Phase 1: Account Setup 1. POST /v1/auth/register → Create account (get API key) 2. POST /v1/auth/verify → Submit verification code 3. POST /v1/billing/subscribe → Send payment link to human \# Phase 2: Platform Connection 4. POST /v1/platforms/connect → Get OAuth URL for Facebook/Instagram \# → Human clicks OAuth URL, grants access 5. GET /v1/platforms → Confirm connection \# Phase 3: Content Creation 6. POST /v1/ai/generate/text → Generate ad copy 7. POST /v1/ai/generate/image → Generate ad images \# Or use /v1/ai/generate/variations for both at once \# Phase 4: Campaign Launch 8. POST /v1/campaigns → Create campaign 9. POST /v1/campaigns/{id}/ad-sets → Add targeting groups 10. POST /v1/.../ads → Add ads with generated content 11. POST /v1/campaigns/{id}/launch → Go live! \# Phase 5: Continuous Optimization (loop) 12. GET /v1/analytics/campaigns/{id} → Check performance 13. POST /v1/ai/optimize/suggest → Get AI suggestions 14. PATCH /v1/campaigns/{id} → Apply optimizations \# → Repeat 12-14 every few hours

## Authentication for Agents

Agents authenticate the same way humans do — with a Bearer token. The API key returned at registration is immediately usable.

\# Store the API key from registration API\_KEY = "aa\_live\_abc123def456" \# Use it in every request headers = { "Authorization": f"Bearer {API\_KEY}", "Content-Type": "application/json" }

### Scoped Keys for Agent Safety

Create limited-scope keys so your agent only has the permissions it needs:

POST /v1/auth/keys { "name": "Campaign Manager Agent", "scopes": \["campaigns:read", "campaigns:write", "content:generate", "analytics:read"\] } // This key CANNOT manage billing, webhooks, or account settings

## Handling Verification

Verification requires a human to check their email or phone for a code. Your agent has two strategies:

### Strategy A: Agent Reads Email (Autonomous)

If your agent has email access (via IMAP, Gmail API, etc.), it can extract the verification code automatically:

\# Pseudocode for autonomous verification 1. POST /v1/auth/register (verification\_method: "email") 2. Wait 10-30 seconds for email delivery 3. Read inbox, find email from "Ads Agents" or "noreply@ads-agents.com" 4. Extract 6-digit code from email body 5. POST /v1/auth/verify (code: extracted\_code) 6. Account is now verified ✓

### Strategy B: Ask Human for Code (Interactive)

If the agent is working with a human, it can simply ask them to provide the code:

\# Agent asks human Agent: "I've sent a verification code to your@email.com. Please check your email and give me the 6-digit code." Human: "482917" Agent: → POST /v1/auth/verify { "code": "482917" }

**Tip:** If verification fails, use `POST /v1/auth/verify/resend` to request a new code. Codes expire after 15 minutes.

## Handling Payment

Payment requires a human to click a checkout link. The agent initiates it and waits for confirmation:

\# Agent initiates payment response = POST /v1/billing/subscribe { "plan": "growth", "billing\_cycle": "monthly", "payment\_method": "email" // sends link to user's email } \# Agent tells user Agent: "I've sent a payment link to your@email.com for the Growth plan ($149/mo). Please complete the checkout. I'll start setting up your campaigns as soon as the payment goes through." \# Agent polls or listens for webhook \# Option A: Poll billing status while true: status = GET /v1/billing/status if status.plan == "growth": break sleep(30) \# Option B: Listen for webhook (preferred) \# → billing.payment\_completed event fires automatically

## Campaign Management

Here's how an agent creates a complete campaign with ad sets and ads:

\# Step 1: Generate content content = POST /v1/ai/generate/variations { "product\_description": "SaaS project management tool", "target\_audience": "Remote teams and startups", "count": 5, "platform": "facebook", "include\_images": true } \# Step 2: Create campaign campaign = POST /v1/campaigns { "name": "Q3 Growth Campaign", "objective": "conversions", "platforms": \["facebook", "instagram"\], "budget": {"type": "daily", "amount": 100, "currency": "USD"}, "schedule": {"start\_date": "2025-07-01", "end\_date": "2025-09-30"}, "optimization": {"enabled": true, "strategy": "maximize\_conversions", "frequency": "hourly"} } \# Step 3: Create ad set with targeting ad\_set = POST /v1/campaigns/{campaign.id}/ad-sets { "name": "US Remote Workers 25-45", "targeting": { "age\_min": 25, "age\_max": 45, "locations": \[{"type": "country", "value": "US"}\], "interests": \["remote work", "project management", "startups"\] } } \# Step 4: Add ads from generated content for variation in content.variations: POST /v1/campaigns/{campaign.id}/ad-sets/{ad\_set.id}/ads { "name": f"Variation {i}", "creative": { "headline": variation.headline, "primary\_text": variation.primary\_text, "description": variation.description, "image\_url": variation.image\_url, "call\_to\_action": "sign\_up", "link\_url": "https://yourapp.com/signup" }, "generation\_id": content.id } \# Step 5: Launch! POST /v1/campaigns/{campaign.id}/launch

## Continuous Optimization Loop

Set up your agent to continuously monitor and improve campaigns:

\# Run every 2-4 hours \# 1. Check performance analytics = GET /v1/analytics/campaigns/{campaign\_id} \# 2. Evaluate metrics if analytics.metrics.ctr < 1.5: \# CTR is low — get AI suggestions suggestions = POST /v1/ai/optimize/suggest { "campaign\_id": campaign\_id, "strategies": \["new\_message", "new\_image", "similar\_audience"\] } \# 3. Apply high-impact suggestions for suggestion in suggestions where suggestion.impact == "high": if suggestion.type == "new\_message": \# Generate fresh ad copy POST /v1/ai/generate/text { ... } elif suggestion.type == "pause\_ad": \# Pause underperformer DELETE /v1/.../ads/{ad\_id} if analytics.metrics.roas > 4.0: \# Campaign is performing well — increase budget PATCH /v1/campaigns/{campaign\_id} { "budget": {"amount": current\_budget \* 1.2} }

### Set Up Optimization Rules

Let the platform auto-optimize without agent intervention:

POST /v1/optimization/rules { "name": "Pause low CTR ads", "condition": { "metric": "ctr", "operator": "lt", "value": 1.0, "timeframe\_hours": 48 }, "action": { "type": "pause\_ad" }, "campaign\_id": "camp\_8xKj2mN" }

## Webhook-Driven Agent Architecture

The most powerful pattern: your agent listens for events and reacts autonomously.

\# Register webhook for key events POST /v1/webhooks { "url": "https://your-agent.com/webhook", "events": \[ "campaign.launched", "ad.optimized", "ad.paused", "budget.reallocated", "alert.performance", "alert.spend", "generation.completed" \] } \# Your agent's webhook handler: def handle\_webhook(event): match event.type: case "ad.optimized": \# Log what the AI changed log(f"Ad {event.data.ad\_id} updated: {event.data.reason}") case "alert.performance": \# Performance dropped — investigate analytics = GET /v1/analytics/campaigns/{event.data.campaign\_id} suggestions = POST /v1/ai/optimize/suggest { ... } \# Apply suggestions... case "alert.spend": \# Budget warning — notify human notify\_human(f"Campaign spend reached {event.data.threshold}") case "generation.completed": \# New content ready — create ads with it result = GET /v1/ai/generations/{event.data.generation\_id} \# Add new ads to campaign...

## Batch Operations

Reduce API calls when managing multiple campaigns:

POST /v1/batch { "requests": \[ { "id": "get-campaign-1", "method": "GET", "path": "/v1/analytics/campaigns/camp\_abc" }, { "id": "get-campaign-2", "method": "GET", "path": "/v1/analytics/campaigns/camp\_def" }, { "id": "update-budget", "method": "PATCH", "path": "/v1/campaigns/camp\_abc", "body": {"budget": {"amount": 75}} } \] } // All 3 requests execute in parallel, results returned together

## MCP Server Integration

Ads Agents provides an MCP (Model Context Protocol) server, allowing LLMs like Claude, GPT-4, and others to use Ads Agents as a native tool.

\# Install the MCP server npm install -g @ads-agents/mcp-server \# Configure in your MCP client (e.g., Claude Desktop) { "mcpServers": { "ads-agents": { "command": "ads-agents-mcp", "env": { "ADS\_AGENTS\_API\_KEY": "aa\_live\_abc123def456" } } } }

### Available MCP Tools

| Tool | Description |
| --- | --- |
| `create_campaign` | Create and configure a new ad campaign |
| `generate_ad_content` | Generate AI-powered ad copy and images |
| `launch_campaign` | Deploy a campaign to Facebook/Instagram |
| `get_analytics` | Retrieve campaign performance metrics |
| `optimize_campaign` | Get and apply AI optimization suggestions |
| `manage_budget` | Adjust campaign budgets and allocation |
| `list_campaigns` | View all campaigns with status and metrics |

### Example: Claude Creating a Campaign

\# User says to Claude: "Create a Facebook ad campaign for my new SaaS product targeting startups. Budget: $50/day for 30 days." \# Claude uses MCP tools: 1. generate\_ad\_content(product="SaaS product", audience="startups") 2. create\_campaign(name="SaaS Launch", budget=50, platforms=\["facebook"\]) 3. launch\_campaign(campaign\_id="camp\_xxx") 4. → "Your campaign is live! I'll monitor performance and optimize."

## Error Recovery for Agents

Build resilient agents that handle errors gracefully:

\# Error handling patterns for agents def api\_call(method, path, body=None, retries=3): for attempt in range(retries): response = request(method, BASE\_URL + path, json=body, headers=headers) match response.status\_code: case 200 | 201 | 204: return response.json() if response.content else None case 401: \# API key invalid — rotate or re-authenticate refresh\_api\_key() continue case 403: error = response.json()\["error"\] if error\["code"\] == "account\_not\_verified": \# Trigger verification flow handle\_verification() elif error\["code"\] == "plan\_limit\_reached": \# Notify human about upgrade notify("Plan limit reached, upgrade needed") return None case 409: \# Resource conflict — likely duplicate return None case 422: \# Validation error — fix the request log(f"Validation: {response.json()\['error'\]\['details'\]}") return None case 429: \# Rate limited — wait and retry retry\_after = int(response.headers.get("Retry-After", 30)) sleep(retry\_after) continue case 500: \# Server error — exponential backoff sleep(2 \*\* attempt) continue

## Full Agent Example: Python

A complete, runnable Python agent that creates and manages a campaign:

import requests, time BASE = "https://app.ads-agents.com/api/v1" API\_KEY = "aa\_live\_abc123def456" H = {"Authorization": f"Bearer {API\_KEY}", "Content-Type": "application/json"} \# 1. Generate ad content gen = requests.post(f"{BASE}/ai/generate/variations", headers=H, json={ "product\_description": "AI-powered project management for remote teams", "target\_audience": "Tech startups with 10-50 employees", "count": 5, "platform": "facebook", "include\_images": True, "tone": "professional" }).json() \# Wait for generation if async if gen.get("status") == "processing": while True: result = requests.get(f"{BASE}/ai/generations/{gen\['id'\]}", headers=H).json() if result\["status"\] == "completed": break time.sleep(5) gen = result \# 2. Create campaign campaign = requests.post(f"{BASE}/campaigns", headers=H, json={ "name": "Q3 Growth - Remote Teams", "objective": "conversions", "platforms": \["facebook", "instagram"\], "budget": {"type": "daily", "amount": 75, "currency": "USD"}, "schedule": {"start\_date": "2025-07-01", "end\_date": "2025-09-30"}, "optimization": {"enabled": True, "strategy": "maximize\_conversions", "frequency": "hourly"} }).json() \# 3. Create ad set ad\_set = requests.post(f"{BASE}/campaigns/{campaign\['id'\]}/ad-sets", headers=H, json={ "name": "US Tech Workers 25-45", "targeting": { "age\_min": 25, "age\_max": 45, "locations": \[{"type": "country", "value": "US"}\], "interests": \["remote work", "project management", "SaaS", "startups"\] } }).json() \# 4. Add ads from generated content for i, v in enumerate(gen\["result"\]\["variations"\]): requests.post( f"{BASE}/campaigns/{campaign\['id'\]}/ad-sets/{ad\_set\['id'\]}/ads", headers=H, json={ "name": f"Variation {i+1}", "creative": { "headline": v\["headline"\], "primary\_text": v\["primary\_text"\], "description": v\["description"\], "image\_url": v.get("image\_url"), "call\_to\_action": "sign\_up", "link\_url": "https://yourapp.com/signup" } } ) \# 5. Launch! requests.post(f"{BASE}/campaigns/{campaign\['id'\]}/launch", headers=H) print(f"Campaign {campaign\['id'\]} is live!") \# 6. Optimization loop while True: time.sleep(14400) \# Every 4 hours analytics = requests.get(f"{BASE}/analytics/campaigns/{campaign\['id'\]}", headers=H).json() if analytics\["metrics"\]\["ctr"\] < 1.5: suggestions = requests.post(f"{BASE}/ai/optimize/suggest", headers=H, json={ "campaign\_id": campaign\["id"\], "strategies": \["new\_message", "new\_image"\] }).json() for s in suggestions\["suggestions"\]: if s\["impact"\] == "high": print(f"Applying: {s\['description'\]}") \# Apply suggestion...
