loops

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2026 License: MIT Imports: 10 Imported by: 0

README

loops-go

Go Reference

Go SDK for the Loops API.

Install

go get github.com/loops-so/loops-go

Quickstart

package main

import (
    "log"

    loops "github.com/loops-so/loops-go"
)

func main() {
    client := loops.NewClient("YOUR_API_KEY")

    err := client.SendEvent(loops.SendEventRequest{
        Email:     "[email protected]",
        EventName: "signup",
        EventProperties: map[string]any{
            "plan": "pro",
        },
    })
    if err != nil {
        log.Fatal(err)
    }
}

Client options

client := loops.NewClient("YOUR_API_KEY",
    loops.WithBaseURL("https://app.loops.so/api/v1"),
    loops.WithHTTPClient(myHTTPClient),
    loops.WithUserAgent("my-app/1.0"),
    loops.WithLogger(os.Stderr), // verbose request/response logging
)

Supported endpoints

  • API key — GetAPIKey
  • Contacts — CreateContact, UpdateContact, DeleteContact, FindContacts, CheckContactSuppression, RemoveContactSuppression
  • Contact properties — ListContactProperties, CreateContactProperty
  • Mailing lists — ListMailingLists
  • Audience segments — GetAudienceSegment, ListAudienceSegments
  • Events — SendEvent
  • Transactional — SendTransactional, ListTransactionals, CreateTransactional, GetTransactional, UpdateTransactional, EnsureTransactionalDraft, PublishTransactional
  • Transactional groups — CreateTransactionalGroup, GetTransactionalGroup, UpdateTransactionalGroup, ListTransactionalGroups
  • Email messages — GetEmailMessage, UpdateEmailMessage, PreviewEmailMessage
  • Campaigns — CreateCampaign, UpdateCampaign, GetCampaign, ListCampaigns
  • Campaign groups — CreateCampaignGroup, GetCampaignGroup, UpdateCampaignGroup, ListCampaignGroups
  • Components — GetComponent, ListComponents
  • Themes — GetTheme, ListThemes
  • Uploads — Upload, CreateUpload, CompleteUpload
  • Workflows — ListWorkflows, GetWorkflow, GetWorkflowNode

Full reference: pkg.go.dev/github.com/loops-so/loops-go.

Errors

API errors are returned as *loops.APIError with StatusCode and Message:

if err := client.SendEvent(req); err != nil {
    var apiErr *loops.APIError
    if errors.As(err, &apiErr) {
        log.Printf("loops api error %d: %s", apiErr.StatusCode, apiErr.Message)
    }
    return err
}

Retries

Requests are automatically retried with exponential backoff and jitter on 429 and 5xx responses (up to 2 retries).

Idempotency

SendEvent and SendTransactional accept an IdempotencyKey field, which is sent as the Idempotency-Key header.

Pagination

ListTransactionals and ListCampaigns return a single page of results along with a *Pagination value. Pass a PaginationParams to control page size and cursor:

items, page, err := client.ListTransactionals(loops.PaginationParams{PerPage: "50"})
if err != nil {
    log.Fatal(err)
}
// page.NextCursor is "" when there are no more pages.

To fetch every page, use the generic Paginate helper:

all, err := loops.Paginate(func(cursor string) ([]loops.Transactional, *loops.Pagination, error) {
    return client.ListTransactionals(loops.PaginationParams{Cursor: cursor})
})

Uploads

Upload is a one-call helper that requests a presigned URL, uploads the bytes, and finalizes the asset. Supported content types are image/jpeg, image/png, image/gif and image/webp, up to 4 MB.

f, err := os.Open("hero.png")
if err != nil {
    log.Fatal(err)
}
defer f.Close()
stat, err := f.Stat()
if err != nil {
    log.Fatal(err)
}

asset, err := client.Upload(loops.UploadRequest{
    EmailMessageID: "em_abc123",
    ContentType:    "image/png",
    ContentLength:  stat.Size(),
    Body:           f,
})
if err != nil {
    log.Fatal(err)
}
// asset.FinalURL is the public URL to reference in your email LMX.

For finer control, call CreateUpload and CompleteUpload directly and do the PUT to the presigned URL yourself.

Escape hatch

Client.Do is a low-level entry point for endpoints that do not yet have a dedicated method. It shares the client's auth, User-Agent, retries and backoff. The body is JSON-encoded when non-nil; pass json.RawMessage to forward a pre-encoded payload. The raw *http.Response is returned so the caller decides how to handle non-2xx — close the body when done.

resp, err := client.Do(ctx, http.MethodPost, "/contacts/create", map[string]any{
    "email": "[email protected]",
})
if err != nil {
    return err
}
defer resp.Body.Close()

License

MIT

Documentation

Overview

