> ## Documentation Index
> Fetch the complete documentation index at: https://elastly.io/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Java SDK

> Price lines with a hard deadline and a fallback, verify webhooks, and sync a connector, from Java.

The `io.elastly:elastly-sdk` artifact is the supported way to call Elastly from Java. The request and
response types are generated from the same [OpenAPI contract](/docs/api/overview) our servers validate
against, so they cannot drift from the API. On top of that it adds what every integration needs: a price
call that never breaks your quote screen, typed errors, webhook verification, and a connector that
pages, checkpoints, retries, and reports for you.

```xml theme={null}
<dependency>
  <groupId>io.elastly</groupId>
  <artifactId>elastly-sdk</artifactId>
  <version>0.2.0</version>
</dependency>
```

Or with Gradle:

```groovy theme={null}
implementation 'io.elastly:elastly-sdk:0.2.0'
```

Java 8 or later.

## Keys and scopes

Create API keys under [Settings → API keys](https://app.elastly.io/settings). Scopes are separate on
purpose: a serving key can never write your catalog, and a connector key can never read prices.

| Scope         | Used for               | SDK surface                                         |
| ------------- | ---------------------- | --------------------------------------------------- |
| **ERP**       | Price serving          | `PricesNamespace`                                   |
| **Connector** | Ingest and write-backs | `IngestApi`, `WritebacksApi`, `ConnectorDefinition` |

```java theme={null}
import io.elastly.sdk.ApiClient;
import io.elastly.sdk.transport.ElastlyTransport;
import io.elastly.sdk.serving.PricesNamespace;

ApiClient apiClient = new ApiClient();
apiClient.setBearerToken("elastly_live_...");

PricesNamespace prices = new PricesNamespace(ElastlyTransport.builder(apiClient).build());
```

## The one thing to get right: the decision id

Every priced line comes back with a pricing decision id. **Store it in your own system, on the quote
line it priced.** When that quote later closes and you send it back to Elastly, the id ties what Elastly
recommended to what your rep actually charged. That difference is what the model learns from.

Skip it and everything still looks like it works: prices serve, quotes ingest, dashboards fill. But the
model learns nothing from your quotes, and nothing tells you. So wire it first:

```java theme={null}
PriceResult result = prices.get(line, failOpen);

if (result.getSource() == PriceResult.Source.ELASTLY) {
    ElastlyPrice priced = (ElastlyPrice) result;
    priced.getPricingDecisionId().ifPresent(id ->
        erp.updateQuoteLine(quoteLineId, priced.getPriceCents(), id));
}
```

## Price a line, with a fallback

A price call usually runs inside a rep's quote screen or a checkout render. If Elastly is slow or down,
your system must keep working. The SDK makes that a policy you declare, not code you write:

```java theme={null}
import io.elastly.sdk.serving.*;
import io.elastly.sdk.model.PricesRequestLinesInner;
import java.math.BigDecimal;
import java.util.Optional;

PricesRequestLinesInner line = new PricesRequestLinesInner()
    .productSku("VLV-200")
    .customerExternalId("cust-1042")
    .quantity(new BigDecimal(25));

FailOpenPolicy failOpen = FailOpenPolicy
    .staticFallback((l, cause) -> Optional.of(new FallbackPrice(erp.listPrice(l.getProductSku()), "USD")))
    .withDeadlineMs(800);

PriceResult result = prices.get(line, failOpen);

switch (result.getSource()) {
    case ELASTLY:
        ElastlyPrice priced = (ElastlyPrice) result;
        render(priced.getPriceCents(), priced.getReasonSummary());
        break;
    case FALLBACK:
        render(((FallbackPriceResult) result).getPriceCents()); // getCause().getReason() tells you why
        break;
    case UNAVAILABLE:
        // no price available
        break;
}
```

Under this policy a timeout, a 5xx, a rate limit, a malformed body, or a network failure never throws.
The SDK retries where it can, then calls your fallback and returns a `FallbackPriceResult` with the
cause attached. If your fallback returns `Optional.empty()`, you get an `UnavailablePrice`, an explicit
typed no-answer.

Requests that mean your call is wrong (`invalid_request`, `feature_not_enabled`) always throw a typed
error, because a bug in your integration is not an outage to paper over. For batch jobs where a wrong
price is worse than no price, use `throwOnFailure`, which throws on everything:

```java theme={null}
List<PriceResult> results = prices.getMany(lines, FailOpenPolicy.throwOnFailure());
```

`getMany` prices up to 100 lines in one HTTP call. One unknown SKU fails that line alone, never the
whole batch.

## Typed errors

Every error is a typed exception carrying the stable error code and the request id, so support can find
the exact call. Catch the specific class or the base:

```java theme={null}
import io.elastly.sdk.errors.*;

try {
    prices.get(line, FailOpenPolicy.throwOnFailure());
} catch (RateLimitException e) {
    e.getRetryAfterMs().ifPresent(ms -> backoff(ms));
} catch (UnknownProductException e) {
    System.out.println(e.getRequestId().orElse(null));
} catch (ElastlyApiException e) {
    System.out.println(e.getApiErrorCode() + " " + e.getStatus());
}
```

There is one exception per API error code (`UnknownProductException`, `NoCostBasisException`,
`MonthlyVolumeExceededException`, and the rest), all extending `ElastlyApiException`, which extends
`ElastlyException`. Catch `ElastlyException` to handle anything, including network and timeout faults.

## Verify a webhook

```java theme={null}
import io.elastly.sdk.webhooks.*;

try {
    VerifiedWebhookEvent event =
        Webhooks.verify(rawBody, request.getHeader("Elastly-Signature"), secret);

    if (event.isOfType("sync.completed")) {
        // handle it
    }
} catch (SignatureVerificationException e) {
    response.setStatus(400);
}
```

`verify` checks the signature in constant time, rejects anything older than five minutes, and returns a
typed event. It throws `SignatureVerificationException` on a bad signature, a replay, or a malformed
body. The four event types are `sync.completed`, `recommendation.created`, `price.written_back`, and
`test.ping`.

## What the SDK handles for you

* **Idempotency.** Every mutating call carries a key that stays stable across retries, so a retried
  price call can never double-count against your plan.
* **Retries.** Failed calls back off with full jitter and honor `Retry-After` and `RateLimit-Reset`.
* **A circuit breaker.** After repeated failures it stops hammering Elastly and goes straight to your
  fallback, then probes once to recover.
* **Fail-open telemetry.** Every call that falls open reports itself to Elastly (fire and forget, never
  on your latency path), so an outage that hit your quote screen shows up in your dashboard.

## Build a connector

To push your own ERP or storefront into Elastly, the SDK ships a connector runtime: implement a few
methods that read your data, and `ConnectorDefinition` runs the whole sync, with paging, checkpoints,
retries, and write-back leases handled for you.

<Card title="Build a connector" icon="wrench" href="/docs/sdks/build-a-connector">
  Feed your data in, apply approved prices back, in Java or any other language.
</Card>

## Versioning

The SDK's major version is bound to the API version in the URL. Every `0.x` and `1.x` release talks to
`/api/v1`, so an upgrade within a major is always safe.

The source is on [GitHub](https://github.com/elastly/elastly-java). It is generated, so file an issue
rather than a pull request against generated code.
