Hey there, fellow Go developer! Ready to dive into the world of Facebook Marketing API? You're in for a treat. We'll be using the github.com/justwatch/facebook-marketing-api-golang-sdk
package to make our lives easier. This nifty SDK will help us navigate the sometimes choppy waters of API integration with ease.
Before we jump in, make sure you've got:
Let's get our hands dirty:
mkdir fb-marketing-api-project cd fb-marketing-api-project go mod init github.com/yourusername/fb-marketing-api-project go get github.com/justwatch/facebook-marketing-api-golang-sdk
Now, let's write some Go:
package main import ( "fmt" "github.com/justwatch/facebook-marketing-api-golang-sdk/fbapi" ) func main() { client := fbapi.NewClient("YOUR_ACCESS_TOKEN") // We'll use this client throughout our app }
accounts, err := client.AdAccount.List().Do() if err != nil { // Handle error } for _, account := range accounts { fmt.Printf("Account ID: %s, Name: %s\n", account.ID, account.Name) }
campaigns, err := client.Campaign.List().AdAccountID("act_123456789").Do() if err != nil { // Handle error } for _, campaign := range campaigns { fmt.Printf("Campaign ID: %s, Name: %s\n", campaign.ID, campaign.Name) }
adSet := &fbapi.AdSet{ Name: "My Awesome Ad Set", Campaign: &fbapi.Campaign{ID: "123456789"}, // Add other required fields } createdAdSet, err := client.AdSet.Create().Params(adSet).Do() if err != nil { // Handle error } fmt.Printf("Created Ad Set ID: %s\n", createdAdSet.ID)
The SDK handles pagination for you, but you can control it:
for page := client.AdAccount.List().Limit(100); page != nil; page = page.Next() { accounts, err := page.Do() if err != nil { // Handle error } // Process accounts }
The SDK includes built-in rate limiting, but always be prepared for errors:
_, err := client.Campaign.List().Do() if err != nil { if apiErr, ok := err.(*fbapi.APIError); ok { fmt.Printf("API Error: %s\n", apiErr.Message) } else { fmt.Printf("Unknown error: %v\n", err) } }
For efficiency, batch your requests:
batch := client.NewBatch() batch.Add(client.AdAccount.List()) batch.Add(client.Campaign.List().AdAccountID("act_123456789")) responses, err := batch.Do() // Process responses
For unit tests, use the SDK's mock client:
mockClient := fbapi.NewMockClient() mockClient.AdAccount.MockList([]fbapi.AdAccount{{ID: "123", Name: "Test Account"}}, nil) // Use mockClient in your tests
When debugging, enable verbose logging:
client.SetDebug(true)
Use environment variables for sensitive info:
accessToken := os.Getenv("FB_ACCESS_TOKEN") client := fbapi.NewClient(accessToken)
Don't forget to implement proper logging and monitoring in your production environment!
And there you have it! You're now equipped to build robust Facebook Marketing API integrations with Go. Remember, the API is vast, so don't be afraid to explore beyond what we've covered here. Happy coding, and may your campaigns be ever successful!