Package loops is the official Go SDK for the Loops API (https://loops.so).

It provides a Client for the Loops REST API, covering contacts, contact properties, mailing lists, events, transactional and campaign emails, email messages, components, and themes.

Construct a client with an API key from your Loops account, then call methods on it:

client := loops.NewClient("YOUR_API_KEY")

err := client.SendEvent(loops.SendEventRequest{
    Email:     "[email protected]",
    EventName: "signup",
})

Requests to 429 and 5xx responses are retried automatically with exponential backoff and jitter. API errors are returned as *APIError and can be inspected with errors.As.

Index

Constants

View Source
const (
	AudienceConditionTypeProperty = "property"
	AudienceConditionTypeOptIn    = "optIn"
	AudienceConditionTypeActivity = "activity"
)
View Source
const (
	WorkflowNodeTypeSignupTrigger          = "SignupTrigger"
	WorkflowNodeTypeEventTrigger           = "EventTrigger"
	WorkflowNodeTypeContactPropertyTrigger = "ContactPropertyTrigger"
	WorkflowNodeTypeAddToListTrigger       = "AddToListTrigger"
	WorkflowNodeTypeBlankTrigger           = "BlankTrigger"
	WorkflowNodeTypeAudienceFilter         = "AudienceFilter"
	WorkflowNodeTypeTimerAction            = "TimerAction"
	WorkflowNodeTypeSendEmailAction        = "SendEmailAction"
	WorkflowNodeTypeExitAction             = "ExitAction"
	WorkflowNodeTypeBranchNode             = "BranchNode"
	WorkflowNodeTypeExperimentBranchNode   = "ExperimentBranchNode"
	WorkflowNodeTypeVariantNode            = "VariantNode"
)

Workflow node typeName discriminator values, used in WorkflowNode and SimplifiedWorkflowNode.

View Source
const CampaignSchedulingMethodNow = "now"

CampaignSchedulingMethodNow means the campaign sends immediately when scheduled.

View Source
const CampaignSchedulingMethodSchedule = "schedule"

CampaignSchedulingMethodSchedule means the campaign sends at a specific time.

View Source
const DefaultBaseURL = "https://app.loops.so/api/v1"

DefaultBaseURL is the base URL for the Loops API used by NewClient when WithBaseURL is not supplied.

View Source
const EmailFormatPlain = "plain"

EmailFormatPlain is the rendered email format with no HTML styling.

View Source
const EmailFormatStyled = "styled"

EmailFormatStyled is the rendered email format with HTML styling.

Variables

View Source
var Version = readVersion()

Version is the loops-go module version, resolved from build info when the SDK is imported as a dependency. It falls back to "dev" when running from a local checkout (including this module's own tests) or when build info is otherwise unavailable. It is appended to the default User-Agent header sent by Client (e.g. "loops-go/v0.2.0").

Functions

func Paginate

func Paginate[T any](fetch func(cursor string) ([]T, *Pagination, error)) ([]T, error)

Paginate fetches every page from a paginated list endpoint by repeatedly calling fetch with the previous page's NextCursor, and returns all items concatenated together. Use it with list methods like Client.ListTransactional and Client.ListCampaigns:

all, err := loops.Paginate(func(cursor string) ([]loops.TransactionalEmail, *loops.Pagination, error) {
    return client.ListTransactional(loops.PaginationParams{Cursor: cursor})
})

Types

type APIError

type APIError struct {
	StatusCode int
	Message    string
}

APIError is returned by Client methods when the Loops API responds with a non-2xx status. Use errors.As to inspect the status code and message:

var apiErr *loops.APIError
if errors.As(err, &apiErr) {
    log.Printf("loops api error %d: %s", apiErr.StatusCode, apiErr.Message)
}

func (*APIError) Error

func (e *APIError) Error() string

Error returns the API error message.

type APIKeyResponse

type APIKeyResponse struct {
	TeamName string `json:"teamName"`
}

APIKeyResponse is returned by Client.GetAPIKey and identifies the team the API key belongs to.

type ActivityCondition added in v0.3.0

type ActivityCondition struct {
	Action string `json:"action"`
	Negate bool   `json:"negate"`
	Target string `json:"target"`
	ID     string `json:"id"`
}

ActivityCondition matches contacts by their activity on a campaign, workflow, or workflow email.

type AddToListTriggerWorkflowNode added in v0.3.1

type AddToListTriggerWorkflowNode struct {
	ID          string   `json:"id"`
	WorkflowID  string   `json:"workflowId"`
	NextNodeIDs []string `json:"nextNodeIds"`
	ReEligible  bool     `json:"reEligible"`
}

AddToListTriggerWorkflowNode is the AddToListTrigger variant of WorkflowNode.

type Attachment

type Attachment struct {
	Filename    string `json:"filename"`
	ContentType string `json:"contentType"`
	Data        string `json:"data"`
}

Attachment is a file attached to a transactional email. Data must be the file contents encoded as a base64 string.

type AudienceFilter added in v0.3.0

type AudienceFilter struct {
	Match      string                    `json:"match"`
	Conditions []AudienceFilterCondition `json:"conditions"`
}

AudienceFilter is a tree of AudienceFilterCondition values combined with Match ("all" or "any"). Used by AudienceSegment and by campaign targeting.

type AudienceFilterCondition added in v0.3.0

type AudienceFilterCondition struct {
	Type     string
	Property *PropertyCondition
	OptIn    *OptInCondition
	Activity *ActivityCondition
}

AudienceFilterCondition is one node in an AudienceFilter tree. Exactly one of Property, OptIn, or Activity is set; Type is the discriminator and matches the variant ("property", "optIn", or "activity").

The condition (de)serializes as a flat object with a "type" field — the variant fields are inlined, not nested.

func (AudienceFilterCondition) MarshalJSON added in v0.3.0

func (c AudienceFilterCondition) MarshalJSON() ([]byte, error)

MarshalJSON encodes the active variant inline with a "type" discriminator.

func (*AudienceFilterCondition) UnmarshalJSON added in v0.3.0

func (c *AudienceFilterCondition) UnmarshalJSON(data []byte) error

UnmarshalJSON dispatches on "type" and decodes the matching variant.

type AudienceFilterWorkflowNode added in v0.3.1

type AudienceFilterWorkflowNode struct {
	ID                string          `json:"id"`
	WorkflowID        string          `json:"workflowId"`
	NextNodeIDs       []string        `json:"nextNodeIds"`
	AudienceFilter    *AudienceFilter `json:"audienceFilter,omitempty"`
	AudienceSegmentID string          `json:"audienceSegmentId,omitempty"`
}

AudienceFilterWorkflowNode is the AudienceFilter variant of WorkflowNode. AudienceFilter reuses the package-level AudienceFilter type.

type AudienceSegment added in v0.3.0

type AudienceSegment struct {
	ID          string          `json:"id"`
	Name        string          `json:"name"`
	Description *string         `json:"description"`
	CreatedAt   string          `json:"createdAt"`
	UpdatedAt   string          `json:"updatedAt"`
	Filter      *AudienceFilter `json:"filter"`
}

AudienceSegment is a saved audience filter. The Filter is null for the reserved "All contacts" segment.

type BlankTriggerWorkflowNode added in v0.3.1

type BlankTriggerWorkflowNode struct {
	ID          string   `json:"id"`
	WorkflowID  string   `json:"workflowId"`
	NextNodeIDs []string `json:"nextNodeIds"`
}

BlankTriggerWorkflowNode is the BlankTrigger variant of WorkflowNode.

type BranchWorkflowNode added in v0.3.1

type BranchWorkflowNode struct {
	ID           string   `json:"id"`
	WorkflowID   string   `json:"workflowId"`
	NextNodeIDs  []string `json:"nextNodeIds"`
	EvalStrategy string   `json:"evalStrategy,omitempty"`
}

BranchWorkflowNode is the BranchNode variant of WorkflowNode.

type Campaign

type Campaign struct {
	ID                string             `json:"id"`
	EmailMessageID    *string            `json:"emailMessageId"`
	Name              string             `json:"name"`
	Status            string             `json:"status"`
	CreatedAt         string             `json:"createdAt"`
	UpdatedAt         string             `json:"updatedAt"`
	CampaignGroupID   *string            `json:"campaignGroupId"`
	MailingListID     *string            `json:"mailingListId"`
	AudienceSegmentID *string            `json:"audienceSegmentId"`
	AudienceFilter    *AudienceFilter    `json:"audienceFilter"`
	Scheduling        CampaignScheduling `json:"scheduling"`
}

Campaign describes a campaign, as returned by Client.GetCampaign, Client.UpdateCampaign, and Client.ListCampaigns. A campaign holds a single EmailMessage linked via EmailMessageID.

type CampaignCreateResponse

type CampaignCreateResponse struct {
	Campaign
	EmailMessageContentRevisionID *string `json:"emailMessageContentRevisionId"`
}

CampaignCreateResponse is returned by Client.CreateCampaign. It embeds the new Campaign and adds the initial content-revision ID for the campaign's email message.

type CampaignListItem deprecated

type CampaignListItem = Campaign

CampaignListItem is the entry shape returned by Client.ListCampaigns.

Deprecated: list items are now full Campaign values; use Campaign directly. CampaignListItem is retained as an alias.

type CampaignScheduling added in v0.3.0

type CampaignScheduling struct {
	Method    string  `json:"method"`
	Timestamp *string `json:"timestamp"`
}

CampaignScheduling describes when a campaign is scheduled to send. Timestamp is nil when Method is CampaignSchedulingMethodNow.

type CampaignSchedulingRequest added in v0.3.0

type CampaignSchedulingRequest struct {
	Method    string `json:"method"`
	Timestamp string `json:"timestamp,omitempty"`
}

CampaignSchedulingRequest sets when a campaign should send. Timestamp is required (and must be in the future) when Method is CampaignSchedulingMethodSchedule, and must be empty when Method is CampaignSchedulingMethodNow.

type Client

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

Client is a Loops API client. Construct one with NewClient. A Client is safe for concurrent use by multiple goroutines.

func NewClient

func NewClient(apiKey string, opts ...Option) *Client

NewClient returns a new Client authenticated with the given API key. Apply zero or more Option values to override defaults.

func (*Client) CheckContactSuppression

func (c *Client) CheckContactSuppression(email, userID string) (*ContactSuppression, error)

CheckContactSuppression reports whether the contact identified by email or user ID is currently suppressed.

func (*Client) CompleteUpload added in v0.1.4

func (c *Client) CompleteUpload(id string) (*CompleteUploadResponse, error)

CompleteUpload finalizes an asset previously created with Client.CreateUpload after its bytes have been PUT to the presigned URL. The id argument is the EmailAssetID returned by CreateUpload.

func (*Client) CreateCampaign

func (c *Client) CreateCampaign(req CreateCampaignRequest) (*CampaignCreateResponse, error)

CreateCampaign creates a new campaign and an empty email message attached to it.

func (*Client) CreateCampaignGroup added in v0.3.0

func (c *Client) CreateCampaignGroup(req CreateGroupRequest) (*Group, error)

CreateCampaignGroup creates a new campaign group.

func (*Client) CreateContact

func (c *Client) CreateContact(req CreateContactRequest) (string, error)

CreateContact creates a new contact and returns the new contact's ID.

func (*Client) CreateContactProperty

func (c *Client) CreateContactProperty(name, propType string) error

CreateContactProperty creates a new custom contact property with the given name and type (e.g. "string", "number", "boolean", "date").

func (*Client) CreateTransactional added in v0.2.0

func (c *Client) CreateTransactional(req CreateTransactionalRequest) (*TransactionalDraft, error)

CreateTransactional creates a new transactional email with an empty draft email message. Use Client.UpdateEmailMessage on the returned DraftEmailMessageID to set the subject, sender, and LMX content, then call Client.PublishTransactional to publish.

func (*Client) CreateTransactionalGroup added in v0.3.0

func (c *Client) CreateTransactionalGroup(req CreateGroupRequest) (*Group, error)

CreateTransactionalGroup creates a new transactional-email group.

func (*Client) CreateUpload added in v0.1.4

func (c *Client) CreateUpload(req CreateUploadRequest) (*CreateUploadResponse, error)

CreateUpload reserves an asset slot on the account and returns a presigned S3 URL the caller must PUT the asset bytes to. After a successful PUT, call Client.CompleteUpload to finalize the asset. Most callers should use Client.Upload instead, which performs all three steps.

func (*Client) DeleteContact

func (c *Client) DeleteContact(email, userID string) error

DeleteContact deletes a contact identified by email or user ID. One of the two must be non-empty.

func (*Client) Do added in v0.3.1

func (c *Client) Do(ctx context.Context, method, path string, body any) (*http.Response, error)

Do executes an arbitrary request against the Loops API. The request is built against the configured base URL with the Authorization and User-Agent headers attached, body is JSON-encoded when non-nil, and the call runs through the shared retry/backoff plumbing. Callers are responsible for closing the returned response body.

Do is an escape hatch for endpoints that do not yet have a dedicated method, or for callers that want to share this client's retries and User-Agent. Non-2xx responses are returned as-is — inspect resp.StatusCode and decode the body to suit. Transport errors are wrapped, matching the behavior of the higher-level methods.

To send a pre-encoded JSON payload without re-marshaling, pass a json.RawMessage.

func (*Client) EnsureTransactionalDraft added in v0.2.0

func (c *Client) EnsureTransactionalDraft(id string) (*TransactionalDraft, error)

EnsureTransactionalDraft ensures the transactional email has a draft email message. If a draft already exists it is returned unchanged; otherwise a new empty draft is created (seeded from the most recent published version when present).

func (*Client) FindContacts

func (c *Client) FindContacts(params FindContactParams) ([]Contact, error)

FindContacts looks up contacts by email or user ID. The result is a slice because the underlying endpoint may return multiple matches; in typical use it contains zero or one entry.

func (*Client) GetAPIKey

func (c *Client) GetAPIKey() (*APIKeyResponse, error)

GetAPIKey verifies the client's API key and returns information about the team it belongs to. Useful as a connectivity check at startup.

func (*Client) GetAudienceSegment added in v0.3.0

func (c *Client) GetAudienceSegment(id string) (*AudienceSegment, error)

GetAudienceSegment returns the audience segment identified by id.

func (*Client) GetCampaign

func (c *Client) GetCampaign(id string) (*Campaign, error)

GetCampaign returns the campaign identified by id.

func (*Client) GetCampaignGroup added in v0.3.0

func (c *Client) GetCampaignGroup(id string) (*Group, error)

GetCampaignGroup returns the campaign group identified by id.

func (*Client) GetComponent added in v0.1.2

func (c *Client) GetComponent(id string) (*Component, error)

GetComponent returns the component identified by id.

func (*Client) GetDedicatedSendingIPs added in v0.3.0

func (c *Client) GetDedicatedSendingIPs() ([]string, error)

GetDedicatedSendingIPs returns the dedicated sending IP addresses assigned to the team. Returns an empty slice when no dedicated IPs are assigned.

func (*Client) GetEmailMessage

func (c *Client) GetEmailMessage(id string) (*EmailMessage, error)

GetEmailMessage returns the email message identified by id.

func (*Client) GetTheme added in v0.1.3

func (c *Client) GetTheme(id string) (*Theme, error)

GetTheme returns the theme identified by id.

func (*Client) GetTransactional added in v0.2.0

func (c *Client) GetTransactional(id string) (*Transactional, error)

GetTransactional returns the transactional email identified by id.

func (*Client) GetTransactionalGroup added in v0.3.0

func (c *Client) GetTransactionalGroup(id string) (*Group, error)

GetTransactionalGroup returns the transactional-email group identified by id.

func (*Client) GetWorkflow added in v0.3.1

func (c *Client) GetWorkflow(id string) (*SimplifiedWorkflow, error)

GetWorkflow returns the simplified workflow graph identified by id.

func (*Client) GetWorkflowNode added in v0.3.1

func (c *Client) GetWorkflowNode(workflowID, nodeID string) (*WorkflowNode, error)

GetWorkflowNode returns the detailed data for a single workflow node.

func (*Client) ListAudienceSegments added in v0.3.0

func (c *Client) ListAudienceSegments(params PaginationParams) ([]AudienceSegment, *Pagination, error)

ListAudienceSegments returns a single page of audience segments along with pagination information. To iterate every page, use Paginate.

func (*Client) ListCampaignGroups added in v0.3.0

func (c *Client) ListCampaignGroups(params PaginationParams) ([]Group, *Pagination, error)

ListCampaignGroups returns a single page of campaign groups along with pagination information. To iterate every page, use Paginate.

func (*Client) ListCampaigns

func (c *Client) ListCampaigns(params PaginationParams) ([]Campaign, *Pagination, error)

ListCampaigns returns a single page of campaigns along with pagination information. To iterate every page, use Paginate.

func (*Client) ListComponents added in v0.1.2

func (c *Client) ListComponents(params PaginationParams) ([]Component, *Pagination, error)

ListComponents returns a single page of components along with pagination information. To iterate every page, use Paginate.

func (*Client) ListContactProperties

func (c *Client) ListContactProperties(customOnly bool) ([]ContactProperty, error)

ListContactProperties returns the contact properties defined on your account. If customOnly is true, only custom properties are returned; otherwise built-in properties are included as well.

func (*Client) ListMailingLists

func (c *Client) ListMailingLists() ([]MailingList, error)

ListMailingLists returns every mailing list defined on your account.

func (*Client) ListThemes added in v0.1.3

func (c *Client) ListThemes(params PaginationParams) ([]Theme, *Pagination, error)

ListThemes returns a single page of themes along with pagination information. To iterate every page, use Paginate.

func (*Client) ListTransactional deprecated

func (c *Client) ListTransactional(params PaginationParams) ([]TransactionalEmail, *Pagination, error)

ListTransactional returns a single page of transactional email templates along with pagination information. To iterate every page, use Paginate:

all, err := loops.Paginate(func(cursor string) ([]loops.TransactionalEmail, *loops.Pagination, error) {
    return client.ListTransactional(loops.PaginationParams{Cursor: cursor})
})

Deprecated: use Client.ListTransactionals, which returns the richer Transactional shape (draft and published email message IDs, separate created/updated timestamps).

func (*Client) ListTransactionalGroups added in v0.3.0

func (c *Client) ListTransactionalGroups(params PaginationParams) ([]Group, *Pagination, error)

ListTransactionalGroups returns a single page of transactional-email groups along with pagination information. To iterate every page, use Paginate.

func (*Client) ListTransactionals added in v0.2.0

func (c *Client) ListTransactionals(params PaginationParams) ([]Transactional, *Pagination, error)

ListTransactionals returns a single page of transactional emails along with pagination information. To iterate every page, use Paginate.

func (*Client) ListWorkflows added in v0.3.1

func (c *Client) ListWorkflows(params PaginationParams) ([]WorkflowSummary, *Pagination, error)

ListWorkflows returns a single page of workflow summaries along with pagination information. To iterate every page, use Paginate.

func (*Client) PreviewEmailMessage added in v0.3.0

func (c *Client) PreviewEmailMessage(id string, req EmailMessagePreviewRequest) (*EmailMessagePreviewResponse, error)

PreviewEmailMessage sends a test preview of the email message identified by id to the addresses in req.Emails. See EmailMessagePreviewRequest for the allowed variable fields by parent type.

func (*Client) PublishTransactional added in v0.2.0

func (c *Client) PublishTransactional(id string) (*Transactional, error)

PublishTransactional publishes the transactional email's current draft email message. The draft becomes the published version and the draft is cleared.

func (*Client) RemoveContactSuppression

func (c *Client) RemoveContactSuppression(email, userID string) (*ContactSuppressionRemoval, error)

RemoveContactSuppression removes a contact from the suppression list, allowing future sends to them. Removals count against a monthly quota reported in the response.

func (*Client) SendEvent

func (c *Client) SendEvent(req SendEventRequest) error

SendEvent sends an event to Loops, optionally updating contact properties and mailing-list memberships at the same time. See SendEventRequest for field semantics.

func (*Client) SendTransactional

func (c *Client) SendTransactional(req SendTransactionalRequest) error

SendTransactional sends a transactional email. See SendTransactionalRequest for field semantics.

func (*Client) UpdateCampaign

func (c *Client) UpdateCampaign(id string, req UpdateCampaignRequest) (*Campaign, error)

UpdateCampaign updates the campaign identified by id with the fields selected in req.Set and returns its new state. See UpdateCampaignRequest for the selection semantics.

func (*Client) UpdateCampaignGroup added in v0.3.0

func (c *Client) UpdateCampaignGroup(id string, req UpdateGroupRequest) (*Group, error)

UpdateCampaignGroup updates the campaign group identified by id.

func (*Client) UpdateContact

func (c *Client) UpdateContact(req UpdateContactRequest) error

UpdateContact updates an existing contact, identified by email or user ID.

func (*Client) UpdateEmailMessage

func (c *Client) UpdateEmailMessage(id string, req UpdateEmailMessageRequest) (*EmailMessage, error)

UpdateEmailMessage updates the email message identified by id with the fields selected in req.Set and returns its new state. See UpdateEmailMessageRequest for the selection semantics.

func (*Client) UpdateTransactional added in v0.2.0

func (c *Client) UpdateTransactional(id string, req UpdateTransactionalRequest) (*Transactional, error)

UpdateTransactional updates the transactional email identified by id and returns its new state.

func (*Client) UpdateTransactionalGroup added in v0.3.0

func (c *Client) UpdateTransactionalGroup(id string, req UpdateGroupRequest) (*Group, error)

UpdateTransactionalGroup updates the transactional-email group identified by id.

func (*Client) Upload added in v0.1.4

func (c *Client) Upload(req UploadRequest) (*CompleteUploadResponse, error)

Upload performs the full three-step asset upload: it calls Client.CreateUpload to obtain a presigned URL, PUTs req.Body to that URL using the SDK's HTTP client, and finalizes the asset with Client.CompleteUpload. The PUT to S3 deliberately does not carry the Loops Authorization header. On success the returned FinalURL is the public URL of the uploaded asset.

type CompleteUploadResponse added in v0.1.4

type CompleteUploadResponse struct {
	EmailAssetID string `json:"emailAssetId"`
	FinalURL     string `json:"finalUrl"`
}

CompleteUploadResponse is returned by Client.CompleteUpload and Client.Upload. FinalURL is the permanent, publicly addressable URL for the asset, suitable for referencing in email content.

type Component added in v0.1.2

type Component struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	LMX  string `json:"lmx"`
}

Component is a reusable LMX snippet that can be included from other email messages. It is identified by ID and has an LMX body.

type Contact

type Contact struct {
	ID           string          `json:"id"`
	Email        string          `json:"email"`
	FirstName    *string         `json:"firstName"`
	LastName     *string         `json:"lastName"`
	Source       string          `json:"source"`
	Subscribed   bool            `json:"subscribed"`
	UserGroup    string          `json:"userGroup"`
	UserID       *string         `json:"userId"`
	MailingLists map[string]bool `json:"mailingLists"`
	OptInStatus  *string         `json:"optInStatus"`
	Custom       map[string]any  `json:"-"`
}

Contact represents a contact in Loops, as returned by Client.FindContacts.

Custom collects any fields returned by the API that are not part of the fixed schema (for example, custom contact properties defined on your account). They are populated by UnmarshalJSON and re-emitted by MarshalJSON.

func (Contact) MarshalJSON

func (c Contact) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler and merges Contact.Custom into the top-level JSON object.

func (*Contact) UnmarshalJSON

func (c *Contact) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler and collects unknown fields into Contact.Custom.

type ContactProperty

type ContactProperty struct {
	Key   string `json:"key"`
	Label string `json:"label"`
	Type  string `json:"type"`
}

ContactProperty describes a property defined on a contact: its API key, human-readable label, and value type (e.g. "string", "number", "boolean", "date").

type ContactPropertyTriggerWorkflowNode added in v0.3.1

type ContactPropertyTriggerWorkflowNode struct {
	ID                   string                        `json:"id"`
	WorkflowID           string                        `json:"workflowId"`
	NextNodeIDs          []string                      `json:"nextNodeIds"`
	ContactPropertyQuery *WorkflowContactPropertyQuery `json:"contactPropertyQuery"`
	ReEligible           bool                          `json:"reEligible"`
}

ContactPropertyTriggerWorkflowNode is the ContactPropertyTrigger variant of WorkflowNode. ContactPropertyQuery is required by the spec but may be null.

type ContactSuppression

type ContactSuppression struct {
	Contact struct {
		ID     string  `json:"id"`
		Email  string  `json:"email"`
		UserID *string `json:"userId"`
	} `json:"contact"`
	IsSuppressed bool `json:"isSuppressed"`
	RemovalQuota struct {
		Limit     int `json:"limit"`
		Remaining int `json:"remaining"`
	} `json:"removalQuota"`
}

ContactSuppression is returned by Client.CheckContactSuppression and reports whether a contact is currently suppressed (e.g. bounced or complained) along with your remaining suppression-removal quota.

type ContactSuppressionRemoval

type ContactSuppressionRemoval struct {
	Success      bool   `json:"success"`
	Message      string `json:"message"`
	RemovalQuota struct {
		Limit     int `json:"limit"`
		Remaining int `json:"remaining"`
	} `json:"removalQuota"`
}

ContactSuppressionRemoval is returned by Client.RemoveContactSuppression and reports the result of the removal along with your remaining quota.

type CreateCampaignRequest

type CreateCampaignRequest struct {
	Name              string                     `json:"name"`
	CampaignGroupID   string                     `json:"campaignGroupId,omitempty"`
	MailingListID     *string                    `json:"mailingListId,omitempty"`
	AudienceSegmentID *string                    `json:"audienceSegmentId,omitempty"`
	AudienceFilter    *AudienceFilter            `json:"audienceFilter,omitempty"`
	Scheduling        *CampaignSchedulingRequest `json:"scheduling,omitempty"`
}

CreateCampaignRequest is the request body for Client.CreateCampaign. MailingListID and AudienceSegmentID are pointer-typed: leave nil to omit, or set to a pointer to a string value.

type CreateContactRequest

type CreateContactRequest struct {
	Email             string
	FirstName         string
	LastName          string
	Source            string
	Subscribed        *bool
	UserGroup         string
	UserID            string
	MailingLists      map[string]bool
	ContactProperties map[string]any
}

CreateContactRequest is the request body for Client.CreateContact.

Email is required. Subscribed is a pointer so the zero value (unset) is distinguishable from an explicit false. ContactProperties carries any custom properties defined on your Loops account.

type CreateGroupRequest added in v0.3.0

type CreateGroupRequest struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
}

