klaviyo

package module
v0.0.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2025 License: MIT Imports: 18 Imported by: 0

README

Go Klaviyo API Client

This project provides a Go client for interacting with the Klaviyo API. It's a partial implementation, tailored to specific features that were required. It's designed to be simple, efficient, and idiomatic.

Features

  • Profile Management: Fetch, create, update, and delete profiles.
  • Built-in retry mechanisms for better reliability.
  • Structured error handling.
  • Easily extendable for additional endpoints.

Installation

go get -u github.com/monetha/go-klaviyo

Usage

First, create a client:

import "github.com/monetha/go-klaviyo"

client := klaviyo.New(API_KEY, logger)
Fetch Profiles
profiles, err := client.GetProfiles(ctx)
Create Profile
newProfile := &profile.NewProfile{
    // populate your profile data
}
createdProfile, err := client.CreateProfile(ctx, newProfile)
Fetch Profile by ID
fetchedProfile, err := client.GetProfile(ctx, PROFILE_ID)
Update Profile
updates := []updater.Profile{
    // your updaters
}
updatedProfile, err := client.UpdateProfile(ctx, PROFILE_ID, updates...)
Handling Errors

All errors returned by the client are structured. You can inspect the error to get more details:

if errors.Is(err, klaviyo.ErrProfileAlreadyExists) {
    // Handle specific error
}

Contributing

Contributions are welcome! Please feel free to submit a pull request, report an issue, or suggest additional features.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidAPIKey indicates that the provided Klaviyo API key is either not specified or invalid.
	ErrInvalidAPIKey = errors.New("klaviyo: invalid or missing API key")

	// ErrTooManyRequests is returned by the client method when the endpoint is retried
	// the maximum number of times defined by defaultRetryMax and still fails.
	ErrTooManyRequests = errors.New("klaviyo: too many requests for calling endpoint")

	// ErrProfileDoesNotExist indicates that an attempt was made to retrieve a profile
	// that does not exist in Klaviyo.
	ErrProfileDoesNotExist = errors.New("klaviyo: a profile does not exist")
)

Functions

This section is empty.

Types

type APIError

type APIError struct {
	Id     string `json:"id"`
	Status int    `json:"status"`
	Code   string `json:"code"`
	Title  string `json:"title"`
	Detail string `json:"detail"`
	Source struct {
		Pointer string `json:"pointer"`
	} `json:"source"`
	Meta struct {
		DuplicateProfileID string `json:"duplicate_profile_id,omitempty"`
	} `json:"meta,omitempty"`
}

APIError represents an error returned by the Klaviyo API.

func (*APIError) Error

func (e *APIError) Error() string

Error returns a human-readable representation of the APIError.

type BadHTTPResponseError

type BadHTTPResponseError struct {
	// contains filtered or unexported fields
}

BadHTTPResponseError represents an error due to a bad HTTP response.

func (*BadHTTPResponseError) Body

func (e *BadHTTPResponseError) Body() []byte

Body returns the body of the HTTP response.

func (*BadHTTPResponseError) Cause

func (e *BadHTTPResponseError) Cause() error

Cause returns the underlying cause of the error.

func (*BadHTTPResponseError) Error

func (e *BadHTTPResponseError) Error() string

Error returns a human-readable representation of the BadHTTPResponseError.

func (*BadHTTPResponseError) StatusCode

func (e *BadHTTPResponseError) StatusCode() int

StatusCode returns the HTTP status code of the response.

func (*BadHTTPResponseError) Unwrap

func (e *BadHTTPResponseError) Unwrap() error

Unwrap provides compatibility for Go's errors.Is() and errors.As() functions.

type BulkImportJobAttributes added in v0.0.9

type BulkImportJobAttributes struct {
	Profiles struct {
		Data []BulkProfileData `json:"data"`
	} `json:"profiles"`
}

BulkImportJobAttributes contains the profiles array for bulk import

type BulkImportJobResponse added in v0.0.9

type BulkImportJobResponse struct {
	Data struct {
		Type       string `json:"type"`
		ID         string `json:"id"`
		Attributes struct {
			Status         string     `json:"status"`
			CreatedAt      time.Time  `json:"created_at"`
			TotalCount     int        `json:"total_count"`
			CompletedCount int        `json:"completed_count"`
			FailedCount    int        `json:"failed_count"`
			CompletedAt    *time.Time `json:"completed_at"`
			ExpiresAt      time.Time  `json:"expires_at"`
			StartedAt      *time.Time `json:"started_at"`
		} `json:"attributes"`
	} `json:"data"`
}

BulkImportJobResponse represents the response from bulk import API

type BulkProfileAttributes added in v0.0.9

type BulkProfileAttributes struct {
	Email      string                 `json:"email,omitempty"`
	Properties map[string]interface{} `json:"properties,omitempty"`
	// Add other fields as needed
	PhoneNumber *string `json:"phone_number,omitempty"`
	ExternalId  *string `json:"external_id,omitempty"`
	FirstName   *string `json:"first_name,omitempty"`
	LastName    *string `json:"last_name,omitempty"`
}

