# Java
Source: https://www.desktopaccountingapi.com/docs/sdks/java/

> Install and use the Desktop Accounting API Java SDK, with BigDecimal money, Iterable pagination, typed exceptions and safe retries.

Maven:

```xml
<dependency>
  <groupId>com.desktopaccountingapi</groupId>
  <artifactId>quickbooks-desktop</artifactId>
  <version>0.12.1</version>
</dependency>
```

Gradle:

```kotlin
implementation("com.desktopaccountingapi:quickbooks-desktop:0.12.1")
```

Requires Java 11 or newer. The SDK has no runtime dependencies: HTTP goes through `java.net.http.HttpClient` and JSON through the SDK's own codec. Models and inputs are in `com.desktopaccountingapi.quickbooksdesktop.models`.

## Create a client

```java
import com.desktopaccountingapi.quickbooksdesktop.DesktopAccountingApiClient;
import java.time.Duration;

DesktopAccountingApiClient client = DesktopAccountingApiClient.builder()
    .apiKey(System.getenv("DAAPI_SECRET_KEY"))
    .timeout(Duration.ofSeconds(100))
    .maxRetries(2)
    .build();

// Or read DAAPI_SECRET_KEY and DAAPI_BASE_URL from the environment
DesktopAccountingApiClient fromEnv = DesktopAccountingApiClient.fromEnv();

DesktopAccountingApiClient qb = client.forEndUser("eu_01j9x4m6v4c8k2t7q0r5s3w1zb");
```

The client is thread-safe. Create one and call `forEndUser` per customer.

## Make calls

Inputs take required fields in the constructor and optional fields through fluent setters. Response models are immutable, with accessors named after the fields (`invoice.refNumber()`).

```java
Customer customer = qb.qbd().customers().create(
    new CustomerCreateInput("Northwind Traders").email("ap@northwind.example"));

Invoice invoice = qb.qbd().invoices().create(
    new InvoiceCreateInput(customer.id())
        .transactionDate(LocalDate.of(2026, 10, 5))
        .lines(List.of(new InvoiceLineCreateInput()
            .itemId("80000003-1730311000")
            .quantity(2.0)
            .rate(new BigDecimal("125.00")))));

qb.qbd().invoices().update(invoice.id(),
    new InvoiceUpdateInput(invoice.revisionNumber()).memo("Thanks for your order"));

qb.qbd().invoices().voidTransaction(invoice.id());
```

Money is `BigDecimal`, quantities are `Double`, dates are `LocalDate` and timestamps are `OffsetDateTime`. `void` is a Java keyword, so the void operation is `voidTransaction`.

Per-call options:

```java
qb.qbd().invoices().create(input, RequestOptions.builder().idempotencyKey("order-5541-invoice").build());
```

## Pagination

List methods return a `Pager<T>`, which is `Iterable<T>`:

```java
for (Invoice invoice : qb.qbd().invoices().list(new InvoiceListParams().updatedAfter("2026-10-01"))) {
    System.out.println(invoice.refNumber() + " " + invoice.subtotal());
}
```