CreateGroupRequest is the request body for Client.CreateCampaignGroup and Client.CreateTransactionalGroup. Name cannot be the reserved value "Unsorted".

type CreateTransactionalRequest added in v0.2.0

type CreateTransactionalRequest struct {
	Name                 string `json:"name"`
	TransactionalGroupID string `json:"transactionalGroupId,omitempty"`
}

CreateTransactionalRequest is the request body for Client.CreateTransactional.

type CreateUploadRequest added in v0.1.4

type CreateUploadRequest struct {
	ContentType   string `json:"contentType"`
	ContentLength int64  `json:"contentLength"`
}

CreateUploadRequest is the request body for Client.CreateUpload. The API restricts ContentType to a small set of image types (currently image/jpeg, image/png, image/gif and image/webp) and enforces a maximum ContentLength; see the Loops API docs for the current limits.

type CreateUploadResponse added in v0.1.4

type CreateUploadResponse struct {
	EmailAssetID string `json:"emailAssetId"`
	PresignedURL string `json:"presignedUrl"`
}

CreateUploadResponse is returned by Client.CreateUpload. PresignedURL is a short-lived S3 URL that the caller must PUT the asset bytes to before calling Client.CompleteUpload with EmailAssetID.

type EmailMessage

type EmailMessage struct {
	ID                         string            `json:"id"`
	CampaignID                 *string           `json:"campaignId,omitempty"`
	TransactionalID            *string           `json:"transactionalId,omitempty"`
	Subject                    string            `json:"subject"`
	PreviewText                string            `json:"previewText"`
	FromName                   string            `json:"fromName"`
	FromEmail                  string            `json:"fromEmail"`
	ReplyToEmail               string            `json:"replyToEmail"`
	CCEmail                    string            `json:"ccEmail,omitempty"`
	BCCEmail                   string            `json:"bccEmail,omitempty"`
	LanguageCode               string            `json:"languageCode,omitempty"`
	EmailFormat                string            `json:"emailFormat"`
	LMX                        string            `json:"lmx"`
	ContentRevisionID          *string           `json:"contentRevisionId"`
	UpdatedAt                  string            `json:"updatedAt"`
	ContactPropertiesFallbacks map[string]string `json:"contactPropertiesFallbacks,omitempty"`
	EventPropertiesFallbacks   map[string]string `json:"eventPropertiesFallbacks,omitempty"`
	DataVariablesFallbacks     map[string]string `json:"dataVariablesFallbacks,omitempty"`
	Warnings                   []LmxWarning      `json:"warnings,omitempty"`
}

