← All SDKs

.NET 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 .NET 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

dotnet add package Likyly

.NET 8 or later. No dependency beyond the framework (HttpClient, System.Text.Json). Async everywhere, CancellationToken on every call.

Quick start

The snippets are top-level statements (Program.cs); in a class, put them in an async method.

1. Initialize

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

using Likyly;

// Backend only: the secret key gives access to your catalog and your users.
var likyly = new LikylyClient(new LikylyClientOptions
{
    ApiKey = Environment.GetEnvironmentVariable("LIKYLY_SECRET_KEY")!,
});

2. Send your catalog

// Send your catalog once (and whenever it changes). Ids are YOUR ids: SKUs, UUIDs, Shopify gids...
await likyly.Items.UpsertManyAsync(
[
    new ItemImport { ItemId = "SKU-1", Title = "Nike Air Max", Description = "Running shoe with air cushioning", Properties = new Dictionary<string, object?> { ["category"] = "shoes", ["brand"] = "Nike", ["price"] = 129.9 } },
    new ItemImport { ItemId = "SKU-2", Title = "Adidas Ultraboost", Description = "Responsive running shoe", Properties = new Dictionary<string, object?> { ["category"] = "shoes", ["brand"] = "Adidas", ["price"] = 149 } },
    new ItemImport { ItemId = "SKU-3", Title = "Nike Pegasus", Description = "Everyday running shoe", Properties = new Dictionary<string, object?> { ["category"] = "shoes", ["brand"] = "Nike", ["price"] = 119 } },
]);

// Users are optional: describe them if you want the profile to travel with their events.
await likyly.Users.UpsertAsync("user_123", new UserInput { Properties = new Dictionary<string, object?> { ["country"] = "FR", ["segment"] = "premium" } });

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.
await likyly.Events.ViewAsync(new EventInput { UserId = "user_123", ItemId = "SKU-1" });

// Purchases carry an EventId: replaying the call can never count the sale twice.
await likyly.Events.PurchaseAsync(new EventInput
{
    EventId = "purchase_order_9281_SKU-1",
    UserId = "user_123",
    ItemId = "SKU-1",
    Quantity = 1,
    Properties = new Dictionary<string, object?> { ["price"] = 129.9, ["currency"] = "EUR", ["orderId"] = "order_9281" },
});

4. Get recommendations

// Ask what to show. You never pick an algorithm: LIKYLY chooses the best strategy for what it knows.
var recs = await likyly.Recommendations.GetAsync(new RecommendationRequest { UserId = "user_123", Placement = "homepage", Limit = 3 });

Console.WriteLine($"strategy: {recs.Strategy}");
foreach (var item in recs.Items)
{
    Console.WriteLine($"{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.
var related = await likyly.Placements.RecommendAsync(new PlacementRecommendRequest
{
    Placement = "pdp-related",
    Context = new PlacementContext { ItemId = "SKU-123", SessionId = "sess_abc" },
    Limit = 4,
});
Console.WriteLine($"strategy used: {related.StrategyUsed}");

// When an anonymous visitor signs in, attach their session's history to their account.
var linked = await likyly.Events.IdentifyAsync(new IdentifyInput { UserId = "user_123", SessionId = "sess_abc" });
Console.WriteLine($"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.
var shown = new EventInput { UserId = "user_123", ItemId = recs.Items[0].ItemId, RecommendationId = recs.RecommendationId, Placement = "homepage" };
await likyly.Events.ImpressionAsync(shown);
await likyly.Events.ClickAsync(shown);

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 (PermissionDeniedException)
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.
var front = new LikylyClient(new LikylyClientOptions
{
    ApiKey = Environment.GetEnvironmentVariable("LIKYLY_PUBLIC_KEY")!,
});

// A visitor who is not logged in: use an anonymous session id (any string you generate and keep in a cookie).
await front.Events.ViewAsync(new EventInput { SessionId = "sess_abc", ItemId = "SKU-2" });
var forVisitor = await front.Recommendations.GetAsync(new RecommendationRequest { SessionId = "sess_abc", ViewedItemIds = ["SKU-2"], Placement = "product_page", Limit = 3 });

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.
await likyly.Events.TrackAsync("favorite", new EventInput { UserId = "user_123", ItemId = "SKU-2", Properties = new Dictionary<string, object?> { ["list"] = "wishlist" } });

// Up to 1000 events per call, each with its own type.
await likyly.Events.TrackManyAsync(
[
    new TypedEventInput { Type = "view", UserId = "user_123", ItemId = "SKU-3" },
    new TypedEventInput { Type = "add_to_cart", UserId = "user_123", ItemId = "SKU-3", Quantity = 1 },
]);
  • 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.
var similar = await likyly.Recommendations.SimilarAsync(new SimilarOptions { ItemId = "SKU-1", Limit = 3 });
var hybrid = await likyly.Recommendations.HybridAsync(new HybridOptions { UserId = "user_123", ItemId = "SKU-1", Alpha = 0.7, Limit = 3 });
var session = await likyly.Recommendations.SessionAsync(new SessionOptions { ViewedItemIds = ["SKU-1", "SKU-2"], Limit = 3 });
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 LikylyException). Catch the ones you care about:

ErrorWhen
ValidationExceptionInvalid request: caught by the SDK before anything is sent, or a 422 from the API (the message names the faulty fields)
AuthenticationException401: missing, invalid or revoked API key
PermissionDeniedException403: for example a public key used for an operation reserved to the secret key, or a plan limit
NotFoundException404
RateLimitException429: see the retry-after value
ApiExceptionAny other error status from the API (the four rows above are subtypes of it)
NetworkExceptionNo HTTP response: DNS, dropped connection, TLS
RequestTimeoutExceptionThe request timed out

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

try
{
    await likyly.Items.GetAsync("does-not-exist");
}
catch (NotFoundException e)
{
    Console.WriteLine($"no such item, request {e.RequestId}");
}
catch (RateLimitException e)
{
    Console.WriteLine($"slow down, retry in {e.RetryAfter}");
}

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 keyApiKeyrequired
Base URLBaseUrlhttps://api.likyly.com
CatalogCatalogyour only catalog
TimeoutTimeout (TimeSpan)10 s
RetriesMaxRetries2
User-Agent suffixUserAgentnone
Custom HTTPnew LikylyClient(options, httpClient)a new HttpClient
var tuned = new LikylyClient(new LikylyClientOptions
{
    ApiKey = Environment.GetEnvironmentVariable("LIKYLY_SECRET_KEY")!,
    Timeout = TimeSpan.FromSeconds(5), // per attempt (default 10 s)
    MaxRetries = 3, // automatic retries on 429 / 502 / 503 / 504 / network errors (default 2, 0 disables)
    UserAgent = "my-shop/1.4", // appended to the SDK's User-Agent
});

Pass a CancellationToken as the last argument; the client's Timeout applies per attempt. Register LikylyClient as a singleton (services.AddSingleton(...)).

Reference

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

MethodEffectKey
likyly.Items.GetAsyncOne item by your own idS
likyly.Items.ListAsyncOne page of the catalog (limit / offset), with the catalog's totalS
likyly.Items.UpsertAsyncCreate or replace an item (idempotent)S
likyly.Items.DeleteAsyncRemove an item (events already recorded for it are kept)S
likyly.Items.UpsertManyAsyncBatch upsert, 1 to 1000 itemsS
likyly.Items.ImportAsyncAlias of the batch upsert above (JSON batch)S
likyly.Items.DeleteManyAsyncBatch delete, 1 to 1000 ids; unknown ids are reported, not raisedS
likyly.Users.GetAsyncOne user profileS
likyly.Users.ListAsyncOne page of users (limit / offset)S
likyly.Users.UpsertAsyncCreate or replace a profile (free-form properties)S
likyly.Users.DeleteAsyncErase the profile and every event recorded for that userS
likyly.Users.ImportAsyncBatch upsert of users, 1 to 1000S
likyly.Events.TrackAsyncRecord an event of any type (open string)P
likyly.Events.TrackManyAsyncUp to 1000 events in one call, each with its own typeP
likyly.Events.ImpressionAsyncThe item was displayed to the visitorP
likyly.Events.ViewAsyncThe visitor looked at the itemP
likyly.Events.ClickAsyncThe visitor clicked the itemP
likyly.Events.AddToCartAsyncThe visitor added the item to their cartP
likyly.Events.RemoveFromCartAsyncThe visitor removed the item from their cartP
likyly.Events.PurchaseAsyncThe visitor bought the item (set an event id)P
likyly.Events.IdentifyAsyncAn anonymous visitor signed in: attach their session's history to their user idP
likyly.Placements.RecommendAsyncRecommendations for a named placement configured in LIKYLY (the recommended way)P
likyly.Recommendations.GetAsyncRecommendations with the automatic strategy: user, session, item or viewed itemsP
likyly.Recommendations.PopularAsyncAdvanced: the most popular itemsP
likyly.Recommendations.SimilarAsyncAdvanced: items similar to one itemP
likyly.Recommendations.CollaborativeAsyncAdvanced: what similar users liked (needs a trained model)P
likyly.Recommendations.HybridAsyncAdvanced: similar items personalised for a user (alpha)P
likyly.Recommendations.SessionAsyncAdvanced: 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).

.NET notes

  • Request and response models are C# records/classes with nullable annotations; identifiers are strings and are never coerced. The keys inside Properties (a Dictionary<string, object?>) are yours and are never renamed.

Package: Likyly on NuGet. Full REST reference: api.likyly.com/docs.