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": "[email protected]", "password": "yourSecurePassword", "first_name": "Jane", "last_name": "Smith" }' # Response: { "user": { "id": 5, "email": "[email protected]", "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": "[email protected]", "code": "482917" }' # Response: { "message": "Account verified successfully.", "user": { "id": 5, "email": "[email protected]", "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

PrefixEnvironmentUse
aa_live_ProductionReal campaigns, real spend
aa_test_SandboxTesting 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": "[email protected]", "password": "securePassword123", "first_name": "Jane", "last_name": "Smith" }

The response includes your API key immediately:

201 Created { "user": { "id": 5, "email": "[email protected]", "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": "[email protected]", "password": "securePassword123" } // Response: { "user": { "id": 5, "email": "[email protected]", "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": "[email protected]", "code": "482917" } // Response: { "message": "Account verified successfully.", "user": { "id": 5, "email": "[email protected]", "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": "[email protected]" }

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 [email protected]. 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 StateAPI AccessWhat You Can Do
Created (unverified)LimitedAuth & account endpoints only
Verified (Free)Free tierCreate business, campaigns, webhooks
Standard ($49/mo)FullExtended campaigns, AI content generation
Flexible ($199/mo)FullUnlimited 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

ObjectiveDescription
CONVERSIONSOptimize for purchases, signups, or other conversions
TRAFFICDrive visitors to your website or landing page
AWARENESSMaximize brand visibility and reach
ENGAGEMENTGet more likes, comments, and shares
LEADSCollect leads via forms
APP_INSTALLSDrive 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

DRAFTACTIVEPAUSEDCOMPLETED

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.

MethodEndpointDescription
GET/v1/analytics/overviewAccount-level summary
GET/v1/analytics/campaigns/{id}Campaign metrics (by platform, by ad set)
GET/v1/analytics/time-seriesTime-series data (hourly/daily/weekly)
POST/v1/analytics/reportsGenerate custom reports (JSON/CSV/PDF)
GET/v1/analytics/predictionsAI 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 [email protected]. 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

EventDescription
account.verifiedAccount verification completed
billing.payment_completedSubscription payment succeeded
billing.payment_failedPayment attempt failed
campaign.createdNew campaign created
campaign.launchedCampaign deployed to platforms
campaign.pausedCampaign paused
ad.optimizedAI replaced/modified ad creative
budget.reallocatedAI shifted budget between ad sets
generation.completedAI content generation finished
alert.spendSpend threshold reached
alert.performancePerformance 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

LimitFreeStarterGrowthAgency
Requests/min103060300
Requests/day5005,00010,000100,000
AI generations/mo1050500Unlimited

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

CodeMeaningWhen
200OKSuccessful request
201CreatedResource created
204No ContentSuccessful delete
400Bad RequestMalformed JSON
401UnauthorizedInvalid/missing API key
403ForbiddenUnverified or insufficient plan
404Not FoundResource doesn't exist
409ConflictEmail/phone already registered
422Validation ErrorInvalid field values
429Rate LimitedToo many requests
500Server ErrorRetry 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.

# 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 "[email protected]" 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 [email protected]. 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 [email protected] 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

ToolDescription
create_campaignCreate and configure a new ad campaign
generate_ad_contentGenerate AI-powered ad copy and images
launch_campaignDeploy a campaign to Facebook/Instagram
get_analyticsRetrieve campaign performance metrics
optimize_campaignGet and apply AI optimization suggestions
manage_budgetAdjust campaign budgets and allocation
list_campaignsView 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...