EmailMessage is the persisted form of an email's content and metadata, including its LMX body. Warnings is populated by the LMX linter when the message is fetched or updated.

CampaignID and TransactionalID are mutually exclusive — exactly one is non-nil and identifies the parent.

type EmailMessageFields

type EmailMessageFields struct {
	Subject                    string             `json:"subject,omitempty"`
	PreviewText                string             `json:"previewText,omitempty"`
	FromName                   string             `json:"fromName,omitempty"`
	FromEmail                  string             `json:"fromEmail,omitempty"`
	ReplyToEmail               string             `json:"replyToEmail,omitempty"`
	CCEmail                    string             `json:"ccEmail,omitempty"`
	BCCEmail                   string             `json:"bccEmail,omitempty"`
	LanguageCode               string             `json:"languageCode,omitempty"`
	EmailFormat                string             `json:"emailFormat,omitempty"`
	LMX                        string             `json:"lmx,omitempty"`
	ContactPropertiesFallbacks map[string]*string `json:"contactPropertiesFallbacks,omitempty"`
	EventPropertiesFallbacks   map[string]*string `json:"eventPropertiesFallbacks,omitempty"`
	DataVariablesFallbacks     map[string]*string `json:"dataVariablesFallbacks,omitempty"`
}

EmailMessageFields holds the editable fields of an email message. It is embedded in UpdateEmailMessageRequest; the request's Set map determines which fields are actually written.