Fast item loops request the next page when they reach it. If you keep requesting items after holding a page for more than two seconds, the iterator can fetch the next page early to reduce cursor expiry. A later `break` can leave that page unused. Page-by-page iteration fetches a page only when requested, so fetch the next page promptly. Read-ahead cannot keep a cursor alive while your code pauses indefinitely. `firstPage()`, `pages()`, `listAll()` and `stream()` give you one page, page by page, everything in a list, or a `java.util.stream.Stream`. If the cursor expires, iteration throws `CursorExpiredException` with `itemsYielded()`, `pagesServed()`, `lastId()`, `lastUpdatedAt()` and `reason()`, and does not restart the list. See [Pagination](https://www.desktopaccountingapi.com/docs/guides/pagination/).

## Exceptions

Exceptions are unchecked. All API errors extend `ApiException`: `InvalidRequestException`, `AuthenticationException`, `PermissionException`, `BillingException`, `RateLimitException`, `IntegrationConnectionException`, `IntegrationException`, `OutcomeUnknownException`, `InternalException`, `CursorExpiredException` and `ResultUnavailableException` (the result is no longer available: never send an applied write again, read the object instead; a read is safe to send again). `ApiConnectionException` means no response arrived. `RequestPendingException` means the SDK stopped waiting for a request that reached QuickBooks: the client timeout ended, or checking on it failed (the failed check says nothing about the write). It carries `requestId()`, `timeoutError()` and `idempotencyKey()`; resend a write only with that key. Every exception of a write carries `idempotencyKey()`.

```java
try {
    qb.qbd().healthCheck();
} catch (IntegrationConnectionException e) {
    System.out.println(e.userFacingMessage());
} catch (ApiException e) {
    System.out.println(e.code() + " " + e.requestId() + " " + e.getMessage());
}
```

`ApiException` exposes every field of the error: `status()`, `type()`, `code()`, `userFacingMessage()`, `httpStatusCode()`, `integrationCode()`, `requestId()`, `errorCause()`, `fixes()`, `docsUrl()`, `retryable()`, `outcome()`, `param()`, `details()` and `headers()`. See [Error handling](https://www.desktopaccountingapi.com/docs/guides/error-handling/).

## Idempotency and retries

Writes get an idempotency key automatically, reused across retries; pass `RequestOptions.builder().idempotencyKey(...).build()` to use your own. Retries follow `Daapi-Should-Retry` and never repeat a write with an unknown or pending outcome. See [Idempotency](https://www.desktopaccountingapi.com/docs/guides/idempotency/).

## Async requests

Operations QuickBooks runs are also available under `enqueue()`. They queue the request without waiting and return a `RequestHandle<T>`:

```java
RequestHandle<Invoice> handle = qb.qbd().invoices().enqueue().create(input,
    RequestOptions.builder().queueTtl(Duration.ofHours(1)).build());
System.out.println(handle.id()); // req_...

Invoice created = handle.await(Duration.ofMinutes(2)); // long-polls until QuickBooks answers
```

`status()` reads the request once, and `result()` returns the result if the request has finished or throws `RequestPendingException` if it has not. A write the API [recovered](https://www.desktopaccountingapi.com/docs/guides/request-lifecycle/#recovered-writes) without its result throws `ResultUnavailableException` from `await()` and `result()`: do not send it again; retrieve the object by `e.recoveredObjectId()`. (`Object.wait()` is final in Java, so the long-poll method is `await`.)

## Raw responses

Methods that do not page have a `...WithResponse` variant that returns `ApiResponse<T>`:

```java
ApiResponse<Customer> response = qb.qbd().customers().retrieveWithResponse("80000001-1730311000");
System.out.println(response.statusCode() + " " + response.requestId() + " " + response.data().name());
```

## Webhooks

```java
try {
    WebhookEvent event = Webhooks.verify(rawBody, requestHeaders, System.getenv("DAAPI_WEBHOOK_SECRET"));
    if (WebhookEventType.REQUEST_SUCCEEDED.equals(event.type())) {
        String requestId = (String) event.data().get("id");
    }
} catch (WebhookVerificationException e) {
    // respond 400
}
```

`requestHeaders` is a `Map<String, ?>` with `String` or `List<String>` values. `verify` checks the signature and timestamp against the raw body and returns the event. See [Webhooks](https://www.desktopaccountingapi.com/docs/guides/webhooks/).

## Porting from Conductor

Conductor has no Java SDK, so Java code that used Conductor calls its REST API. The paths, parameters and JSON fields are the same here; move the settings to the client builder:

```java
// Before: java.net.http calls to https://api.conductor.is/v1 with a Conductor-End-User-Id header.
DesktopAccountingApiClient client = DesktopAccountingApiClient.builder()
    .baseUrl("https://api.desktopaccountingapi.com/v1") // a trailing /v1 is accepted
    .timeout(Duration.ofSeconds(120))                   // per attempt
    .totalTimeout(Duration.ofMinutes(5))                // the whole call, retries included
    .defaultHeader("X-Trace-Id", "billing-sync")
    .build();
DesktopAccountingApiClient qb = client.forEndUser("eu_01j9..."); // replaces Conductor-End-User-Id
try {
    qb.qbd().invoices().retrieve("1A4F-1730312567");
} catch (ApiException e) {
    if (e.status() == 404) System.out.println(e.code() + " " + e.userFacingMessage() + " " + e.requestId());
    else throw e;
}
```

Conductor's error fields (`code`, `type`, `userFacingMessage`, `httpStatusCode`, `integrationCode`, `requestId`) are accessors of `ApiException`, next to `errorCause()`, `fixes()`, `docsUrl()` and `outcome()`.
