The Amazon B2b Data Interchange SDK for .NET provides access to the Amazon B2b Data Interchange REST APIs from .NET applications.
Tip
Looking for a specific signature, model, enum, or error type? This SDK ships a generated, machine-readable SDK map — a lookup index of the SDK's entire C# surface. Consult it before grepping or scanning the source tree; it answers most contract questions directly and, when a source file is genuinely needed, names the exact one to open. Details under SDK map.
Generated from AWS's published Smithy model for AWS B2B Data Interchange. 5 operation(s).
Add the .NET SDK as a project reference into your solution:
dotnet add reference <path-to-sdk>/src/AmazonB2BDataInterchange/AmazonB2BDataInterchange.csprojThe project takes its build settings from the files around it, so reference it in place. Building from source needs the .NET 10 SDK (C# 14).
The package holds two builds. A .NET 10 or later application gets the net10.0 build, which depends on Microsoft.Bcl.AsyncInterfaces, Microsoft.Bcl.TimeProvider, Microsoft.Extensions.Http and Microsoft.Extensions.Logging.Abstractions. Every other runtime gets the netstandard2.0 build, among them .NET Framework 4.6.2 and later and .NET 8 and 9. Both builds have the same public API, and a library built against one build runs against the other: a .NET Standard 2.0 library that uses the SDK works in a .NET 10 application.
On .NET Framework:
- The SDK writes a number such as
99.99as99.99in bodies, query values and headers. If you serialize an SDK model yourself, System.Text.Json writes 17 digits there (99.989999999999995). The value is the same; only the text is longer.
The assembly embeds its PDB, so stack traces carry SDK file and line numbers.
dotnet pack src/AmazonB2BDataInterchange/AmazonB2BDataInterchange.csproj -c ReleaseRelease packs come from CI, where CI=true makes the build deterministic; to reproduce that locally add -p:ContinuousIntegrationBuild=true.
The generator never emits Directory.Build.targets, so a customer-owned one at the repo root is MSBuild's auto-imported customization seam. It imports after the props and the project body into every project under the root, so put SDK-only settings under <PropertyGroup Condition="'$(MSBuildProjectName)' == 'AmazonB2BDataInterchange'">.
It overrides every property the SDK reads when targets run (package metadata, Version, AssemblyVersion, compiler warnings, package references, which under central package management use VersionOverride). It cannot change values the SDK derives earlier: TargetFramework(s), AssemblyName and output paths stay generator settings; turning off GenerateDocumentationFile also needs <DocumentationFile />; a ContinuousIntegrationBuild set there also needs <DeterministicSourcePaths>true</DeterministicSourcePaths>.
The SDK's props files are a boundary: a parent repository's Directory.Build.props does not apply, while a parent Directory.Build.targets does.
APIMatic's delivery tools do not yet preserve Directory.Build.targets across regeneration — list it in .codegenignore when publishing to GitHub.
Register the client with IServiceCollection and resolve it from the container. Configure the client's behavior through AmazonB2BDataInterchangeClientOptions.
services.AddAmazonB2BDataInterchangeClient(options =>
{
options.Sigv4 = "YOUR_API_KEY";
options.Environment = ServerEnvironment.Production;
// TODO: configure more client options here
});AddAmazonB2BDataInterchangeClient registers the client as a singleton over its own named IHttpClientFactory client and returns that registration's IHttpClientBuilder. Chain any IHttpClientBuilder extension onto it to customize the SDK's transport — handlers, proxies, client certificates — without touching the HttpClient any other part of your application uses. The client keeps its handler for the process lifetime, so refresh pooled connections there if your API's DNS changes:
services.AddAmazonB2BDataInterchangeClient(options =>
{
// TODO: configure the client options as above
})
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
{
PooledConnectionLifetime = TimeSpan.FromMinutes(5),
});The named client has no timeout of its own: AddAmazonB2BDataInterchangeClient sets its HttpClient.Timeout to Timeout.InfiniteTimeSpan, so AmazonB2BDataInterchangeClientOptions.Timeout is the only one. If you do want a transport timeout, chain .ConfigureHttpClient(client => client.Timeout = …) onto the returned builder.
Note: the SDK applies its own retry policy. If you add a resilience handler such as
AddStandardResilienceHandler(), disable the SDK's retries withoptions.Retry = RetryOptions.Disabled()so attempts don't multiply.
Create the client by passing an HttpClient you manage yourself. Configure the client's behavior through AmazonB2BDataInterchangeClientOptions.
var httpClient = new HttpClient { Timeout = Timeout.InfiniteTimeSpan };
// TODO: configure more client options here
var options = new AmazonB2BDataInterchangeClientOptions
{
Sigv4 = "YOUR_API_KEY",
Environment = ServerEnvironment.Production,
};
var client = new AmazonB2BDataInterchangeClient(httpClient, options);Whichever way you created it, call an operation on the client and await it; with dependency injection, take AmazonB2BDataInterchangeClient as a constructor parameter. The API reference has a sample for every operation.
await client.Capabilities.CreateCapability(new CreateCapabilityOperationRequest
{
XAmzTarget = XAmzTarget.B2BiCreateCapability,
});Every credential is an option on AmazonB2BDataInterchangeClientOptions. A static credential can also come from a provider that is asked on every request, so a rotated secret reaches the next call without rebuilding the client:
var options = new AmazonB2BDataInterchangeClientOptions
{
Sigv4Provider = async ct => await vault.ReadAsync("api-key", ct),
};When a server answers 401 Unauthorized:
- A call with a static credential (bearer token, API key, basic auth) is not retried; a provider, if you set one, is asked again on the next call, not on this one. A throwing operation raises
ApiExceptionwithStatusCode401.
An operation sends only the credentials its API declares. If a required credential is not configured, the call fails before anything is sent with an AuthSchemeException that names the scheme (… requires the Sigv4 scheme, which is not configured.). A credential that is set but blank is treated as configured and sent as-is: the SDK checks presence, never content.
Any credential option left null is read from an environment variable when the client is constructed. The variable name is the SDK name and the option's name, each in upper snake case, plus the member name for multi-member credentials:
| Option | Environment variables |
|---|---|
Sigv4 |
AMAZON_B2_BDATA_INTERCHANGE_SIGV4 |
| logging | AMAZON_B2_BDATA_INTERCHANGE_LOG = info, debug or trace (read only when no ILoggerFactory is set; AddAmazonB2BDataInterchangeClient always supplies the container's) |
Rules:
- A value set in code always wins over the environment, including the placeholder assignments in the Quick Start samples; delete the line for any credential you supply through an environment variable.
- A variable that is unset, empty or whitespace counts as not configured.
- Variables are read once, when the client is constructed. Changing them afterwards has no effect on an existing client.
Hosted applications that already use the .NET options pattern can bind the whole options object from IConfiguration instead, which picks up environment variables through the configuration provider (AmazonB2BDataInterchange__Sigv4, and so on):
services.AddAmazonB2BDataInterchangeClient(options => configuration.GetSection("AmazonB2BDataInterchange").Bind(
options));Both paths coexist: a slot the bound configuration leaves null still falls back to its environment variable.
For code examples and error responses, see API Reference.
Every enum the spec declares is a sealed class with one public static readonly member per value (XAmzTarget.B2BiCreateCapability), a JSON converter, and a Match that makes handling exhaustive: one on{Member} arm per known value, then otherwise, which receives the raw wire value the server sent when it is one this SDK does not declare.
var label =
received.Match(onB2BiCreateCapability: () => "B2BiCreateCapability", otherwise: raw => $"undeclared ({raw})");Prefer named arguments as above. The arms are positional, in the order the spec lists its values, and a regenerated SDK that adds or moves a value changes the Match signature: a positional call site compiled against the old shape either stops compiling or, if the assembly is not rebuilt, throws MissingMethodException at the first call, and a reordered value can rebind a positional argument to a different member without any diagnostic. Treat an added or moved enum value as a breaking change of that enum. Code that must survive regeneration untouched compares instead of matching: received == XAmzTarget.B2BiCreateCapability or received.Is(rawValue) against a raw wire value; neither reopens construction.
A value the SDK does not declare still round-trips: IsKnownValue() tells you whether it is one of the generated members, and sending the instance back echoes the server's own casing. You cannot construct an undeclared value yourself — there is no public factory — so a typo cannot compile; resolve a raw value with XAmzTarget.TryGetKnownValue("B2BI.CreateCapability", out var known).
A spec value whose name would collide with the enum's own name, with a member every enum inherits or generates (such as Value, Match or IsKnownValue), or with a member of object takes a Member suffix — a value value becomes ValueMember — and the other members keep their plain names.
This SDK ships a generated SDK map — sdk-map.md plus the map/ pages — a deterministic, lookup-oriented table of contents of the SDK's C# surface, generated by APIMatic alongside this SDK.
Read it before scanning the source. Whether you are an AI coding assistant or searching by hand, the map answers "what is the exact …" by lookup for every call-level contract, and for anything it does not carry it names the one file that does — so you never have to search the source tree:
sdk-map.md— the index: client construction, servers/auth, the options/retry reference, the SDK-wide defaults the operation rows rely on, and link tables intomap/.map/operations/— one page per controller: the exact C# signature, the return type, the error type with its typedTryGet…accessors, and pagination — plus, per operation, a Type sources table naming the file that declares every type that operation mentions.
Model shapes — record fields with their JSON wire names, enum member names and wire values, OneOf/AnyOf union variants — are not duplicated in the map. Take the path from the operation's Type sources table and read the declaring file; it is the single source of truth and cannot go stale against the code.
Each operation row states what is specific to that operation. The SDK-wide defaults are stated once in sdk-map.md — throw-only (no Result-style no-throw variants), no pagination, the four fixed RawError accessors, the Default server group — and a row appears only where its operation departs from one. A row silent on pagination is telling you that operation has none.
The HTTP verb and route, and the endpoint's behavioural prose, live on the operation itself, in the source file named at the top of its operations page. Read them there when something needs them — wiring a mock, reading a provider log, or settling a rule about what you must pass.
Workflow: look the fact up in the map → where the map leaves something ambiguous, open the one source file the row names → the compiler is the backstop (a name that isn't in the map won't build). Don't scan or grep the tree to find things — the map is the locator.
The map and the API Reference answer different questions, and the map is generated from this SDK's source so it stays in lockstep with the code it describes.
| Use | For |
|---|---|
sdk-map.md + map/ |
Traversing the SDK and working out its surface — locating the operation you need (this SDK exposes 30 operations), its exact signature and request record, the shape and JSON wire names of the models it takes and returns, which error type it throws and how to read it, and the source file behind any of it. This is the index to consume the SDK from, and the one to reach for first. |
api-reference.md |
Usage guidance for a single operation once you know which one you want — a runnable code sample, a link to its request record, and the error responses it can return. |
The SDK retries a failed request itself, with backoff, and bounds every attempt with a timeout. Both are set on AmazonB2BDataInterchangeClientOptions:
| Option | Default | Meaning |
|---|---|---|
Timeout |
100 s | Time each attempt may take to receive the response, not the time for the whole call |
StreamReadTimeout |
60 s | Longest wait between two events of a Server-Sent Events stream |
Retry.MaxRetries |
3 | Retries after the first attempt |
Retry.Delay |
1 s | Wait before the first retry |
Retry.BackoffFactor |
2 | Each wait is the previous one multiplied by this; 1 keeps it constant |
Retry.MaxJitter |
500 ms | Upper bound of the random time added to each wait |
Retry.StatusCodesToRetry |
408, 425, 429, 500, 502, 503, 504 | The statuses that are retried |
Retry.IdempotentMethods |
GET, HEAD, PUT, DELETE, OPTIONS |
The methods that are safe to repeat |
var options = new AmazonB2BDataInterchangeClientOptions
{
Timeout = TimeSpan.FromSeconds(30),
Retry = new RetryOptions { MaxRetries = 5, Delay = TimeSpan.FromSeconds(2) },
};What is retried:
- Only a status in
StatusCodesToRetryis retried. With an empty list no status is retried. 408,425,429and503are retried on every method,POSTincluded. With these statuses the server says it did not process the request.- Every other status in the list, a network failure and a timed-out attempt are retried only on a method in
IdempotentMethods, because the server may already have acted. The SDK sends anIdempotency-Keyheader with every non-GET call, a fresh value per call unless the operation's request record carries that header; if your API honours it, addHttpMethod.PostandHttpMethod.PatchtoIdempotentMethods. - A request whose body cannot be sent twice (a file or stream upload) is never retried.
Before retry n the SDK waits Delay × BackoffFactor^(n−1) plus the jitter, and never more than one minute. When the response carries a Retry-After header with a positive value, the SDK waits that long instead, again capped at one minute.
RetryOptions.Disabled() turns retries off. A negative MaxRetries, Delay or MaxJitter, or a BackoffFactor below 1, throws ArgumentOutOfRangeException when the client is constructed.
Timeouts:
Timeoutapplies to each attempt, so a call with three retries can take up to four timeouts plus the waits between them. A timed-out attempt on an idempotent method is retried; when no retry is left, the call throwsSdkTimeoutException.- The clock of an attempt starts when the request is sent and stops when the whole response has been received, body included. A response that stalls part-way is a timed-out attempt, and one that breaks off part-way is a network failure; both are retried like any other. Set
Timeoutlong enough for the largest response you expect. - A file download and a Server-Sent Events stream are handed to you while they arrive, so for them the clock stops when the response headers arrive; an error response is still received in full. After that,
StreamReadTimeoutbounds the wait for each event of a stream, and cancelling yourCancellationTokenends the stream and releases its connection. A download's stream is yours to read, and no timeout applies to it: dispose theBinaryContentto abandon a read that hangs. - Getting a credential (an OAuth2 token request, a credential provider) and your hooks run outside that window. They are not timed, so a slow provider or hook is never reported as a timeout. Pass a
CancellationTokento the call if one of them can hang. Timeout.InfiniteTimeSpanremoves the limit, forTimeoutand forStreamReadTimeout. Zero or a negative value throwsArgumentOutOfRangeExceptionwhen the client is constructed.- The
HttpClient.Timeoutof a client you construct yourself still applies and cuts an attempt short when it is the shorter of the two, so set it toTimeout.InfiniteTimeSpanas the Quick Start does;AddAmazonB2BDataInterchangeClientdoes that for its own client. When it does elapse, it is reported asSdkTimeoutExceptionand the attempt is retried like any other timeout. - A timeout set on the handler, such as
SocketsHttpHandler.ConnectTimeout, is reported asSdkConnectionExceptionand retried like any other network failure whenHttpClient.Timeoutis infinite. Under a finiteHttpClient.Timeoutthe runtime does not tell the two apart, so it is reported asSdkTimeoutExceptionnamingHttpClient.Timeout.
Every operation takes an optional RequestOptions, after its request record when it has one. It changes these settings for that one call:
| Property | Effect on the call |
|---|---|
Timeout |
Replaces AmazonB2BDataInterchangeClientOptions.Timeout for each attempt |
MaxRetries |
Replaces Retry.MaxRetries |
Headers |
Adds or replaces request headers; a null value removes a header |
LogLevel |
Sets the level of the SDK's log lines for this call, in place of the client's header and body switches: a higher level suppresses lines, Debug adds the headers and Trace adds the request body, even when the client's Logging options leave them off |
Hooks |
Hooks that run after the client-wide ones |
using AmazonB2BDataInterchange.Core;
var requestOptions = new RequestOptions { Timeout = TimeSpan.FromSeconds(10), MaxRetries = 0 };- Pass it as the
requestOptionsargument. A property leftnulluses the client's value. MaxRetriesmay be higher than the client's value and works on a client built withRetryOptions.Disabled(). It never makes an upload that cannot be sent twice retry.Timeoutis per attempt, like the client's, andTimeout.InfiniteTimeSpanremoves the limit for the call. A value longer than theHttpClient.Timeoutof a client you constructed yourself is still cut by that client.- A zero or negative
Timeout, or a negativeMaxRetries, throwsArgumentOutOfRangeExceptionfrom the call, before anything is sent. - On a paginated operation the options apply to every page request.
The SDK logs each retry as a warning before the wait starts, as event 1006 (HttpRetrying):
HTTP GET … retrying in 00:00:01.2140000 (retry 1/3): 503 ServiceUnavailable
- The entry carries
Method,Url,Delay,Retry,MaxRetriesandReasonas structured values.Reasonis the status, or the exception type for a network failure or a timeout (SdkConnectionException,SdkTimeoutException), in which case the exception is attached to the entry. - Hooks run for every attempt, so
SdkHook.OnRequestsees each request that is sent again andSdkHook.OnResponseeach response that led to a retry. - There is no retry callback:
RetryOptionsholds only settings.
Operations throw when the server answers with an error status. TError is the operation's error type from the spec — RawError (the status code plus the raw body) when the spec declares none.
using AmazonB2BDataInterchange.Core.Exceptions; // the exception family
using AmazonB2BDataInterchange.Errors; // generated error types such as CreateCapabilityError
using AmazonB2BDataInterchange.Requests.Capabilities; // request records such as CreateCapabilityOperationRequest
using AmazonB2BDataInterchange.Models.Enums; // models such as XAmzTarget
try
{
await client.Capabilities.CreateCapability(new CreateCapabilityOperationRequest
{
XAmzTarget = XAmzTarget.B2BiCreateCapability,
});
}
catch (ApiException<CreateCapabilityError> ex)
{
// "POST <server>/#CreateCapability returned 400 (BadRequest)."
Console.Error.WriteLine(ex.Message);
if (ex.Error.TryGetNoContent(out var noContent))
{
// TODO: handle 'noContent' of type RawError
}
}Match on an error type is exhaustive: one on{Arm} arm per body the operation declares, each receiving the parsed body, and a last otherwise arm that receives the RawError (status code plus raw body) of a status the operation does not declare, such as a gateway's 502. An arm is a body, not a status: statuses that share a body share an arm, and the status itself is on result.StatusCode or ex.StatusCode. TryGet{Arm} reads one arm when that is all you need, as in the catch above; TryGetRawError is the accessor behind otherwise.
Prefer named arguments, as with enums and unions: the arms are positional, in the order of their names, and a regenerated SDK whose operation gains or loses an error body changes the Match signature — a positional call site stops compiling or, if the assembly is not rebuilt, throws MissingMethodException at the first call. Treat an added or removed error body as a breaking change of that error type. A status added for a body the operation already declares changes nothing. Code that must survive regeneration untouched uses the TryGet{Arm} accessors instead.
Everything the SDK raises for a call derives from SdkException, which carries the failed call's Method and RequestUri. Every message starts with that call, and the underlying cause is always InnerException.
| Exception | When | Extra members |
|---|---|---|
ApiException<TError> |
The server answered with an error status | Error, plus StatusCode, Headers and ContentType from ApiException |
ResponseDeserializationException |
A response body did not match the type the spec declares | TargetType, plus the ApiException members |
SdkConnectionException |
The request could not be sent, or the connection failed before the whole response was received | |
SdkTimeoutException |
An attempt, the transport, or a Server-Sent Events stream went silent (derives from SdkConnectionException) |
Timeout |
AuthSchemeException |
A required credential is not configured, a provider returned nothing, or a credential could not be applied — for example the OAuth2 token endpoint refused it or did not answer | SchemeFailures |
Catch from specific to general: ApiException means the server answered, SdkConnectionException means it did not, and SdkException is everything the SDK raises. Your own cancellation surfaces as the usual OperationCanceledException, never wrapped.
Tip
Use a single AmazonB2BDataInterchangeClient instance for the lifetime of your application and
reuse it across all requests. Creating a new instance per request might exhaust the
connection pool.
Tip
Let the SDK own timeouts. AmazonB2BDataInterchangeClientOptions.Timeout bounds each attempt (default 100 s),
and a timed-out attempt is retried under the retry policy before it surfaces as
SdkTimeoutException. When you construct the HttpClient yourself, set its Timeout to
Timeout.InfiniteTimeSpan (or comfortably above the SDK's) so the transport does not race the
SDK; AddAmazonB2BDataInterchangeClient does that for its own client. See
Retries and Timeouts.
Tip
The SDK reads time only through AmazonB2BDataInterchangeClientOptions.TimeProvider (default
TimeProvider.System): retry backoff, Retry-After, the SSE idle timeout, OAuth2 token
expiry and the logged request durations all follow it. Under AddAmazonB2BDataInterchangeClient a
TimeProvider registered in the container is picked up automatically, and setting the
option explicitly wins. To fake time in your own tests use a provider that implements
timers, such as FakeTimeProvider from Microsoft.Extensions.TimeProvider.Testing, so
retries and idle timeouts advance with it.
This SDK is distributed under the MIT License.
Refer to the API reference for detailed information on available operations with code samples.