Hey there, fellow Go enthusiast! Ready to supercharge your marketing automation? Let's dive into building a Klaviyo API integration in Go. Klaviyo's powerful API lets you manage lists, subscribers, and events with ease. We'll cover the essentials, so buckle up!
Before we jump in, make sure you've got:
Let's kick things off:
mkdir klaviyo-integration cd klaviyo-integration go mod init github.com/yourusername/klaviyo-integration
Now, let's grab the HTTP client we'll use:
go get github.com/go-resty/resty/v2
Klaviyo uses API keys for authentication. Let's set that up:
package main import ( "github.com/go-resty/resty/v2" ) const ( baseURL = "https://a.klaviyo.com/api" apiKey = "your-api-key-here" ) func main() { client := resty.New(). SetBaseURL(baseURL). SetHeader("Authorization", "Klaviyo-API-Key "+apiKey) // We'll use this client for all our requests }
Let's try a GET request to fetch a list:
resp, err := client.R(). SetResult(&ListResponse{}). Get("/v2/lists") if err != nil { log.Fatalf("Error: %v", err) } lists := resp.Result().(*ListResponse) fmt.Printf("Found %d lists\n", len(lists.Data))
And a POST to create a new list:
resp, err := client.R(). SetBody(map[string]string{ "list_name": "My Awesome List", }). Post("/v2/lists") if err != nil { log.Fatalf("Error: %v", err) } fmt.Printf("List created with ID: %s\n", resp.String())
func getLists() ([]List, error) { // Implementation } func createList(name string) (string, error) { // Implementation }
func addSubscriber(listID, email string) error { // Implementation } func removeSubscriber(listID, email string) error { // Implementation }
func sendEmail(templateID string, recipients []string) error { // Implementation }
func trackEvent(event string, customerProperties map[string]interface{}) error { // Implementation }
Klaviyo has rate limits, so let's be good citizens:
func rateLimitedClient() *resty.Client { return resty.New(). SetBaseURL(baseURL). SetHeader("Authorization", "Klaviyo-API-Key "+apiKey). SetRetryCount(3). SetRetryWaitTime(5 * time.Second) }
Here's a quick unit test example:
func TestGetLists(t *testing.T) { lists, err := getLists() assert.NoError(t, err) assert.NotEmpty(t, lists) }
For integration tests, consider using a test API key and cleaning up after your tests.
And there you have it! You're now equipped to build a robust Klaviyo integration in Go. Remember, the Klaviyo API is vast, so don't hesitate to explore their docs for more advanced features. Happy coding, Gopher!