Skip to content

About

Java 11+ library and Spring Boot starter for blooms.ai Imagine: request AI images in bulk, mint browser sessions, read results and verify signed webhooks.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Imagine for Java

Generate AI images with blooms.ai Imagine from your Java backend.

You send prompts. blooms.ai tells you when it will start and at what pace, makes the images at that pace, delivers them to your S3 bucket if you want, and calls your webhook each time a batch is ready.

  • Safe to retry. Every job create carries an idempotency key, so a retry or a restarted process never makes the same job twice.
  • Retries for you on network errors, timeouts, 429 and 5xx, honouring Retry-After.
  • One exception type, ImagineException, with a code to branch on. Your key never appears in an error.
  • Signed webhooks, checked in constant time, with replay protection.
  • No dependencies. Java 11+, built on java.net.http, so it never clashes with your own Jackson, OkHttp or Apache client.
  • Spring Boot starter for Boot 3 and 4: set one property and inject the client.

For browser pages, use @bloomscorp/imagine.js (or its Angular and React wrappers) with a session from this library. For Node.js backends, use @bloomscorp/imagine-node.

Install

Plain Java (Java 11+):

<dependency>
  <groupId>com.bloomscorp</groupId>
  <artifactId>imagine-java</artifactId>
  <version>0.1.0</version>
</dependency>
implementation("com.bloomscorp:imagine-java:0.1.0")

Spring Boot 3 or 4 (Java 17+): use the starter instead. It includes the client.

<dependency>
  <groupId>com.bloomscorp</groupId>
  <artifactId>imagine-spring-boot-starter</artifactId>
  <version>0.1.0</version>
</dependency>
implementation("com.bloomscorp:imagine-spring-boot-starter:0.1.0")

Set up

  1. Ask Bloomscorp to switch on API access and Imagine for your project.
  2. In Project Settings → API keys, create a key and tick the imagine scope. A key without it is refused. Keep the key in your server's environment, never in code or a browser.
  3. Optional: in the project's 🔌 API tab, add an S3 destination and a webhook. Both are made in the portal, because they hold secrets. You refer to them by id.

Quick start

import com.bloomscorp.imagine.*;

ImagineClient imagine = ImagineClient.builder()
    .apiKey(System.getenv("BLOOMS_API_KEY"))
    .build();                                   // one per application; thread-safe

Job job = imagine.jobs().create(CreateJobRequest.builder()
    .row(JobRow.builder("Sku 123 on white").count(2).externalRef("sku-123/white").build())
    .row(JobRow.builder("Sku 124 lifestyle").externalRef("sku-124/life").build())
    .style("studio")
    .build());

job.getPacePerMinute();                         // e.g. 5 images a minute
job.getSchedule().getFinishesAt();              // when blooms.ai expects to finish

Job done = imagine.jobs().waitFor(job.getId(), Duration.ofMinutes(10));
for (Image image : imagine.jobs().images(job.getId())) {
    image.getExternalRef();                     // "sku-123/white"
    image.getUrl();                             // presigned, valid for 1 hour
}

Calls block until blooms.ai answers, through any retries. Call them from a background thread or a virtual thread if a request must not wait.

For long jobs, use webhooks instead of waitFor. A job of 1,000 images at 5 a minute takes over 3 hours.

Rows or a recipe

A job takes either rows or a recipe. Mixing them is refused before anything is sent.

Rows are one entry per prompt. Each row has its own count (1–50), references, aspect ratio and your own reference string. Every item and image of the row keeps that string. Up to 1,000 rows. Rows make a batch job.

CreateJobRequest.builder()
    .row(JobRow.builder("Sku 123 on white").count(2).aspectRatio("1:1")
        .referenceIds(refId).externalRef("sku-123/white").build())
    .row(JobRow.of("Sku 124 lifestyle"))
    .style("studio")
    .build();

A recipe is one of the Studio's four modes. blooms.ai expands it into items.

CreateJobRequest.builder()
    .mode("product").productName("Linen shirt").productDetails("Sky blue")
    .shots("white", "angle", "lifestyle").perShot(4).referenceIds(photoId)
    .style("studio").aspectRatio("4:5")
    .build();