BulkProfileAttributes represents a profile in a bulk import request

type BulkProfileData added in v0.0.9

type BulkProfileData struct {
	Type       string                `json:"type"`
	Attributes BulkProfileAttributes `json:"attributes"`
}

BulkProfileData represents a single profile in bulk import

type Client

type Client struct {
	APIKey string
	// contains filtered or unexported fields
}

Client represents a Klaviyo client with methods to interact with the Klaviyo API.

func New

func New(apiKey string, logger *zap.Logger) *Client

New initializes a new Klaviyo client with the default http client.

func NewWithClient

func NewWithClient(apiKey string, logger *zap.Logger, httpClient *http.Client) *Client

NewWithClient initializes a new Klaviyo client with a custom http client.

func (*Client) BulkCreateOrUpdateProfiles added in v0.0.9

func (c *Client) BulkCreateOrUpdateProfiles(
	ctx context.Context,
	profiles []BulkProfileAttributes,
) (string, error)

BulkCreateOrUpdateProfiles creates or updates multiple profiles using Klaviyo's bulk import API. This method submits up to 10,000 profiles in a single async job.

Parameters:

  • ctx: context for the request
  • profiles: slice of BulkProfileAttributes (max 10,000 profiles, max 5MB payload)

Returns:

  • job ID string for tracking the async job status
  • error if the submission fails

Example:

profiles := []klaviyo.BulkProfileAttributes{
    {
        Email: "user1@example.com",
        Properties: map[string]interface{}{
            "last_login_at": "2025-12-01T10:00:00Z",
        },
    },
    {
        Email: "user2@example.com",
        Properties: map[string]interface{}{
            "last_transaction_at": "2025-11-20T15:30:00Z",
        },
    },
}
jobID, err := client.BulkCreateOrUpdateProfiles(ctx, profiles)

func (*Client) CreateEvent added in v0.0.5

func (c *Client) CreateEvent(ctx context.Context, e *event.NewEvent, ID string, metricName string) error

CreateEvent creates a new event in Klaviyo.

func (*Client) CreateOrUpdateProfile added in v0.0.8

func (c *Client) CreateOrUpdateProfile(
	ctx context.Context,
	profileID string,
	updaters ...updater.Profile,
) (*profile.ExistingProfile, error)

CreateOrUpdateProfile creates a new profile or updates an existing one using Klaviyo’s POST /api/profile-import “upsert” endpoint.

Behaviour:

  • If profileID is an empty string the call is treated as a pure upsert: Klaviyo will look for a profile matching any identifiers contained in the supplied updaters and will update it, or create a new profile if none is found.

  • If profileID is non-empty the request explicitly targets that profile while still allowing identifier updates (email, phone, external_id…).

Only the attributes produced by the supplied updaters are sent; fields you don’t set are **omitted altogether**, guaranteeing we never clear data unintentionally (cf. “setting a field to null will clear it” in the API docs).

The method mirrors UpdateProfile’s signature so that callers can write:

    _, err := c.CreateOrUpdateProfile(
	    ctx,
	    klaviyoProfileID,   // "" if unknown
	    klaviyoProfile.ToUpdaters()...,
    )

func (*Client) CreateProfile

func (c *Client) CreateProfile(ctx context.Context, p *profile.NewProfile) (*profile.ExistingProfile, error)

CreateProfile creates a new profile in Klaviyo. If a profile with the same identifiers already exists, it will return ErrProfileAlreadyExists.

func (*Client) GetEvents added in v0.0.5

func (c *Client) GetEvents(ctx context.Context, params ...getprofiles.Param) ([]*event.ExistingEvent, error)

GetEvents retrieves a list of created events from Klaviyo.

func (*Client) GetProfile

func (c *Client) GetProfile(ctx context.Context, profileID string) (*profile.ExistingProfile, error)

GetProfile retrieves a specific profile by its ID from Klaviyo. If the profile with the given ID does not exist, it will return ErrProfileDoesNotExist.

func (*Client) GetProfiles

func (c *Client) GetProfiles(ctx context.Context, params ...getprofiles.Param) ([]*profile.ExistingProfile, error)

GetProfiles retrieves a list of created profiles from Klaviyo.

func (*Client) UpdateProfile

func (c *Client) UpdateProfile(ctx context.Context, profileID string, updaters ...updater.Profile) (*profile.ExistingProfile, error)

UpdateProfile updates a specific profile by its ID in Klaviyo.

type ErrProfileAlreadyExists

type ErrProfileAlreadyExists struct {
	DuplicateProfileID string
}

ErrProfileAlreadyExists indicates that an attempt was made to create a profile that already exists in Klaviyo. It holds the ID of the duplicate profile.

func (*ErrProfileAlreadyExists) Error added in v0.0.2

func (e *ErrProfileAlreadyExists) Error() string

Error returns a string representation of the ErrProfileAlreadyExists error. It conforms to the error interface.

Directories

Path Synopsis
internal
log
models
operations

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL