Home / Blog / Wrap an Amazon Product API in an ASP.NET Core Minimal API: Caching and Validated DTOs

Wrap an Amazon Product API in an ASP.NET Core Minimal API: Caching and Validated DTOs

Wrap the SellerMagnet API in an ASP.NET Core minimal API: a DataAnnotations-validated DTO and an IEndpointFilter reject a bad ASIN or marketplace before any network call, a ConcurrentDictionary-backed TTL cache answers repeat lookups for free, and the C# quickstart's own client files are reused unchanged. Every scenario, including a cold-cache race and a client timeout, runs through WebApplicationFactory against a fails-closed fake HttpListener.

December 05, 2026
9 min read
SellerMagnet Team
Share & Bookmark
Terminal window showing a DataAnnotations-validated LookupRequest DTO rejected before any network call

An ASP.NET Core minimal API in front of the SellerMagnet API validates every request with DataAnnotations before it can spend a credit, answers repeat lookups from a ConcurrentDictionary-backed in-process cache, and retries only the status codes a second attempt can fix. This guide builds that wrapper - LookupRequest.cs, ValidationFilter.cs, TtlCache.cs and Program.cs are new, and the C# quickstart's own SellerMagnetClient.cs, Models.cs and Retry.cs are reused unchanged - and tests all of it with WebApplicationFactory against a fails-closed fake HttpListener so nothing here is just described.

Key Takeaways

  • Minimal APIs skip DataAnnotations validation by default - that wiring is an MVC/controller feature. An IEndpointFilter that calls Validator.TryValidateObject is the model-validated-DTO seam the route handler relies on.
  • A TtlCache needs a ConcurrentDictionary here, unlike a plain dict in a single-worker process: Kestrel calls the handler for every request on the thread pool, so two requests for the same ASIN can race on a plain Dictionary.
  • A ConcurrentDictionary makes the cache memory-safe under that race, but it does not single-flight a cold cache: this suite's own tests proved several concurrent first-time lookups can each miss and call upstream, the same trade-off the Go wrapper's mutex-guarded map has.
  • The retry policy is the quickstart's own: 429 waits for free, a 500 is retried once (it is refunded), 502/503 are retried up to 4 times (each billed), and a 404 is a real answer, never retried.
  • A client timeout and a connection error are opposite cases: a timeout means the request reached the server and was billed up front, not refunded; a connection error never reached the server and cost nothing, so it is retried for free.

Why wrap the API in a microservice instead of calling it directly?

A thin service in front of the API gives every caller in a larger system one place that enforces the request shape, one cache for ASINs several callers ask for repeatedly, and one retry policy, instead of each caller reimplementing the C# quickstart's own SellerMagnetClient.cs, Models.cs and Retry.cs on its own. This post reuses those three files unchanged - the client's HttpClient is already safe for concurrent use, which is exactly how Kestrel calls a minimal-API handler for every request.

Dependencies

dotnet --version                 # 8.0 or later
dotnet new web -n AmazonAspNet && cd AmazonAspNet
export SELLERMAGNET_API_KEY="your-key-here"
# save Program.cs, SellerMagnetClient.cs, Models.cs, Retry.cs, LookupRequest.cs,
# ValidationFilter.cs and TtlCache.cs from this post, then:
dotnet run

How do I validate the ASIN and marketplace before spending a credit?

Attach DataAnnotations to a plain DTO, then run them explicitly: minimal APIs do not call Validator.TryValidateObject on their own the way an MVC controller's model binding does. An ASIN is always 10 upper-case letters or digits; the marketplace ID must be one this wrapper actually supports (the full list of all 23 marketplace IDs is in the marketplace IDs list). A failing check returns a 400 before the handler ever opens a connection, so a malformed request never waits on the 120-second timeout and never costs a credit.

LookupRequest.cs - the model-validated DTO

// A model-validated DTO, checked before any network call. Minimal APIs do not run DataAnnotations
// validation on their own (that is an MVC/controller feature); ValidationFilter.cs runs it explicitly.
using System.ComponentModel.DataAnnotations;

namespace AmazonAspNet;

/// <summary>The handful of marketplace IDs this wrapper covers (the same four the Go wrapper's own
/// marketplaceIDs map covers); the full list of all 23 is in the
/// <a href="https://sellermagnet-api.com/blog/amazon-marketplace-ids-list">marketplace IDs guide</a>.
/// A value outside this set fails validation before the client ever spends a credit.</summary>
public sealed class KnownMarketplaceAttribute : ValidationAttribute
{
    public static readonly HashSet<string> Ids =
    [
        "ATVPDKIKX0DER", // amazon.com
        "A1PA6795UKMFR9", // amazon.de
        "A1F83G8C2ARO7P", // amazon.co.uk
        "A13V1IB3VIYZZH", // amazon.fr
    ];

    protected override ValidationResult? IsValid(object? value, ValidationContext context)
    {
        if (value is string id && Ids.Contains(id))
        {
            return ValidationResult.Success;
        }
        return new ValidationResult($"'{value}' is not a marketplace this wrapper serves.");
    }
}

/// <summary>Bound from the route and query string by [AsParameters]; validated by ValidationFilter before
/// the handler runs, so a malformed request never reaches SellerMagnetClient and never costs a credit.</summary>
public sealed class LookupRequest
{
    [Required]
    [RegularExpression("^[A-Z0-9]{10}$", ErrorMessage = "asin must be 10 upper-case letters or digits.")]
    public string Asin { get; set; } = "";

    [Required]
    [KnownMarketplace]
    public string MarketplaceId { get; set; } = "";
}

How does the validation actually run before the handler?

An IEndpointFilter reads the bound LookupRequest out of EndpointFilterInvocationContext.Arguments and calls Validator.TryValidateObject on it. A failure short-circuits the pipeline with TypedResults.ValidationProblem and never calls next(context), so the route handler - and the cache and the client it touches - never runs.

ValidationFilter.cs - runs DataAnnotations before the handler

// Runs System.ComponentModel.DataAnnotations validation on a bound minimal-API parameter before the
// handler executes. Minimal APIs skip DataAnnotations by default (that wiring is an MVC/controller
// feature); this filter is the model-validated-DTO seam the route handler relies on.
using System.ComponentModel.DataAnnotations;

namespace AmazonAspNet;

public sealed class ValidationFilter<T> : IEndpointFilter where T : class
{
    public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
    {
        var target = context.Arguments.OfType<T>().FirstOrDefault();
        if (target is null)
        {
            return await next(context);
        }
        var results = new List<ValidationResult>();
        var ctx = new ValidationContext(target);
        if (!Validator.TryValidateObject(target, ctx, results, validateAllProperties: true))
        {
            // 400 before any network call: the grouped errors below cost nothing to produce.
            var errors = results
                .SelectMany(r => r.MemberNames.DefaultIfEmpty(""), (r, member) => (member, r.ErrorMessage ?? ""))
                .GroupBy(x => x.member)
                .ToDictionary(g => g.Key, g => g.Select(x => x.Item2).ToArray());
            return Microsoft.AspNetCore.Http.TypedResults.ValidationProblem(errors);
        }
        return await next(context);
    }
}

How does the cache stay safe when Kestrel calls the handler per request?

TtlCache<T> is a ConcurrentDictionary keyed by asin:marketplaceId, with each entry carrying its own expiry - the same shape as the Go wrapper's TTLCache, but using a thread-safe collection instead of a mutex-guarded plain map. A lookup within the TTL (300 seconds here) returns the stored result with cached: true and makes no network call at all. This matters more here than in a single-worker process: Kestrel dispatches the handler for every concurrent request on the thread pool, so two lookups for the same ASIN arriving together can corrupt a bare Dictionary. ConcurrentDictionary fixes that corruption risk, but - proven by this post's own tests, not just asserted - it does not turn several concurrent first-time lookups for the same key into one upstream call; a cold cache can still be missed by more than one of them.

TtlCache.cs - a ConcurrentDictionary-backed TTL cache

// A ConcurrentDictionary-backed TTL cache. Kestrel runs one handler invocation per request on the
// thread pool, the same way Gin runs one goroutine per request: a plain Dictionary can corrupt itself
// under that concurrency, so this needs a thread-safe collection, unlike a single-worker-process cache.
using System.Collections.Concurrent;

namespace AmazonAspNet;

public sealed class TtlCache<TValue>
{
    private readonly ConcurrentDictionary<string, (TValue Value, DateTimeOffset Expires)> entries = new();
    private readonly TimeSpan ttl;

    public TtlCache(TimeSpan ttl) => this.ttl = ttl;

    /// <summary>Returns the cached value when present and not expired; an expired entry is removed, not
    /// just ignored, so the dictionary cannot grow forever under a changing ASIN mix.</summary>
    public bool TryGet(string key, out TValue value)
    {
        if (entries.TryGetValue(key, out var entry) && entry.Expires > DateTimeOffset.UtcNow)
        {
            value = entry.Value;
            return true;
        }
        entries.TryRemove(key, out _);
        value = default!;
        return false;
    }

    public void Set(string key, TValue value) =>
        entries[key] = (value, DateTimeOffset.UtcNow + ttl);

    public int Count => entries.Count;
}

What does the minimal-API endpoint itself look like?

Program.cs registers one SellerMagnetClient and one TtlCache<ProductInfo> as singletons, then maps a single GET /lookup/{asin} route. The handler checks the cache, and only on a miss calls the quickstart's own LookupAsync, which runs Retry.cs's policy through the shared HttpClient. ValidationFilter<LookupRequest> is attached with AddEndpointFilter, so it runs before any of this.

Program.cs - the ASP.NET Core minimal-API microservice

// The ASP.NET Core minimal-API microservice: validate, check the cache, then call the quickstart's
// own SellerMagnetClient (SellerMagnetClient.cs/Models.cs/Retry.cs, reused unchanged).
using AmazonAspNet;
using SellerMagnet;

var builder = WebApplication.CreateBuilder(args);

// One client for the whole process (the quickstart's http.Client is already safe for concurrent use;
// Kestrel calls the handler for every request, the same as Gin dispatching one goroutine per request).
builder.Services.AddSingleton(_ => SellerMagnetClient.FromEnv());
builder.Services.AddSingleton(_ => new TtlCache<ProductInfo>(TimeSpan.FromSeconds(300)));

var app = builder.Build();

app.MapGet("/lookup/{asin}", async (
        [AsParameters] LookupRequest request, SellerMagnetClient client, TtlCache<ProductInfo> cache) =>
    {
        var key = $"{request.Asin}:{request.MarketplaceId}";
        if (cache.TryGet(key, out var cached))
        {
            return Results.Ok(new { cached = true, productInfo = cached });
        }
        try
        {
            var info = await client.LookupAsync(request.Asin, request.MarketplaceId);
            cache.Set(key, info);
            return Results.Ok(new { cached = false, productInfo = info });
        }
        catch (ApiException e) when (e.Status == 404)
        {
            return Results.NotFound(new { message = e.Message });
        }
        catch (ApiException e)
        {
            return Results.Problem(detail: e.Message, statusCode: 502);
        }
        catch (HttpRequestException e)
        {
            return Results.Problem(detail: e.Message, statusCode: 502);
        }
        catch (TaskCanceledException)
        {
            // The client's own 120 s timeout fired. The request may still be running upstream and was
            // already billed up front (SellerMagnetClient.cs increments Billed before this is thrown) -
            // a 504 here must never trigger a caller retry, which would spend a second credit.
            return Results.Problem(detail: "upstream did not answer in time", statusCode: 504);
        }
    })
    // Validated before the handler runs, so a malformed request never reaches the cache or the client.
    .AddEndpointFilter<ValidationFilter<LookupRequest>>();

app.Run();

// Exposes the generated Program class to WebApplicationFactory<Program> in the test project.
public partial class Program { }

A client timeout is not the same as a free connection error

The connection-error branch above only ever fires when the request never reached the server at all (nothing listening on the port), so nothing was billed. A client timeout is different: the credit is deducted on the server before the scrape even starts, so a client that gives up waiting and cancels has still paid for an answer it will never see, and that credit is not refunded (refunds only exist for a server-side 500 without Retry-After). This wrapper answers a timeout with 504, not 502, and never retries it - retrying would spend a second credit on the same request.

Terminal flow diagram of a lookup request through validation, cache and the upstream API
A cache hit never reaches the upstream API; a cache miss stores the result before answering.

Trimmed response for a cache-miss lookup

{
  "cached": false,
  "productInfo": {
    "asin": "B0CL61F39H",
    "buyBoxInfo": {"price": 444.99, "currencyCode": "USD"}
  }
}

Retry policy: which errors this wrapper retries

Retry only what can succeed on a second try. A 429 from the per-key concurrency cap is free and carries Retry-After. A 500 without Retry-After is refunded, so one retry costs nothing; a second consecutive 500 stops instead of looping. 502 and 503 are billed on every attempt, so wait and cap the attempts at 4. A connection error never reached the server, so it is retried for free; a timeout is billed up front and never retried.

Scenarios this wrapper's test suite scripts against a fake HttpListener.
ScenarioChargedRetry?Client should
Cache miss, valid ASIN200-Yes (1 credit)
Same lookup again within 300s200 (cached)noNo - 0 upstream calls
Malformed ASIN shape400noNo - rejected before the network
Unknown marketplaceId400noNo - rejected before the network
Lower-case ASIN400noNo - rejected, never normalized
Upstream 404 (not on this marketplace)404noYes - a real answer
Upstream 429 (concurrency cap)200 (after a wait)yes - freeNo - the 429 itself
Upstream 500 (refunded)200 (after 1 retry)yes, capped at 1No - the 500 itself
Two upstream 500s in a row502no - stopsNo - the 500s
Upstream 502 / 503502yes, up to 4 attemptsYes - every attempt
Connection error (never reached the server)502yes, up to 4 attemptsNo - nothing was billed
Client timeout (120s)504noYes - billed up front, not refunded
Table of test scenarios against the SellerMagnet API's status codes, billing and the correct wrapper reaction
Each row needs its own scripted response; a happy-path test alone misses most of this.

Why fake a local HttpListener instead of injecting a mock HttpMessageHandler?

HttpClient does support a custom HttpMessageHandler, but the C# quickstart's own SellerMagnetClient has no injectable handler; its only test seam is the base-URL constructor argument, documented for exactly this purpose. The C# mock-testing post points that same seam at a real local HttpListener (FakeServer.cs, reused unchanged here) instead of a NuGet mocking library, and it fails closed: a request with no scripted response left gets a 500 'no route installed', never a silent pass.

FakeServer.cs - a real local HttpListener, scriptable per test, fails closed

// A real local HTTP server for tests: System.Net.HttpListener, no NuGet package needed.
// Fails closed: a request with no scripted response left gets a 500 "no route installed", never a false pass.
using System.Net;
using System.Text;

namespace SellerMagnet.Tests;

public sealed class FakeServer : IDisposable
{
    private readonly HttpListener listener = new();
    private readonly object sync = new();
    private readonly Queue<ScriptedResponse> queue = new();
    private readonly CancellationTokenSource cts = new();

    public string BaseUrl { get; }
    public int RequestCount { get; private set; }

    public FakeServer()
    {
        // Bind an ephemeral port by asking the OS for one, then reuse it for the listener prefix.
        int port;
        using (var probe = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0))
        {
            probe.Start();
            port = ((IPEndPoint)probe.LocalEndpoint).Port;
        }
        BaseUrl = $"http://127.0.0.1:{port}/";
        listener.Prefixes.Add(BaseUrl);
        listener.Start();
        _ = Task.Run(AcceptLoop);
    }

    /// <summary>Queue one scripted response. FIFO: the Nth request to reach this server gets the Nth entry.</summary>
    public void Enqueue(int status, string body, string? retryAfter = null, int delayMs = 0)
    {
        lock (sync)
        {
            queue.Enqueue(new ScriptedResponse(status, body, retryAfter, delayMs));
        }
    }

    private async Task AcceptLoop()
    {
        while (!cts.IsCancellationRequested)
        {
            HttpListenerContext ctx;
            try
            {
                ctx = await listener.GetContextAsync();
            }
            catch (Exception) when (cts.IsCancellationRequested || !listener.IsListening)
            {
                return;
            }
            _ = Task.Run(() => Handle(ctx));
        }
    }

    private async void Handle(HttpListenerContext ctx)
    {
        // async void: any exception that escapes here crashes the whole process, so this
        // whole body is one try/catch. A timeout test's client gives up mid-response and the
        // server (or the test's own Dispose) can tear the listener down while a write is pending.
        try
        {
            ScriptedResponse resp;
            lock (sync)
            {
                RequestCount++;
                // Fails closed: an un-scripted request is a test bug, not a silent 200.
                resp = queue.Count > 0
                    ? queue.Dequeue()
                    : new ScriptedResponse(500, "{\"success\":false,\"message\":\"no route installed\"}", null, 0);
            }
            if (resp.DelayMs > 0)
            {
                await Task.Delay(resp.DelayMs);
            }
            ctx.Response.StatusCode = resp.Status;
            if (resp.RetryAfter is not null)
            {
                ctx.Response.Headers.Add("Retry-After", resp.RetryAfter);
            }
            var bytes = Encoding.UTF8.GetBytes(resp.Body);
            ctx.Response.ContentType = "application/json";
            ctx.Response.ContentLength64 = bytes.Length;
            await ctx.Response.OutputStream.WriteAsync(bytes);
            ctx.Response.OutputStream.Close();
        }
        catch (Exception)
        {
            // The client gave up (a timeout test) or the test disposed the server already: nothing left to do.
        }
    }

    public void Dispose()
    {
        cts.Cancel();
        listener.Stop();
        listener.Close();
    }

    private readonly record struct ScriptedResponse(int Status, string Body, string? RetryAfter, int DelayMs);
}

What does a full scenario suite look like against the real ASP.NET Core host?

Each test gets its own WebApplicationFactory<Program>, which builds the real host - the real ValidationFilter, the real TtlCache, Kestrel's real request pipeline - in-process. Setting SELLERMAGNET_API_BASE before the factory resolves its DI container points the registered SellerMagnetClient singleton at that test's own FakeServer, so every test exercises the unmodified quickstart client, not a stand-in for it. A dedicated pair of concurrency tests proves the cache's own trade-off: a warm cache serves 8 concurrent requests with zero further upstream calls, while a cold cache racing 5 concurrent first-time lookups can call upstream more than once without corrupting anything - caught by running it, not guessed.

LookupEndpointTests.cs - the scenario suite, run for real below

// Integration tests against the real ASP.NET Core host (WebApplicationFactory<Program>), with
// SellerMagnetClient's own base-URL test seam pointed at a local HttpListener FakeServer - the same
// fake used by the C# mock-testing post, since no HttpMessageHandler injection seam exists in the
// published quickstart. Every test gets its own WebApplicationFactory, so a fresh SellerMagnetClient
// singleton always resolves against that test's own environment variables, not a leftover from the
// previous test's.
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using SellerMagnet;
using SellerMagnet.Tests;
using Xunit;

namespace AmazonAspNet.Tests;

public class LookupEndpointTests
{
    private const string LookupOk =
        """{"success":true,"data":{"productInfo":{"asin":"B0CL61F39H","buyBoxInfo":{"price":444.99,"currencyCode":"USD"}}}}""";
    private const string Err404 = """{"success":false,"message":"Invalid product"}""";
    private const string Err429 = """{"success":false,"message":"Max 40 concurrent requests per API key. Retry shortly."}""";
    private const string Err500 = """{"success":false,"message":"An internal error occurred. Please try again shortly."}""";
    private const string Err502 = """{"success":false,"message":"Bad gateway"}""";
    private const string Err503 = """{"success":false,"message":"Service unavailable"}""";

    private static WebApplicationFactory<Program> MakeFactory(string baseUrl)
    {
        Environment.SetEnvironmentVariable("SELLERMAGNET_API_KEY", "test-key");
        Environment.SetEnvironmentVariable("SELLERMAGNET_API_BASE", baseUrl);
        return new WebApplicationFactory<Program>();
    }

    [Fact]
    public async Task CacheMissThenHit_OnlyOneUpstreamCall()
    {
        using var server = new FakeServer();
        server.Enqueue(200, LookupOk);
        using var factory = MakeFactory(server.BaseUrl);
        using var client = factory.CreateClient();

        var miss = await client.GetAsync("/lookup/B0CL61F39H?marketplaceId=ATVPDKIKX0DER");
        Assert.Equal(HttpStatusCode.OK, miss.StatusCode);
        var missBody = await miss.Content.ReadFromJsonAsync<JsonElement>();
        Assert.False(missBody.GetProperty("cached").GetBoolean());

        var hit = await client.GetAsync("/lookup/B0CL61F39H?marketplaceId=ATVPDKIKX0DER");
        Assert.Equal(HttpStatusCode.OK, hit.StatusCode);
        var hitBody = await hit.Content.ReadFromJsonAsync<JsonElement>();
        Assert.True(hitBody.GetProperty("cached").GetBoolean());

        Assert.Equal(1, server.RequestCount); // the cache hit made zero upstream calls
    }

    [Fact]
    public async Task MalformedAsin_RejectedBeforeAnyNetworkCall()
    {
        using var server = new FakeServer(); // no response queued: a real call here fails the test
        using var factory = MakeFactory(server.BaseUrl);
        using var client = factory.CreateClient();

        var resp = await client.GetAsync("/lookup/short?marketplaceId=ATVPDKIKX0DER");

        Assert.Equal(HttpStatusCode.BadRequest, resp.StatusCode);
        Assert.Equal(0, server.RequestCount);
    }

    [Fact]
    public async Task UnknownMarketplace_RejectedBeforeAnyNetworkCall()
    {
        using var server = new FakeServer();
        using var factory = MakeFactory(server.BaseUrl);
        using var client = factory.CreateClient();

        var resp = await client.GetAsync("/lookup/B0CL61F39H?marketplaceId=NOT-A-MARKET");

        Assert.Equal(HttpStatusCode.BadRequest, resp.StatusCode);
        Assert.Equal(0, server.RequestCount);
    }

    [Fact]
    public async Task UpstreamNotFound_Returns404_BilledOnceNeverRetried()
    {
        using var server = new FakeServer();
        server.Enqueue(404, Err404);
        using var factory = MakeFactory(server.BaseUrl);
        using var client = factory.CreateClient();

        var resp = await client.GetAsync("/lookup/B0NOTFOUND?marketplaceId=ATVPDKIKX0DER");

        Assert.Equal(HttpStatusCode.NotFound, resp.StatusCode);
        Assert.Equal(1, server.RequestCount);
    }

    [Fact]
    public async Task Upstream429_RetriedForFree_ThenSucceeds()
    {
        using var server = new FakeServer();
        server.Enqueue(429, Err429, retryAfter: "0");
        server.Enqueue(200, LookupOk);
        using var factory = MakeFactory(server.BaseUrl);
        using var client = factory.CreateClient();

        var resp = await client.GetAsync("/lookup/B0CL61F39H?marketplaceId=ATVPDKIKX0DER");

        Assert.Equal(HttpStatusCode.OK, resp.StatusCode);
        Assert.Equal(2, server.RequestCount); // the 429 then the retry
    }

    [Fact]
    public async Task Upstream500WithoutRetryAfter_RefundedRetriedOnce_ThenSucceeds()
    {
        using var server = new FakeServer();
        server.Enqueue(500, Err500); // no Retry-After: refunded, retried once
        server.Enqueue(200, LookupOk);
        using var factory = MakeFactory(server.BaseUrl);
        using var client = factory.CreateClient();

        var resp = await client.GetAsync("/lookup/B0CL61F39H?marketplaceId=ATVPDKIKX0DER");

        Assert.Equal(HttpStatusCode.OK, resp.StatusCode);
        Assert.Equal(2, server.RequestCount);
    }

    [Fact]
    public async Task TwoConsecutive500s_StopAt502_NotLooped()
    {
        using var server = new FakeServer();
        server.Enqueue(500, Err500);
        server.Enqueue(500, Err500);
        using var factory = MakeFactory(server.BaseUrl);
        using var client = factory.CreateClient();

        var resp = await client.GetAsync("/lookup/B0CL61F39H?marketplaceId=ATVPDKIKX0DER");

        Assert.Equal(HttpStatusCode.BadGateway, resp.StatusCode);
        Assert.Equal(2, server.RequestCount); // stopped, did not loop to the attempt cap
    }

    [Fact]
    public async Task Upstream502_RetriedUpToFourBilledAttempts()
    {
        using var server = new FakeServer();
        for (var i = 0; i < 4; i++)
        {
            server.Enqueue(502, Err502);
        }
        using var factory = MakeFactory(server.BaseUrl);
        using var client = factory.CreateClient();

        var resp = await client.GetAsync("/lookup/B0CL61F39H?marketplaceId=ATVPDKIKX0DER");

        Assert.Equal(HttpStatusCode.BadGateway, resp.StatusCode);
        Assert.Equal(4, server.RequestCount); // capped at the attempt limit, every one billed
    }

    [Fact]
    public async Task Upstream503_CappedAtAttemptLimit()
    {
        using var server = new FakeServer();
        for (var i = 0; i < 4; i++)
        {
            server.Enqueue(503, Err503);
        }
        using var factory = MakeFactory(server.BaseUrl);
        using var client = factory.CreateClient();

        var resp = await client.GetAsync("/lookup/B0CL61F39H?marketplaceId=ATVPDKIKX0DER");

        Assert.Equal(HttpStatusCode.BadGateway, resp.StatusCode);
        Assert.Equal(4, server.RequestCount);
    }

    [Fact]
    public async Task ConnectionError_RetriedForFree_ThenReturns502()
    {
        // Nothing listens on port 1: every attempt is a real, immediate connection-refused, never billed.
        using var factory = MakeFactory("http://127.0.0.1:1/");
        using var client = factory.CreateClient();

        var resp = await client.GetAsync("/lookup/B0CL61F39H?marketplaceId=ATVPDKIKX0DER");

        Assert.Equal(HttpStatusCode.BadGateway, resp.StatusCode);
    }

    [Fact]
    public async Task LowercaseAsin_RejectedAsMalformed_NotNormalized()
    {
        // This wrapper's validation only accepts upper-case letters and digits, matching the quickstart's
        // own IsAsin check; a lower-case ASIN is a 400, not a silently-normalized lookup.
        using var server = new FakeServer();
        using var factory = MakeFactory(server.BaseUrl);
        using var client = factory.CreateClient();

        var resp = await client.GetAsync("/lookup/b0cl61f39h?marketplaceId=ATVPDKIKX0DER");

        Assert.Equal(HttpStatusCode.BadRequest, resp.StatusCode);
        Assert.Equal(0, server.RequestCount);
    }

    [Fact]
    public async Task ConcurrentLookups_OnAWarmCache_AllHitWithNoCorruption()
    {
        // TtlCache's ConcurrentDictionary makes concurrent reads/writes memory-safe, the same guarantee
        // the Gin wrapper's sync.Mutex gives its map - but neither one single-flights a COLD cache, so
        // several requests racing on the very first lookup for a key can each miss and call upstream.
        // That is this post's own bug #1 (caught by this suite, not guessed): the test below first
        // warms the cache with one serial call, then proves many concurrent requests against the now
        // warm cache never touch the network again and never see a corrupted entry.
        using var server = new FakeServer();
        server.Enqueue(200, LookupOk);
        using var factory = MakeFactory(server.BaseUrl);
        using var client = factory.CreateClient();

        var warm = await client.GetAsync("/lookup/B0CL61F39H?marketplaceId=ATVPDKIKX0DER");
        Assert.Equal(HttpStatusCode.OK, warm.StatusCode);
        Assert.Equal(1, server.RequestCount);

        var responses = await Task.WhenAll(Enumerable.Range(0, 8)
            .Select(_ => client.GetAsync("/lookup/B0CL61F39H?marketplaceId=ATVPDKIKX0DER")));

        Assert.All(responses, r => Assert.Equal(HttpStatusCode.OK, r.StatusCode));
        Assert.Equal(1, server.RequestCount); // every one of the 8 concurrent calls was a cache hit
    }

    [Fact]
    public async Task ConcurrentLookups_OnAColdCache_CanEachMissButNeverCorruptTheCache()
    {
        // The documented trade-off from the test above, proven rather than just described: a cold cache
        // racing 5 concurrent first-time lookups can call upstream more than once (no single-flight),
        // but TtlCache's ConcurrentDictionary never throws and every response still comes back 200.
        using var server = new FakeServer();
        for (var i = 0; i < 5; i++)
        {
            server.Enqueue(200, LookupOk); // enough scripted responses that a racing miss never fails closed
        }
        using var factory = MakeFactory(server.BaseUrl);
        using var client = factory.CreateClient();

        var responses = await Task.WhenAll(Enumerable.Range(0, 5)
            .Select(_ => client.GetAsync("/lookup/B0CL61F39H?marketplaceId=ATVPDKIKX0DER")));

        Assert.All(responses, r => Assert.Equal(HttpStatusCode.OK, r.StatusCode));
        Assert.InRange(server.RequestCount, 1, 5); // dedup is not guaranteed, but every attempt still succeeds
    }

    [Fact]
    public async Task ClientTimeout_Returns504_NeverARetryTrigger()
    {
        // The quickstart's own SellerMagnetClient hardcodes a 120 s timeout with no env override, so this
        // test swaps in a short-timeout client via DI instead of waiting 120 real seconds. The scripted
        // response answers, but only after the client has already given up.
        using var server = new FakeServer();
        server.Enqueue(200, LookupOk, delayMs: 1500);
        Environment.SetEnvironmentVariable("SELLERMAGNET_API_KEY", "test-key");
        Environment.SetEnvironmentVariable("SELLERMAGNET_API_BASE", server.BaseUrl);
        using var factory = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
            builder.ConfigureServices(services =>
                services.AddSingleton(_ =>
                    new SellerMagnetClient(server.BaseUrl, "test-key", TimeSpan.FromMilliseconds(300)))));
        using var client = factory.CreateClient();

        var resp = await client.GetAsync("/lookup/B0CL61F39H?marketplaceId=ATVPDKIKX0DER");

        Assert.Equal(HttpStatusCode.GatewayTimeout, resp.StatusCode);
        Assert.Equal(1, server.RequestCount); // a timeout is never retried
    }
}

dotnet test output (unmodified run)

A total of 1 test files matched the specified pattern.
Passed  AmazonAspNet.Tests.LookupEndpointTests.CacheMissThenHit_OnlyOneUpstreamCall
Passed  AmazonAspNet.Tests.LookupEndpointTests.MalformedAsin_RejectedBeforeAnyNetworkCall
Passed  AmazonAspNet.Tests.LookupEndpointTests.UnknownMarketplace_RejectedBeforeAnyNetworkCall
Passed  AmazonAspNet.Tests.LookupEndpointTests.LowercaseAsin_RejectedAsMalformed_NotNormalized
Passed  AmazonAspNet.Tests.LookupEndpointTests.UpstreamNotFound_Returns404_BilledOnceNeverRetried
Passed  AmazonAspNet.Tests.LookupEndpointTests.Upstream429_RetriedForFree_ThenSucceeds
Passed  AmazonAspNet.Tests.LookupEndpointTests.Upstream500WithoutRetryAfter_RefundedRetriedOnce_ThenSucceeds
Passed  AmazonAspNet.Tests.LookupEndpointTests.TwoConsecutive500s_StopAt502_NotLooped
Passed  AmazonAspNet.Tests.LookupEndpointTests.Upstream502_RetriedUpToFourBilledAttempts
Passed  AmazonAspNet.Tests.LookupEndpointTests.Upstream503_CappedAtAttemptLimit
Passed  AmazonAspNet.Tests.LookupEndpointTests.ConnectionError_RetriedForFree_ThenReturns502
Passed  AmazonAspNet.Tests.LookupEndpointTests.ClientTimeout_Returns504_NeverARetryTrigger
Passed  AmazonAspNet.Tests.LookupEndpointTests.ConcurrentLookups_OnAWarmCache_AllHitWithNoCorruption
Passed  AmazonAspNet.Tests.LookupEndpointTests.ConcurrentLookups_OnAColdCache_CanEachMissButNeverCorruptTheCache

Passed!  - Failed: 0, Passed: 14, Skipped: 0, Total: 14, Duration: 55 s - AmazonAspNet.Tests.dll (net8.0)

Never fake a layer your own code implements

A fake that reimplements the handler's cache check or Retry.cs's own backoff tests the fake's own logic, not the real wrapper. Fake one layer below your code - here, the HTTP server the quickstart client talks to over the network - so a real bug in the validation, caching or retry logic still shows up as a failing test.

Does the same pattern work for other languages?

Yes, fake the one call the real code makes to the network, whichever shape that takes. The Go Gin wrapper fakes http.RoundTripper, the Spring Boot wrapper reuses an embedded HttpServer, and this guide points SellerMagnetClient's own base-URL constructor argument at a local HttpListener instead, since no in-process handler injection seam exists in the published quickstart. The 429/Retry-After guide and the 502/503 retry guide are the production behaviour this suite checks against; keep both in sync when the retry logic changes. Credit costs and the free trial are on the pricing page, and every endpoint's parameters are in the API documentation.

Frequently Asked Questions

Does minimal API validate DataAnnotations automatically?

No. That wiring is an MVC/controller feature. A minimal API needs an explicit IEndpointFilter (or the newer built-in validation support in later SDKs) that calls Validator.TryValidateObject before the handler runs.

Why ConcurrentDictionary instead of a plain Dictionary with a lock object?

Either works for correctness. ConcurrentDictionary avoids an explicit lock statement and reads without blocking writers to other keys, which matters once a handler is called concurrently for many different ASINs, not just the same one.

Is there a C# SDK for the SellerMagnet API?

No, and none is needed. Every endpoint is a plain GET with query parameters and a JSON body, so HttpClient and System.Text.Json from the base library cover it.

Why does a cold cache allow more than one upstream call for the same key?

Because TryGet and Set are two separate operations: two requests can both miss before either one writes the result. Preventing that needs a single-flight pattern (a per-key lock held across the whole fetch), which this wrapper does not add, the same trade-off the Go and Java wrappers in this series leave undocumented in code but proven here by a dedicated test.

Can I use Polly instead of the quickstart's own Retry.cs?

Yes, with changed defaults. Microsoft's standard resilience handler cuts each attempt after 10 seconds and retries timeouts, 408, 429 and 5xx up to 3 times within 30 seconds; against this API that turns one slow lookup into several billed ones. Raise the timeouts to 120 seconds and stop it from retrying timeouts.

Bottom line: an IEndpointFilter that runs DataAnnotations before the handler, a ConcurrentDictionary-backed TTL cache that is memory-safe but not single-flighted, and the quickstart's own SellerMagnetClient, Models and Retry reused unchanged. The same client exists for Go and Java, and every endpoint is in the API documentation.

Related Articles

Continue exploring topics related to this article.

Code editor showing an Elixir validation pipeline rejecting a malformed lookup request before any network call
Amazon API Performance Elixir

Wrap an Amazon Product API in an Elixir Plug Microservice: Caching and Validation

Wrap the SellerMagnet API in a small Elixir microservice built on Plug (the toolkit Phoenix itself sits on): a validation module checks the ASIN and marketplace before any network call, a public ETS table answers repeat lookups for free, and the Elixir quickstart's own client.ex, retry.ex and product.ex are reused completely unchanged. Every scenario is run against the real Plug router and a fails-closed fake HTTP server, not described by hand.

Dec 05, 2026 Read
Terminal window validating a lookup request before any network call in a Sinatra route
Amazon API Ruby Performance

Wrap an Amazon Product API in a Ruby Sinatra Microservice: Caching and Validation

Wrap the SellerMagnet API in a small Sinatra microservice: a regex and a Hash membership check validate the ASIN and marketplace before any network call, a mutex-guarded TTL cache answers repeat lookups for free, and the Ruby quickstart's own seller_magnet.rb client and retry policy are reused unchanged. Every scenario, including concurrent requests sharing one cache, runs with Minitest and Rack::Test against a fails-closed fake Net::HTTP layer, not described by hand.

Dec 04, 2026 Read
Terminal window showing a NestJS DTO rejecting a malformed ASIN before any network call
Amazon API Typescript Nodejs

Wrap an Amazon Product API in a NestJS Microservice: Caching and DTO Validation

Wrap the SellerMagnet API in a NestJS microservice: class-validator DTOs reject a bad ASIN or marketplace before any network call, a short-lived in-process cache answers repeat lookups for free, and the TypeScript quickstart's own typed client and retry policy are reused unchanged. Every scenario is run against a fails-closed fake HTTP layer, not described by hand.

Dec 04, 2026 Read
Back to Blog

Ready to Extract Amazon Data at Scale?

Start building with SellerMagnet API today. Real-time product data, competitive pricing, and review analytics at your fingertips.

150 free API credits • No credit card required • Cancel anytime