CreateJobRequest.builder().mode("prompt").prompt("A mug on a desk").count(4).build();
CreateJobRequest.builder().mode("edit").prompt("Make the background blue").sourceImageId(imageId).count(2).build();
CreateJobRequest.builder().mode("batch").text("A red mug\nA blue mug").build();

Common fields, for both: credentialId, model, style, aspectRatio, name (≤ 120), externalRef (≤ 200), destinationId, keepCopy, notify. field(name, value) sends any field newer than this library.

imagine.presets() lists the styles, aspect ratios and product shots. imagine.status() shows limits, usage and models. imagine.credentials().list() shows the project's Google tokens.

Your own idempotency key makes a create safe even across restarts:

Job job = imagine.jobs().create(request, "catalogue-2026-11");
job.isReplay();   // true when that key was used before with the same body

The same key with a different body throws IDEMPOTENCY_CONFLICT. Keys are kept 24 hours.

References. Upload product photos first, then pass their ids:

List<ReferenceImage> refs = imagine.references().upload(List.of(
    ReferenceFile.fromPath(Path.of("/srv/products/123-front.jpg")),
    ReferenceFile.of("back.png", bytes)));
imagine.references().fromUrls(List.of("https://cdn.example.com/123.webp"));

1–5 files, PNG, JPEG or WebP, up to 10 MB each. These rules are checked before anything is uploaded.

Following and controlling a job

imagine.jobs().get(jobId);                       // status, counts, schedule
imagine.jobs().list(JobListQuery.builder().status("active").externalRef("catalogue-2026-11").build());
imagine.jobs().items(jobId);                     // each item: status, errorCode, imageIds

imagine.jobs().pause(jobId);
imagine.jobs().resume(jobId);
imagine.jobs().cancel(jobId);                    // can't be undone
imagine.jobs().retry(jobId);                     // failed items again
imagine.jobs().move(jobId, otherCredentialId);   // to another Google token

ImagePage page = imagine.jobs().imagesPage(jobId, null, 100);   // one page
page = imagine.jobs().imagesPage(jobId, page.getNextCursor(), 100);
imagine.jobs().images(jobId).stream()...;                        // every page, lazily

imagine.images().get(imageId);                   // a fresh presigned URL
imagine.images().delete(imageId);                // from Bloomscorp storage only

images(jobId) stops at the images made so far. For a running job, iterate again later, or keep the last cursor from imagesPage.

Browser pages: sessions

Never send the API key to a browser. Your backend mints a short-lived session, and the page uses only its token.

@GetMapping("/imagine-session")
Map<String, String> imagineSession(@AuthenticationPrincipal User user) {
    Session session = imagine.sessions().create(SessionRequest.builder()
        .maxImages(10)                                  // for all jobs of this session
        .modes("prompt", "product")
        .origins("https://shop.example.com")            // exact origins; empty = any
        .externalUser(user.getId())                     // shows on the jobs, for your reports
        .ttlSeconds(900)                                // 60–3600
        .build());
    return Map.of("token", session.getToken(), "expiresAt", session.getExpiresAt().toString());
}

The browser library calls this endpoint through its getSessionToken() callback, and again when the token expires. Tokens can't be refreshed. imagine.sessions().revoke(id) ends one now.

Destinations and manifests

With destinationId, each image is written to your S3 bucket as {prefix}{jobId}/{seq:000000}-{imageId}.{ext}. With keepCopy(false) (the default when a destination is given), Bloomscorp keeps only a thumbnail, and Image.getUrl() is null. Read the image from Image.getDestination() instead.

Each imagine.images.ready webhook also writes a manifest, {prefix}{jobId}/manifest-{n:0000}.json. Read it from your bucket and parse it:

Manifest manifest = Manifests.parse(jsonFromS3);
for (Manifest.Entry e : manifest.getImages()) {
    e.getKey(); e.getExternalRef(); e.getSha256();
}

imagine.destinations().list() shows each destination and whether it is verified. If the bucket refuses a write, its jobs pause with pauseReason destination, and resume when a check in the portal passes.

Webhooks

blooms.ai calls your webhook for imagine.images.ready (every 50 images or 30 minutes by default; set per job with Notify), imagine.job.paused, imagine.job.resumed, imagine.job.completed, imagine.job.failed and imagine.job.cancelled.