type EmailMessagePreviewRequest added in v0.3.0

type EmailMessagePreviewRequest struct {
	Emails            []string          `json:"emails"`
	ContactProperties map[string]string `json:"contactProperties,omitempty"`
	EventProperties   map[string]string `json:"eventProperties,omitempty"`
	DataVariables     map[string]any    `json:"dataVariables,omitempty"`
}

EmailMessagePreviewRequest is the request body for Client.PreviewEmailMessage. The accepted variable fields depend on the parent email message's type:

  • campaign previews accept ContactProperties
  • workflow previews accept ContactProperties and EventProperties
  • transactional previews accept DataVariables

type EmailMessagePreviewResponse added in v0.3.0

type EmailMessagePreviewResponse struct {
	ID string `json:"id"`
}

EmailMessagePreviewResponse is returned by Client.PreviewEmailMessage. ID is the email message ID the preview was sent for.

type EventTriggerWorkflowNode added in v0.3.1

type EventTriggerWorkflowNode struct {
	ID              string                  `json:"id"`
	WorkflowID      string                  `json:"workflowId"`
	NextNodeIDs     []string                `json:"nextNodeIds"`
	EventName       *string                 `json:"eventName"`
	EventProperties []WorkflowEventProperty `json:"eventProperties,omitempty"`
	ReEligible      bool                    `json:"reEligible"`
}

EventTriggerWorkflowNode is the EventTrigger variant of WorkflowNode. EventName is nullable; EventProperties may be empty.

type ExitActionWorkflowNode added in v0.3.1

type ExitActionWorkflowNode struct {
	ID          string   `json:"id"`
	WorkflowID  string   `json:"workflowId"`
	NextNodeIDs []string `json:"nextNodeIds"`
}

ExitActionWorkflowNode is the ExitAction variant of WorkflowNode.

type ExperimentBranchWorkflowNode added in v0.3.1

type ExperimentBranchWorkflowNode struct {
	ID             string                 `json:"id"`
	WorkflowID     string                 `json:"workflowId"`
	NextNodeIDs    []string               `json:"nextNodeIds"`
	SamplingRate   float64                `json:"samplingRate"`
	URL            string                 `json:"url,omitempty"`
	ExperimentID   string                 `json:"experimentId,omitempty"`
	ExperimentType WorkflowExperimentType `json:"experimentType"`
}

ExperimentBranchWorkflowNode is the ExperimentBranchNode variant of WorkflowNode.

type FindContactParams

type FindContactParams struct {
	Email  string
	UserID string
}

FindContactParams is the query for Client.FindContacts. One of Email or UserID must be set.

type Group added in v0.3.0

type Group struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	CreatedAt   string `json:"createdAt"`
	UpdatedAt   string `json:"updatedAt"`
}

Group is a campaign or transactional-email group. Each team has a reserved "Unsorted" group that cannot be renamed or edited.

type LmxWarning

type LmxWarning struct {
	Rule     string `json:"rule"`
	Severity string `json:"severity"`
	Message  string `json:"message"`
	Path     string `json:"path,omitempty"`
}

LmxWarning is a non-fatal issue reported by the Loops Markup (LMX) linter when validating email content. Severity is typically "warning" or "info".

type MailingList

type MailingList struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	IsPublic    bool   `json:"isPublic"`
}

MailingList describes a mailing list defined on your Loops account. Use its ID as the key in the mailingLists map on contact and event requests.

type OptInCondition added in v0.3.0

type OptInCondition struct {
	Status *string `json:"status"`
}

OptInCondition matches contacts by their opt-in status on a mailing list. Status may be "accepted", "pending", "rejected", or nil for any.

type Option

type Option func(*Client)

Option configures a Client. Pass options to NewClient.

func WithBaseURL

func WithBaseURL(u string) Option

WithBaseURL overrides the API base URL used by the Client. Most callers do not need this; the default is DefaultBaseURL.

func WithHTTPClient

func WithHTTPClient(h *http.Client) Option

WithHTTPClient replaces the underlying *http.Client used to make requests. Use this to configure custom timeouts, transports, or proxies. The default client has a 5 second timeout.

func WithLogger

func WithLogger(w io.Writer) Option

WithLogger enables verbose request and response logging to w. The Authorization header is redacted. Intended for debugging only.

func WithUserAgent

func WithUserAgent(ua string) Option

WithUserAgent sets the User-Agent header sent on outgoing requests. The default is "loops-go/" + Version.

type Pagination

type Pagination struct {
	TotalResults    int    `json:"totalResults"`
	ReturnedResults int    `json:"returnedResults"`
	PerPage         int    `json:"perPage"`
	TotalPages      int    `json:"totalPages"`
	NextCursor      string `json:"nextCursor"`
	NextPage        string `json:"nextPage"`
}

Pagination describes the position of a single page within a paginated result set. NextCursor is empty when the current page is the last one.

type PaginationParams

type PaginationParams struct {
	PerPage string
	Cursor  string
}

PaginationParams controls a single page request. Both fields are optional; leave Cursor empty to request the first page.

type PropertyCondition added in v0.3.0

type PropertyCondition struct {
	Key      string                  `json:"key"`
	Operator string                  `json:"operator"`
	Value    *PropertyConditionValue `json:"value,omitempty"`
}

PropertyCondition matches contacts by the value of a contact property.

type PropertyConditionRange added in v0.3.0

type PropertyConditionRange struct {
	From string `json:"from"`
	To   string `json:"to"`
}

PropertyConditionRange is the value for the "between" operator on a PropertyCondition. Both bounds are ISO 8601 timestamps.

type PropertyConditionValue added in v0.3.0

type PropertyConditionValue struct {
	String *string
	Number *float64
	Range  *PropertyConditionRange
}

PropertyConditionValue is the right-hand side of a PropertyCondition. Exactly one of String, Number, or Range is set, depending on Operator. For most operators a String or Number is used; the "between" operator uses Range. Value-less operators (such as "isTrue" or "empty") leave all fields zero and should be passed as a nil pointer.

func (PropertyConditionValue) MarshalJSON added in v0.3.0

func (v PropertyConditionValue) MarshalJSON() ([]byte, error)

MarshalJSON serializes the value as a string, number, or range object.

func (*PropertyConditionValue) UnmarshalJSON added in v0.3.0

func (v *PropertyConditionValue) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a string, number, or range object into the value.

type SendEmailActionWorkflowNode added in v0.3.1

type SendEmailActionWorkflowNode struct {
	ID          string   `json:"id"`
	WorkflowID  string   `json:"workflowId"`
	NextNodeIDs []string `json:"nextNodeIds"`
	Subject     string   `json:"subject,omitempty"`
}

SendEmailActionWorkflowNode is the SendEmailAction variant of WorkflowNode. The full variant does not include emailMessageId (only the simplified variant does).

type SendEventRequest

type SendEventRequest struct {
	Email             string          `json:"-"`
	UserID            string          `json:"-"`
	EventName         string          `json:"-"`
	EventProperties   map[string]any  `json:"-"`
	MailingLists      map[string]bool `json:"-"`
	ContactProperties map[string]any  `json:"-"`
	IdempotencyKey    string          `json:"-"`
}

SendEventRequest is the request body for Client.SendEvent.

One of Email or UserID must be set to identify the contact. EventName is required. EventProperties are sent alongside the event; ContactProperties are merged onto the contact at the same time.

If IdempotencyKey is set, it is sent as the Idempotency-Key HTTP header so the event can be safely retried without duplication.

type SendTransactionalRequest

type SendTransactionalRequest struct {
	Email           string         `json:"email"`
	TransactionalID string         `json:"transactionalId"`
	AddToAudience   *bool          `json:"addToAudience,omitempty"`
	DataVariables   map[string]any `json:"dataVariables,omitempty"`
	Attachments     []Attachment   `json:"attachments,omitempty"`
	IdempotencyKey  string         `json:"-"`
}

SendTransactionalRequest is the request body for Client.SendTransactional.

TransactionalID identifies the template to send and Email is the recipient. DataVariables populates the template's variables. If AddToAudience is true, the recipient is also added to your audience.

If IdempotencyKey is set, it is sent as the Idempotency-Key HTTP header so the send can be safely retried without duplication.

type SignupTriggerWorkflowNode added in v0.3.1

type SignupTriggerWorkflowNode struct {
	ID          string   `json:"id"`
	WorkflowID  string   `json:"workflowId"`
	NextNodeIDs []string `json:"nextNodeIds"`
}

SignupTriggerWorkflowNode is the SignupTrigger variant of WorkflowNode.

type SimplifiedAddToListTriggerWorkflowNode added in v0.3.1

type SimplifiedAddToListTriggerWorkflowNode struct {
	NextNodeIDs []string `json:"nextNodeIds"`
	MailingList string   `json:"mailingList,omitempty"`
	ReEligible  *bool    `json:"reEligible,omitempty"`
}

SimplifiedAddToListTriggerWorkflowNode is the AddToListTrigger variant of SimplifiedWorkflowNode.

type SimplifiedAudienceFilterWorkflowNode added in v0.3.1

type SimplifiedAudienceFilterWorkflowNode struct {
	NextNodeIDs []string `json:"nextNodeIds"`
}

SimplifiedAudienceFilterWorkflowNode is the AudienceFilter variant of SimplifiedWorkflowNode.

type SimplifiedBlankTriggerWorkflowNode added in v0.3.1

type SimplifiedBlankTriggerWorkflowNode struct {
	NextNodeIDs []string `json:"nextNodeIds"`
}

SimplifiedBlankTriggerWorkflowNode is the BlankTrigger variant of SimplifiedWorkflowNode.

type SimplifiedBranchWorkflowNode added in v0.3.1

type SimplifiedBranchWorkflowNode struct {
	NextNodeIDs []string `json:"nextNodeIds"`
}

SimplifiedBranchWorkflowNode is the BranchNode variant of SimplifiedWorkflowNode.

type SimplifiedContactPropertyTriggerWorkflowNode added in v0.3.1

type SimplifiedContactPropertyTriggerWorkflowNode struct {
	NextNodeIDs          []string                      `json:"nextNodeIds"`
	ContactPropertyQuery *WorkflowContactPropertyQuery `json:"contactPropertyQuery,omitempty"`
	ReEligible           *bool                         `json:"reEligible,omitempty"`
}

SimplifiedContactPropertyTriggerWorkflowNode is the ContactPropertyTrigger variant of SimplifiedWorkflowNode.

type SimplifiedEventTriggerWorkflowNode added in v0.3.1

type SimplifiedEventTriggerWorkflowNode struct {
	NextNodeIDs []string `json:"nextNodeIds"`
	EventName   string   `json:"eventName,omitempty"`
	ReEligible  *bool    `json:"reEligible,omitempty"`
}

SimplifiedEventTriggerWorkflowNode is the EventTrigger variant of SimplifiedWorkflowNode.

type SimplifiedExitActionWorkflowNode added in v0.3.1

type SimplifiedExitActionWorkflowNode struct {
	NextNodeIDs []string `json:"nextNodeIds"`
}

SimplifiedExitActionWorkflowNode is the ExitAction variant of SimplifiedWorkflowNode.

type SimplifiedExperimentBranchWorkflowNode added in v0.3.1

type SimplifiedExperimentBranchWorkflowNode struct {
	NextNodeIDs    []string               `json:"nextNodeIds"`
	SamplingRate   *float64               `json:"samplingRate,omitempty"`
	URL            string                 `json:"url,omitempty"`
	ExperimentID   string                 `json:"experimentId,omitempty"`
	ExperimentType WorkflowExperimentType `json:"experimentType,omitempty"`
}

SimplifiedExperimentBranchWorkflowNode is the ExperimentBranchNode variant of SimplifiedWorkflowNode.

type SimplifiedSendEmailActionWorkflowNode added in v0.3.1

type SimplifiedSendEmailActionWorkflowNode struct {
	NextNodeIDs    []string `json:"nextNodeIds"`
	EmailMessageID string   `json:"emailMessageId,omitempty"`
	Subject        string   `json:"subject,omitempty"`
}

SimplifiedSendEmailActionWorkflowNode is the SendEmailAction variant of SimplifiedWorkflowNode.

type SimplifiedSignupTriggerWorkflowNode added in v0.3.1

type SimplifiedSignupTriggerWorkflowNode struct {
	NextNodeIDs []string `json:"nextNodeIds"`
}

SimplifiedSignupTriggerWorkflowNode is the SignupTrigger variant of SimplifiedWorkflowNode.

type SimplifiedTimerActionWorkflowNode added in v0.3.1

type SimplifiedTimerActionWorkflowNode struct {
	NextNodeIDs []string          `json:"nextNodeIds"`
	Amount      *float64          `json:"amount,omitempty"`
	Unit        WorkflowTimerUnit `json:"unit,omitempty"`
}

SimplifiedTimerActionWorkflowNode is the TimerAction variant of SimplifiedWorkflowNode.

type SimplifiedVariantWorkflowNode added in v0.3.1

type SimplifiedVariantWorkflowNode struct {
	NextNodeIDs []string `json:"nextNodeIds"`
	VariantID   string   `json:"variantId,omitempty"`
	IsControl   *bool    `json:"isControl,omitempty"`
}

SimplifiedVariantWorkflowNode is the VariantNode variant of SimplifiedWorkflowNode.

type SimplifiedWorkflow added in v0.3.1

type SimplifiedWorkflow struct {
	ID            string                            `json:"id"`
	Name          string                            `json:"name,omitempty"`
	Description   string                            `json:"description,omitempty"`
	Emoji         string                            `json:"emoji,omitempty"`
	MailingListID *string                           `json:"mailingListId"`
	RootNodeID    *string                           `json:"rootNodeId"`
	Nodes         map[string]SimplifiedWorkflowNode `json:"nodes"`
}

SimplifiedWorkflow is returned by Client.GetWorkflow. Nodes is keyed by node ID; entry shapes are discriminated by their TypeName.

type SimplifiedWorkflowNode added in v0.3.1

SimplifiedWorkflowNode is one entry in SimplifiedWorkflow.Nodes. Exactly one variant pointer is set; TypeName is the discriminator and matches the active variant (see the WorkflowNodeType* constants).

func (SimplifiedWorkflowNode) MarshalJSON added in v0.3.1

func (n SimplifiedWorkflowNode) MarshalJSON() ([]byte, error)

MarshalJSON encodes the active variant inline with a "typeName" discriminator.

func (*SimplifiedWorkflowNode) UnmarshalJSON added in v0.3.1

func (n *SimplifiedWorkflowNode) UnmarshalJSON(data []byte) error

UnmarshalJSON dispatches on "typeName" and decodes the matching variant.

type Theme added in v0.1.3

type Theme struct {
	ID        string      `json:"id"`
	Name      string      `json:"name"`
	Styles    ThemeStyles `json:"styles"`
	IsDefault bool        `json:"isDefault"`
	CreatedAt string      `json:"createdAt"`
	UpdatedAt string      `json:"updatedAt"`
}

Theme is a named collection of styles applied to email messages. Exactly one theme on the account has IsDefault set to true.

type ThemeStyles added in v0.1.3

type ThemeStyles struct {
	BackgroundColor       string  `json:"backgroundColor"`
	BackgroundXPadding    float64 `json:"backgroundXPadding"`
	BackgroundYPadding    float64 `json:"backgroundYPadding"`
	BodyColor             string  `json:"bodyColor"`
	BodyXPadding          float64 `json:"bodyXPadding"`
	BodyYPadding          float64 `json:"bodyYPadding"`
	BodyFontFamily        string  `json:"bodyFontFamily"`
	BodyFontCategory      string  `json:"bodyFontCategory"`
	BorderColor           string  `json:"borderColor"`
	BorderWidth           float64 `json:"borderWidth"`
	BorderRadius          float64 `json:"borderRadius"`
	ButtonBodyColor       string  `json:"buttonBodyColor"`
	ButtonBodyXPadding    float64 `json:"buttonBodyXPadding"`
	ButtonBodyYPadding    float64 `json:"buttonBodyYPadding"`
	ButtonBorderColor     string  `json:"buttonBorderColor"`
	ButtonBorderWidth     float64 `json:"buttonBorderWidth"`
	ButtonBorderRadius    float64 `json:"buttonBorderRadius"`
	ButtonTextColor       string  `json:"buttonTextColor"`
	ButtonTextFormat      float64 `json:"buttonTextFormat"`
	ButtonTextFontSize    float64 `json:"buttonTextFontSize"`
	DividerColor          string  `json:"dividerColor"`
	DividerBorderWidth    float64 `json:"dividerBorderWidth"`
	TextBaseColor         string  `json:"textBaseColor"`
	TextBaseFontSize      float64 `json:"textBaseFontSize"`
	TextBaseLineHeight    float64 `json:"textBaseLineHeight"`
	TextBaseLetterSpacing float64 `json:"textBaseLetterSpacing"`
	TextLinkColor         string  `json:"textLinkColor"`
	Heading1Color         string  `json:"heading1Color"`
	Heading1FontSize      float64 `json:"heading1FontSize"`
	Heading1LineHeight    float64 `json:"heading1LineHeight"`
	Heading1LetterSpacing float64 `json:"heading1LetterSpacing"`
	Heading2Color         string  `json:"heading2Color"`
	Heading2FontSize      float64 `json:"heading2FontSize"`
	Heading2LineHeight    float64 `json:"heading2LineHeight"`
	Heading2LetterSpacing float64 `json:"heading2LetterSpacing"`
	Heading3Color         string  `json:"heading3Color"`
	Heading3FontSize      float64 `json:"heading3FontSize"`
	Heading3LineHeight    float64 `json:"heading3LineHeight"`
	Heading3LetterSpacing float64 `json:"heading3LetterSpacing"`
}

ThemeStyles is the set of visual style values for a Theme. Colors are CSS color strings (typically hex), and numeric fields are pixel values unless otherwise implied by the field name.

type TimerActionWorkflowNode added in v0.3.1

type TimerActionWorkflowNode struct {
	ID          string            `json:"id"`
	WorkflowID  string            `json:"workflowId"`
	NextNodeIDs []string          `json:"nextNodeIds"`
	Amount      float64           `json:"amount"`
	Unit        WorkflowTimerUnit `json:"unit"`
}

TimerActionWorkflowNode is the TimerAction variant of WorkflowNode.

type Transactional added in v0.2.0

type Transactional struct {
	ID                      string   `json:"id"`
	Name                    string   `json:"name"`
	DraftEmailMessageID     *string  `json:"draftEmailMessageId"`
	PublishedEmailMessageID *string  `json:"publishedEmailMessageId"`
	TransactionalGroupID    *string  `json:"transactionalGroupId"`
	CreatedAt               string   `json:"createdAt"`
	UpdatedAt               string   `json:"updatedAt"`
	DataVariables           []string `json:"dataVariables"`
}

Transactional describes a transactional email template managed via the content API. A transactional email can have a draft and/or a published EmailMessage, linked via DraftEmailMessageID and PublishedEmailMessageID.

type TransactionalDraft added in v0.2.0

type TransactionalDraft struct {
	Transactional
	DraftEmailMessageContentRevisionID *string `json:"draftEmailMessageContentRevisionId"`
}

TransactionalDraft is returned by Client.CreateTransactional and Client.EnsureTransactionalDraft. It embeds the Transactional and adds DraftEmailMessageContentRevisionID, which should be passed as ExpectedRevisionID on the first call to Client.UpdateEmailMessage for optimistic concurrency control.

type TransactionalEmail

type TransactionalEmail struct {
	ID            string   `json:"id"`
	Name          string   `json:"name"`
	LastUpdated   string   `json:"lastUpdated"`
	DataVariables []string `json:"dataVariables"`
}

TransactionalEmail describes a transactional email template configured in Loops, as returned by Client.ListTransactional.

type UpdateCampaignRequest

type UpdateCampaignRequest struct {
	Name              string
	CampaignGroupID   string
	MailingListID     *string
	AudienceSegmentID *string
	AudienceFilter    *AudienceFilter
	Scheduling        *CampaignSchedulingRequest
	Set               map[string]bool
}

UpdateCampaignRequest is the request body for Client.UpdateCampaign.

Set selects which fields are applied — only fields whose key is true in Set are sent. This lets the caller distinguish "leave alone" from "set to null" for nullable fields, and from "set to empty string" for required string fields.

At least one field must be selected. Setting AudienceSegmentID clears any AudienceFilter and vice versa.

type UpdateContactRequest

type UpdateContactRequest struct {
	Email             string
	UserID            string
	FirstName         string
	LastName          string
	Subscribed        *bool
	UserGroup         string
	MailingLists      map[string]bool
	ContactProperties map[string]any
}

UpdateContactRequest is the request body for Client.UpdateContact. The contact is identified by Email or UserID; one must be set. Fields left at their zero value are not modified, except Subscribed which uses a pointer so an explicit false can be sent.

type UpdateEmailMessageRequest

type UpdateEmailMessageRequest struct {
	EmailMessageFields
	Set                map[string]bool
	ExpectedRevisionID string
}

UpdateEmailMessageRequest is the request body for Client.UpdateEmailMessage.

Set selects which fields from the embedded EmailMessageFields are applied — only fields whose key is true in Set are sent. This lets the caller distinguish "leave alone" from "set to empty string".

For the *Fallbacks maps, a nil value in the map clears the fallback for that key; a string value sets it. Each map is a full replacement of the server-side map.

ExpectedRevisionID is optional; if set, the update fails if the message's current ContentRevisionID does not match (optimistic concurrency control).

type UpdateGroupRequest added in v0.3.0

type UpdateGroupRequest struct {
	Name        string `json:"name,omitempty"`
	Description string `json:"description,omitempty"`
}

UpdateGroupRequest is the request body for Client.UpdateCampaignGroup and Client.UpdateTransactionalGroup. At least one field must be set.

type UpdateTransactionalRequest added in v0.2.0

type UpdateTransactionalRequest struct {
	Name                 string `json:"name"`
	TransactionalGroupID string `json:"transactionalGroupId,omitempty"`
}

UpdateTransactionalRequest is the request body for Client.UpdateTransactional. Name is required. Set TransactionalGroupID to move the email to a different group; leave it empty to keep the existing group.

type UploadRequest added in v0.1.4

type UploadRequest struct {
	ContentType   string
	ContentLength int64
	Body          io.Reader
}

UploadRequest is the input to Client.Upload, the one-call helper that performs the full three-step upload flow. Body is read up to ContentLength bytes and sent as the asset body.

type VariantWorkflowNode added in v0.3.1

type VariantWorkflowNode struct {
	ID          string   `json:"id"`
	WorkflowID  string   `json:"workflowId"`
	NextNodeIDs []string `json:"nextNodeIds"`
	VariantID   string   `json:"variantId,omitempty"`
	IsControl   *bool    `json:"isControl,omitempty"`
}

VariantWorkflowNode is the VariantNode variant of WorkflowNode.

type WorkflowContactPropertyComparison added in v0.3.1

type WorkflowContactPropertyComparison struct {
	Value    WorkflowContactPropertyValue `json:"value"`
	Operator string                       `json:"operator"`
}

WorkflowContactPropertyComparison is a single comparison in a WorkflowContactPropertyQuery.

type WorkflowContactPropertyQuery added in v0.3.1

type WorkflowContactPropertyQuery struct {
	Key string                            `json:"key"`
	Is  WorkflowContactPropertyComparison `json:"is"`
	Was WorkflowContactPropertyComparison `json:"was"`
}

WorkflowContactPropertyQuery is the contact-property predicate of a ContactPropertyTriggerWorkflowNode or SimplifiedContactPropertyTriggerWorkflowNode.

type WorkflowContactPropertyValue added in v0.3.1

type WorkflowContactPropertyValue struct {
	String *string
	Number *float64
	Bool   *bool
}

WorkflowContactPropertyValue holds the right-hand side of a comparison; exactly one of String, Number, or Bool is set depending on the operator. Value-less operators may leave all fields zero.

func (WorkflowContactPropertyValue) MarshalJSON added in v0.3.1

func (v WorkflowContactPropertyValue) MarshalJSON() ([]byte, error)

MarshalJSON serializes the value as a string, number, or boolean.

func (*WorkflowContactPropertyValue) UnmarshalJSON added in v0.3.1

func (v *WorkflowContactPropertyValue) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a string, number, or boolean into the value.

type WorkflowEventProperty added in v0.3.1

type WorkflowEventProperty struct {
	Name string `json:"name"`
	Type string `json:"type"`
}

WorkflowEventProperty describes one event property surfaced by an EventTriggerWorkflowNode. Type is one of "string", "number", "boolean", or "date".

type WorkflowExperimentType added in v0.3.1

type WorkflowExperimentType string

WorkflowExperimentType is the kind of experiment driving an ExperimentBranchWorkflowNode.

const (
	WorkflowExperimentTypeWebhook   WorkflowExperimentType = "webhook"
	WorkflowExperimentTypeAutosplit WorkflowExperimentType = "autosplit"
)

type WorkflowNode added in v0.3.1

type WorkflowNode struct {
	TypeName               string
	SignupTrigger          *SignupTriggerWorkflowNode
	EventTrigger           *EventTriggerWorkflowNode
	ContactPropertyTrigger *ContactPropertyTriggerWorkflowNode
	AddToListTrigger       *AddToListTriggerWorkflowNode
	BlankTrigger           *BlankTriggerWorkflowNode
	AudienceFilter         *AudienceFilterWorkflowNode
	TimerAction            *TimerActionWorkflowNode
	SendEmailAction        *SendEmailActionWorkflowNode
	ExitAction             *ExitActionWorkflowNode
	BranchNode             *BranchWorkflowNode
	ExperimentBranchNode   *ExperimentBranchWorkflowNode
	VariantNode            *VariantWorkflowNode
}

WorkflowNode is returned by Client.GetWorkflowNode. Exactly one variant pointer is set; TypeName is the discriminator and matches the active variant (see the WorkflowNodeType* constants).

func (WorkflowNode) MarshalJSON added in v0.3.1

func (n WorkflowNode) MarshalJSON() ([]byte, error)

MarshalJSON encodes the active variant inline with a "typeName" discriminator.

func (*WorkflowNode) UnmarshalJSON added in v0.3.1

func (n *WorkflowNode) UnmarshalJSON(data []byte) error

UnmarshalJSON dispatches on "typeName" and decodes the matching variant.

type WorkflowSummary added in v0.3.1

type WorkflowSummary struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	CreatedAt string `json:"createdAt"`
	UpdatedAt string `json:"updatedAt"`
}

WorkflowSummary is an entry in the Client.ListWorkflows response.

type WorkflowTimerUnit added in v0.3.1

type WorkflowTimerUnit string

WorkflowTimerUnit is the unit of a TimerActionWorkflowNode delay.

const (
	WorkflowTimerUnitSeconds WorkflowTimerUnit = "s"
	WorkflowTimerUnitMinutes WorkflowTimerUnit = "m"
	WorkflowTimerUnitHours   WorkflowTimerUnit = "h"
	WorkflowTimerUnitDays    WorkflowTimerUnit = "d"
)

Jump to

Keyboard shortcuts

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