← All SDKs

Go SDK

LIKYLY shows each visitor of your site the products they are most likely to want: “You may also like” on a product page, “Recommended for you” on the home page, “Complete your order” in the cart. It learns from what your visitors actually do.

This is the official Go client for the LIKYLY API. Your code uses it to:

  1. Send your catalog: the products, articles or movies to recommend.
  2. Report what visitors do: they view a product, add it to their cart, sometimes buy it. Viewing alone is useful: a visitor who never buys still teaches LIKYLY which products go together, and gets recommendations.
  3. Ask what to show: the products to recommend on a page, for a visitor, or both.
  4. Report what happens to the recommendations: which ones were seen, which ones were clicked. LIKYLY learns what works, and you measure what they bring in.

Installation

go get github.com/likyly/likyly-go

Go 1.21 or later. Standard library only. Every call takes a context.Context. Safe for concurrent use.

Quick start

The snippets run inside func main(); log.Fatal keeps them short, handle errors as you see fit.

1. Initialize

Create one client and reuse it. Use your secret key on the server (see Which key?).

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/likyly/likyly-go"
)

ctx := context.Background()

// Backend only: the secret key gives access to your catalog and your users.
client, err := likyly.New(os.Getenv("LIKYLY_SECRET_KEY"))
if err != nil {
	log.Fatal(err)
}

2. Send your catalog

// Send your catalog once (and whenever it changes). Ids are YOUR ids: SKUs, UUIDs, Shopify gids...
_, err = client.Items.UpsertMany(ctx, []likyly.ItemImport{
	{ItemID: "SKU-1", Title: "Nike Air Max", Description: "Running shoe with air cushioning", Properties: likyly.Properties{"category": "shoes", "brand": "Nike", "price": 129.9}},
	{ItemID: "SKU-2", Title: "Adidas Ultraboost", Description: "Responsive running shoe", Properties: likyly.Properties{"category": "shoes", "brand": "Adidas", "price": 149}},
	{ItemID: "SKU-3", Title: "Nike Pegasus", Description: "Everyday running shoe", Properties: likyly.Properties{"category": "shoes", "brand": "Nike", "price": 119}},
})
if err != nil {
	log.Fatal(err)
}

// Users are optional: describe them if you want the profile to travel with their events.
_, err = client.Users.Upsert(ctx, "user_123", likyly.UserInput{Properties: likyly.Properties{"country": "FR", "segment": "premium"}})
if err != nil {
	log.Fatal(err)
}

The ids are yours: any string (SKU-123, a UUID, gid://shopify/Product/123). properties is free-form; category and description improve similarity, the rest is stored as is.

3. Track events

// Tell LIKYLY what your visitors do.
if _, err = client.Events.View(ctx, likyly.EventInput{UserID: "user_123", ItemID: "SKU-1"}); err != nil {
	log.Fatal(err)
}

// Purchases carry an EventID: replaying the call can never count the sale twice.
_, err = client.Events.Purchase(ctx, likyly.EventInput{
	EventID:    "purchase_order_9281_SKU-1",
	UserID:     "user_123",
	ItemID:     "SKU-1",
	Quantity:   1,
	Properties: likyly.Properties{"price": 129.9, "currency": "EUR", "orderId": "order_9281"},
})
if err != nil {
	log.Fatal(err)
}

4. Get recommendations

// Ask what to show. You never pick an algorithm: LIKYLY chooses the best strategy for what it knows.
recs, err := client.Recommendations.Get(ctx, likyly.RecommendationRequest{UserID: "user_123", Placement: "homepage", Limit: 3})
if err != nil {
	log.Fatal(err)
}

fmt.Println("strategy:", recs.Strategy)
for _, item := range recs.Items {
	fmt.Println(item.ItemID, item.Title)
}

You never pick an algorithm: LIKYLY selects the best strategy from what it knows about the visitor and tells you which one it used (strategy: hybrid, content, collaborative, session or popular). With no user, no session and no item, you still get a useful answer: what is popular.

5. Placements: the recommended way

// The recommended way: a placement ("pdp-related"...) is configured once in LIKYLY - strategy,
// fallback, filters - and your page only says where it is and what it knows.
related, err := client.Placements.Recommend(ctx, likyly.PlacementRequest{
	Placement: "pdp-related",
	Context:   &likyly.PlacementContext{ItemID: "SKU-123", SessionID: "sess_abc"},
	Limit:     4,
})
if err != nil {
	log.Fatal(err)
}
fmt.Println("strategy used:", related.StrategyUsed)

// When an anonymous visitor signs in, attach their session's history to their account.
linked, err := client.Events.Identify(ctx, likyly.IdentifyInput{UserID: "user_123", SessionID: "sess_abc"})
if err != nil {
	log.Fatal(err)
}
fmt.Println("linked:", linked.LinkedInteractions)

A placement (pdp-related, home-for-you, cart-cross-sell…) is set up once in LIKYLY, by your AI assistant through the MCP server or in the console: strategy, fallback, filters, number of items. Your code just names it and passes what it knows (product shown, user, session); the setup can then change without a redeploy. identify attaches an anonymous visitor’s history to their account as soon as they sign in, to keep recommendations personal.

6. Close the loop: attribution

// Send the RecommendationID back: LIKYLY measures which recommendations get seen, clicked and bought.
shown := likyly.EventInput{UserID: "user_123", ItemID: recs.Items[0].ItemID, RecommendationID: recs.RecommendationID, Placement: "homepage"}
if _, err = client.Events.Impression(ctx, shown); err != nil {
	log.Fatal(err)
}
if _, err = client.Events.Click(ctx, shown); err != nil {
	log.Fatal(err)
}

Send the recommendation id back on the events that follow (impression on display, click, add_to_cart, purchase): that is how LIKYLY measures which recommendations actually convert.

Which key?

Secret keyPublic key
Where to use iton your server onlyanywhere, including a web page
Recommendationsyesyes
Record eventsyesyes
Items and users (create, read, delete)yesno (*PermissionDeniedError)
debug explanationsyesno

The public key can only read recommendations and write events, so it can be exposed. Never put the secret key in code shipped to a browser or a mobile app.

// Where the code is exposed to visitors, use the PUBLIC key: it can only read recommendations and record events.
front, err := likyly.New(os.Getenv("LIKYLY_PUBLIC_KEY"))
if err != nil {
	log.Fatal(err)
}

// A visitor who is not logged in: use an anonymous session id (any string you generate and keep in a cookie).
if _, err = front.Events.View(ctx, likyly.EventInput{SessionID: "sess_abc", ItemID: "SKU-2"}); err != nil {
	log.Fatal(err)
}
forVisitor, err := front.Recommendations.Get(ctx, likyly.RecommendationRequest{SessionID: "sess_abc", ViewedItemIDs: []string{"SKU-2"}, Placement: "product_page", Limit: 3})
if err != nil {
	log.Fatal(err)
}

Events

track is the single mechanism; impression, view, click, add_to_cart, remove_from_cart and purchase are shortcuts to it. Event types are free-form strings: use your own (favorite, share, video_played...) as freely as the official ones.

// Any string is a valid event type: track what matters to your business.
_, err = client.Events.Track(ctx, "favorite", likyly.EventInput{UserID: "user_123", ItemID: "SKU-2", Properties: likyly.Properties{"list": "wishlist"}})
if err != nil {
	log.Fatal(err)
}

// Up to 1000 events per call, each with its own type.
_, err = client.Events.TrackMany(ctx, []likyly.TypedEvent{
	{Type: "view", EventInput: likyly.EventInput{UserID: "user_123", ItemID: "SKU-3"}},
	{Type: "add_to_cart", EventInput: likyly.EventInput{UserID: "user_123", ItemID: "SKU-3", Quantity: 1}},
})
if err != nil {
	log.Fatal(err)
}
  • An event carries an item and a user, a session, or both (both link the anonymous session to the user once signed in).
  • Anonymous visitors: generate a session id (any string) and keep it in a cookie; no sign-in required.
  • properties is a free-form object (price, currency, order number...). Its keys are stored exactly as you send them and never renamed by the SDK.
  • The event id (idempotency key): replaying an event with the same id records nothing and returns duplicate: true. Set it on purchases, for example purchase_<order>_<item>.
  • placement is a free-form label for where something happened or will be shown (homepage, product_page, cart...).

Advanced recommendations

recommendations.get is the normal way. To pick the strategy yourself:

// Advanced Recommendations: one strategy at a time, when you want to choose.
alpha := 0.7
similar, err := client.Recommendations.Similar(ctx, likyly.SimilarOptions{ItemID: "SKU-1", AdvancedOptions: likyly.AdvancedOptions{Limit: 3}})
if err != nil {
	log.Fatal(err)
}
hybrid, err := client.Recommendations.Hybrid(ctx, likyly.HybridOptions{UserID: "user_123", ItemID: "SKU-1", Alpha: &alpha, AdvancedOptions: likyly.AdvancedOptions{Limit: 3}})
if err != nil {
	log.Fatal(err)
}
session, err := client.Recommendations.Session(ctx, likyly.SessionOptions{ViewedItemIDs: []string{"SKU-1", "SKU-2"}, AdvancedOptions: likyly.AdvancedOptions{Limit: 3}})
if err != nil {
	log.Fatal(err)
}
StrategyWhat it does
popularThe most popular items: the fallback for a visitor with no history
similarItems similar to an item (content similarity), no user needed
collaborativeWhat users with similar histories liked. Needs a trained model, otherwise a “not found” error
hybridSimilar items personalized for a user; alpha (0 to 1) weighs collaborative against content
sessionWeighted by recency, from the items viewed or a user's history (exactly one of the two)

These endpoints carry the ids in the URL path: an id containing / (like gid://shopify/Product/1) or, for the session list, ,, is rejected with a validation error. In that case use recommendations.get, which takes the ids in the request body.

Errors

Errors are typed (all of them are error). Catch the ones you care about:

ErrorWhen
*ValidationErrorInvalid request: caught by the SDK before anything is sent, or a 422 from the API (the message names the faulty fields)
*AuthenticationError401: missing, invalid or revoked API key
*PermissionDeniedError403: for example a public key used for an operation reserved to the secret key, or a plan limit
*NotFoundError404
*RateLimitError429: see the retry-after value
*APIErrorAny other error status from the API (the four rows above are subtypes of it)
*NetworkErrorNo HTTP response: DNS, dropped connection, TLS
*TimeoutErrorThe request timed out

Errors from the API carry: StatusCode, RequestID, RetryAfter (time.Duration), Body. Share the request id when you contact support.

_, err = client.Items.Get(ctx, "does-not-exist")
var notFound *likyly.NotFoundError
var rateLimited *likyly.RateLimitError
switch {
case errors.As(err, &notFound):
	fmt.Println("no such item, request", notFound.RequestID)
case errors.As(err, &rateLimited):
	fmt.Println("slow down, retry in", rateLimited.RetryAfter)
case err != nil:
	log.Fatal(err)
}

Retries and timeouts

The SDK retries transient failures for you (2 retries by default, exponential backoff from 0.5 s capped at 8 s, with full jitter):

  • 429: always retried, honoring Retry-After. A Retry-After above 60 s is not waited for: the rate limit error is returned.
  • 502, 503, 504, dropped connections and timeouts: retried only when replaying the call is safe: reads, upserts, deletes, events that carry an event id, and batches where every event has one.
  • An event without an event id is never retried after an ambiguous failure, so a flaky network can never record a purchase twice. Set the id on the events that matter and they become retryable.
  • Other 4xx errors are never retried.

Configuration

SettingOptionDefault
API keyfirst argument of Newrequired
Base URLWithBaseURLhttps://api.likyly.com
CatalogWithCatalogyour only catalog
TimeoutWithTimeout (time.Duration)10 s
RetriesWithMaxRetries2
User-Agent suffixWithUserAgentnone
Custom HTTPWithHTTPClient (any Doer, e.g. *http.Client)http.DefaultClient
tuned, err := likyly.New(os.Getenv("LIKYLY_SECRET_KEY"),
	likyly.WithTimeout(5*time.Second),                                   // per attempt (default 10s)
	likyly.WithMaxRetries(3),                                            // automatic retries on 429 / 502 / 503 / 504 / network errors (default 2, 0 disables)
	likyly.WithUserAgent("my-shop/1.4"),                                 // appended to the SDK's User-Agent
)
if err != nil {
	log.Fatal(err)
}

Cancel or set a deadline through the context.Context. Per-call options go last: WithRequestTimeout(d), WithRequestMaxRetries(n).

Reference

Key: S = secret key only, P = public or secret key.

MethodEffectKey
client.Items.GetOne item by your own idS
client.Items.ListOne page of the catalog (limit / offset), with the catalog's totalS
client.Items.UpsertCreate or replace an item (idempotent)S
client.Items.DeleteRemove an item (events already recorded for it are kept)S
client.Items.UpsertManyBatch upsert, 1 to 1000 itemsS
client.Items.ImportAlias of the batch upsert above (JSON batch)S
client.Items.DeleteManyBatch delete, 1 to 1000 ids; unknown ids are reported, not raisedS
client.Users.GetOne user profileS
client.Users.ListOne page of users (limit / offset)S
client.Users.UpsertCreate or replace a profile (free-form properties)S
client.Users.DeleteErase the profile and every event recorded for that userS
client.Users.ImportBatch upsert of users, 1 to 1000S
client.Events.TrackRecord an event of any type (open string)P
client.Events.TrackManyUp to 1000 events in one call, each with its own typeP
client.Events.ImpressionThe item was displayed to the visitorP
client.Events.ViewThe visitor looked at the itemP
client.Events.ClickThe visitor clicked the itemP
client.Events.AddToCartThe visitor added the item to their cartP
client.Events.RemoveFromCartThe visitor removed the item from their cartP
client.Events.PurchaseThe visitor bought the item (set an event id)P
client.Events.IdentifyAn anonymous visitor signed in: attach their session's history to their user idP
client.Placements.RecommendRecommendations for a named placement configured in LIKYLY (the recommended way)P
client.Recommendations.GetRecommendations with the automatic strategy: user, session, item or viewed itemsP
client.Recommendations.PopularAdvanced: the most popular itemsP
client.Recommendations.SimilarAdvanced: items similar to one itemP
client.Recommendations.CollaborativeAdvanced: what similar users liked (needs a trained model)P
client.Recommendations.HybridAdvanced: similar items personalised for a user (alpha)P
client.Recommendations.SessionAdvanced: from viewed items or a user's view historyP

Lists are paginated with limit and offset (the API’s default page holds 100 items); the total comes with the page. Users have a batch import but no batch delete: the API has no such endpoint. The items’ import is an alias of the batch upsert (CSV import is a dashboard feature).

Go notes

  • Optional fields use zero values as "not set" (Limit: 0 = the API's default). HybridOptions.Alpha is a *float64 so that 0 is expressible. Test errors with errors.As; a *ValidationError from a 422 also matches *APIError.
  • Request and response fields are PascalCase structs; the keys inside Properties (a map[string]any) are yours and are never renamed.

Package: github.com/likyly/likyly-go on Go modules. Full REST reference: api.likyly.com/docs.