CreateJobRequest.builder()
    ...
    .notify(Notify.builder().webhookId(webhookId).everyImages(100).everyMinutes(15).build())
    .build();

Every webhook is signed. Check the signature on the raw body, before anything else. A body that was parsed and written again is not the same bytes, and will not match.

With Spring Boot, set the secret and inject the verifier:

bloomscorp.imagine.webhook-secret=${IMAGINE_WEBHOOK_SECRET}
@RestController
class ImagineWebhookController {
    private final ImagineWebhookVerifier verifier;

    ImagineWebhookController(ImagineWebhookVerifier verifier) {
        this.verifier = verifier;
    }

    @PostMapping(path = "/hooks/imagine", consumes = "application/json")
    ResponseEntity<Void> receive(@RequestBody byte[] body,              // raw bytes, not a DTO
                                 @RequestHeader(name = "Blooms-Signature", required = false) String signature) {
        WebhookEvent event;
        try {
            event = verifier.verify(body, signature);
        } catch (ImagineSignatureException e) {
            return ResponseEntity.badRequest().build();
        }
        if (WebhookEvent.IMAGES_READY.equals(event.getType())) {
            for (Image image : event.getData().getImages()) {
                // image.getDestination().getKey(), image.getUrl() (valid 24 hours)
            }
        }
        return ResponseEntity.noContent().build();   // any 2xx; anything else is retried
    }
}

Without Spring:

WebhookEvent event = WebhookVerifier.verify(rawBody, signatureHeader, secret);
  • The header is Blooms-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>. Several v1 values may appear; one match is enough.
  • A t more than 5 minutes from now is refused (SIGNATURE_EXPIRED). Pass a Duration to change that.
  • Failures throw ImagineSignatureException with SIGNATURE_MISSING, SIGNATURE_MALFORMED, SIGNATURE_MISMATCH, SIGNATURE_EXPIRED or BAD_PAYLOAD. Answer 400.
  • A failed delivery is retried after 1, 5 and 30 minutes, 2 hours and 12 hours. Use event.getId() to skip one you already handled.
  • The secret (whsec_…) is shown once in the portal. imagine.webhooks().list() never returns it.
  • WebhookVerifier.signatureHeader(body, secret, t) makes a header, to test your endpoint.

Spring Boot

bloomscorp.imagine.api-key=${BLOOMS_API_KEY}
bloomscorp.imagine.webhook-secret=${IMAGINE_WEBHOOK_SECRET}
@Service
class Catalogue {
    private final ImagineClient imagine;

    Catalogue(ImagineClient imagine) {
        this.imagine = imagine;
    }
}
  • api-key gives an ImagineClient bean. webhook-secret gives an ImagineWebhookVerifier bean. Each is optional.
  • With no value (or an empty one, such as ${BLOOMS_API_KEY:} in a dev profile), there is no bean and the application still starts.
  • A key that is not a blooms.ai key stops startup with INVALID_API_KEY. A wrong key is found at deploy, not at the first job.
  • Your own beans always win.
Property Default
bloomscorp.imagine.api-key (none: required for a client)
bloomscorp.imagine.base-url https://z.bloomscorp.com
bloomscorp.imagine.timeout 30s, per attempt
bloomscorp.imagine.upload-timeout 2m, per attempt of a reference upload
bloomscorp.imagine.max-retries 3
bloomscorp.imagine.max-retry-wait 60s; a longer Retry-After is thrown, not waited out
bloomscorp.imagine.webhook-secret (none: required for a verifier)
bloomscorp.imagine.webhook-tolerance 5m

Errors

try {
    imagine.jobs().create(request);
} catch (ImagineException e) {
    e.getCode();            // "TOO_MANY_JOBS", "NO_CREDENTIAL", "IMAGINE_DISABLED", …
    e.getStatus();          // HTTP status, when there was a response
    e.getMessage();         // for people; branch on the code
    e.getRetryAfter();      // seconds, when blooms.ai said when to try again
    e.getIdempotencyKey();  // for a create: retry with this to stay safe
    e.getDetails();         // any other fields of the error
}
Status Codes
400 VALIDATION_ERROR, PROMPT_REQUIRED, BAD_MODE, BAD_RATIO, TOO_MANY_LINES, TOO_MANY_REFERENCES, BAD_REFERENCE, PRODUCT_REQUIRED, PRODUCT_PHOTO_REQUIRED, SHOTS_REQUIRED, SOURCE_REQUIRED, BATCH_EMPTY, NO_CREDENTIAL, CREDENTIAL_DISABLED, BAD_MODEL, MODEL_UNREACHABLE, TOO_MANY_ITEMS, BAD_DESTINATION, BAD_WEBHOOK, BAD_URL, BROWSER_NOT_ALLOWED
401 MISSING_API_KEY, INVALID_API_KEY
403 API_ACCESS_DISABLED, KEY_SCOPE, IMAGINE_DISABLED, ENDPOINT_DISABLED
404 NOT_FOUND
409 TOO_MANY_JOBS, STORAGE_FULL, JOB_FINISHED, NOT_PAUSED, NOTHING_TO_RETRY, NOTHING_TO_MOVE, IDEMPOTENCY_CONFLICT, IDEMPOTENCY_IN_PROGRESS
413 TOO_LARGE
429 RATE_LIMITED

This library's own codes:

Code Meaning
INVALID_API_KEY The key is missing or not a blooms.ai key (checked when the client is built)
VALIDATION_ERROR, BAD_MODE, PROMPT_REQUIRED, TOO_MANY_LINES, TOO_MANY_REFERENCES, BAD_REFERENCE, BAD_URL, TOO_LARGE Refused before anything was sent
NETWORK_FAILURE, TIMEOUT, BAD_RESPONSE blooms.ai could not be reached or answered oddly, after retries
WAIT_TIMEOUT waitFor gave up; getDetails().get("status") has the last status
BAD_MANIFEST Manifests.parse got something that is not a manifest
INTERRUPTED Your thread was interrupted while waiting; its interrupt flag is kept

Retries

  • 429, 500, 502, 503, 504, network errors and timeouts are retried up to 3 times, with exponential backoff (0.5 s, 1 s, 2 s, …) and up to 25% jitter.
  • A Retry-After is honoured. One longer than maxRetryWait (60 s) is thrown at once, with getRetryAfter(), so a request never hangs for minutes.
  • Job creates always carry an Idempotency-Key, the same on every attempt, so they are retried safely. 409 IDEMPOTENCY_IN_PROGRESS (an earlier attempt with the same key is still being accepted) is retried too, so you get that job back.
  • Session creates and reference uploads have no idempotency key. They are retried only after a 429, which means nothing was done.
  • Reads, deletes and the job controls are safe to repeat and are always retried.

Security

  • Keep the API key on the server. The server API refuses calls from a browser (an Origin header). Use sessions for pages.
  • Give each session the smallest scope: few images, the modes it needs, your exact origins, a short time to live.
  • Check every webhook's signature on the raw body, and answer 400 when it fails.
  • Keep the webhook secret in the environment. Rotate it in the portal if it leaks.
  • The key never appears in an exception, a log line from this library, or toString(). Neither do session tokens or webhook secrets.
  • Delivered images in your bucket are yours. Deleting an image here removes only Bloomscorp's copy.

Options

ImagineClient.builder()
    .apiKey(apiKey)                              // required
    .baseUrl("https://z.bloomscorp.com")
    .timeout(Duration.ofSeconds(30))             // per attempt, end to end
    .uploadTimeout(Duration.ofMinutes(2))        // the same, for reference uploads
    .maxRetries(3)
    .maxRetryWait(Duration.ofSeconds(60))        // a longer Retry-After is thrown, not waited out
    .httpClient(myHttpClient)                    // optional: proxies, custom TLS
    .build();

Development

mvn verify                          # both modules, Spring Boot 3.5
mvn -pl imagine-spring-boot-starter -am verify -Dspring-boot.version=4.1.2
scripts/verify-package.sh           # what would be published (set JAVA11_HOME to prove Java 11)

The webhook tests run the signature vectors shared with imagine-node (imagine-java/src/test/resources/vectors/webhook-signature.json). Keep the two copies the same.

Releases are published to Maven Central by the release workflow when a v* tag is pushed. See RELEASING.md.

License

MIT

About

Java 11+ library and Spring Boot starter for blooms.ai Imagine: request AI images in bulk, mint browser sessions, read results and verify signed webhooks.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages