Marketing platforms like Facebook Ads organize campaigns in strict hierarchies - Campaigns contain Ad Sets, which contain Ads that reference Creatives. These complex relationships and dependencies make it challenging to build reliable automation. When creating campaigns programmatically, a single misstep in the object hierarchy can lead to validation errors, orphaned resources, or violated platform constraints.
This playbook shows how to build reliable marketing automation using Pydantic's validation and type safety. We transform Facebook's complex API into clean business objects where platform rules are enforced automatically - budget constraints cascade properly, campaigns must exist before Ad Sets, and content validation happens before any API calls.
The result is marketing automation that respects platform requirements while preventing expensive errors.
We will build a complete implementation that handles campaign creation from image upload to live ads - including budget validation, content safety checks, and proper execution ordering that prevents costly API errors.
🤖
This playbook focuses on building the foundational Pydantic interfaces that agents will use. We'll dive into creating agents that can autonomously run ads using these interfaces in upcoming tutorials.
Getting Facebook Marketing API Access
Before building agent tools, you need access to the Facebook Marketing API. To effectively utilize the Marketing API, users must follow some key steps to set up their environment and gain access to the API's features.
Prerequisites:
- An active ad account, which is not only for running campaigns but also for managing billing settings and setting spending limits
- A registered Meta developer account
- A Facebook app configured for marketing API access
Setup Steps:
- Register as Meta Developer: Create your developer account at developers.facebook.com if you don't have one already. Follow the Marketing API Getting Started guide for a complete walkthrough.
- Create a Facebook App: The app creation flow gathers the minimum amount of information needed to generate a unique ID for your app. Select "Business" as your app type to access marketing features. Detailed instructions are available in the Create an App documentation.
- Configure API Access: Business apps are automatically approved for standard access for all permissions and features available to the Business app type. For managing your own ad accounts, request
ads_read
and ads_management
permissions. See the Authorization guide for complete permission details. - Get Your Credentials: You'll need four key pieces of information for your
.env
file:META_ADS_TOKEN
: Your access token from the Graph API ExplorerMETA_APP_SECRET
: Your app secret from the App DashboardMETA_ADS_ACCOUNT_ID
: Your ad account ID (format: act_123456789
)META_PAGE_ID
: Your Facebook page ID
If your app is only managing your ad account, standard access to the ads_read and ads_management permissions are sufficient. This allows unlimited API calls for development and testing with your own ad accounts.
The Graph API Explorer provides the easiest way to generate access tokens and test API calls before implementing them in your agent tools.
Pydantic's Role in Agent Architecture
Pydantic serves as the contract layer between AI agents and marketing platforms. When agents need to create campaigns, they work with validated business objects rather than raw API calls. This transforms agent development from managing complex SDK methods to manipulating intuitive data structures.
The key insight is that Pydantic models become tool schemas for AI frameworks. In Pydantic AI, each model can be directly used as a tool parameter with built-in validation. In LangGraph, these models flow between workflow nodes as typed, validated objects that carry business logic and constraints.
Consider how an agent creates a Facebook campaign. Instead of learning Facebook's SDK patterns, the agent works with clean business concepts:
class FacebookObject(BaseModel):
"""Base class for all Facebook marketing objects with common validation"""
name: str = Field(..., min_length=1, max_length=100)
status: AdStatus = AdStatus.PAUSED # Safe default for all objects
class Campaign(FacebookObject):
"""Facebook Campaign with business rule validation"""
objective: str = "OUTCOME_TRAFFIC"
class AdSet(FacebookObject):
"""Facebook AdSet with budget constraints and targeting validation"""
daily_budget: int = Field(..., ge=100, description="Budget in cents (min $1.00)")
target_countries: List[str] = Field(["US"], min_items=1)
class Creative(FacebookObject):
"""Facebook Ad Creative with content validation and image handling"""
message: str = Field(..., min_length=1, max_length=500)
link_url: str
image_path: str
class Ad(FacebookObject):
"""Facebook Ad that references AdSet and Creative dependencies"""
# Inherits safe defaults and validation from FacebookObject
Agent Integration Patterns
These Pydantic models integrate seamlessly with AI agent frameworks through several key patterns: