Text-to-image API integration guide: request to accepted image


Quick answer
A production text-to-image API integration is a job lifecycle, not one HTTP request. Keep the provider key on your server, validate the request, record the exact provider and model, handle uncertain retries, wait for a terminal result, copy outputs before URLs expire, review the image and measure cost per accepted asset.
Use the current AI image API comparison to choose a provider. This page owns the implementation question: how to turn any selected image endpoint into a reliable product workflow. The examples use Magic Hour’s current image-project lifecycle where a concrete response shape is helpful.
The production lifecycle at a glance
Stage | Store | Handle explicitly | Failure to avoid |
|---|---|---|---|
Accept request | Internal request ID, user and prompt version | Authentication, validation, quota and abuse controls | Putting a provider key in browser or mobile code |
Create job | Provider, model, parameters and provider job ID | Timeouts, rate limits and whether the call is synchronous | Retrying an uncertain request without deduplication |
Wait | Status, attempts and last error | Polling backoff, webhook verification and terminal states | Treating an HTTP timeout as proof that creation failed |
Download | Output URL or bytes, checksum and expiry | Stream to controlled storage before a signed URL expires | Saving only a temporary provider URL |
Review | Acceptance result and reason | Safety, text, identity, product, brand and visual defects | Counting every generated file as a usable asset |
Measure | Spend, latency, retries and review time | Cost per accepted image and qualified downstream result | Optimizing raw generation price alone |
Test the image API
Send one representative brief through a sandbox integration, retain every attempt, and calculate accepted-image cost before adding production traffic.
Explore Magic Hour API1. Define one accepted image before integrating
Write a representative brief and a machine-checkable output contract. Include intended subject, composition, aspect ratio, resolution, background, required or forbidden text, reference inputs, number of candidates and where the final image will be used.
Visual acceptance: correct subject, count, composition, crop, color and brand treatment.
Text acceptance: every visible word matches the approved copy; generated text still needs inspection.
Identity and product acceptance: approved references remain recognizable and material product details are not invented.
Technical acceptance: expected dimensions, format, alpha behavior, file size and color handling.
Rights acceptance: authorized inputs, current plan and model terms, permitted commercial use and retained generation record.
2. Keep authentication on the server
A browser or mobile app should call your backend. Your backend authenticates the user, applies quotas and content rules, then calls the image provider with a secret loaded from a server-side secret manager. Never ship the provider API key in a public client bundle.
Magic Hour’s integration guidance uses file and project outputs, while the image creation reference requires Bearer authentication and returns a project ID plus credits charged. Other providers return different shapes; wrap only the contract your product needs.
3. Store the exact provider, model and parameters
“AI image” is not reproducible metadata. Save the provider, endpoint, model identifier, model version when exposed, prompt version, aspect ratio, resolution, reference asset IDs, safety settings and account or pricing tier. A provider platform and its underlying model are different fields.
Model names and routes change. Google’s current Gemini image-generation documentation says Imagen endpoints were deprecated and directs new image work to Nano Banana models. Pin supported identifiers in server configuration and review deprecation notices before changing them.
4. Make request creation idempotent
Generate an internal request ID before calling the provider. Store it with a hash of the normalized input. If your server times out after sending the request, first look up the existing record and provider job ID. Blindly creating a second job can spend twice and produce duplicate assets.
Use bounded retries for rate limits and transient transport failures. Do not retry invalid parameters, insufficient balance, moderation decisions or other terminal client errors without changing the request.
5. Handle synchronous, queued and streaming responses separately
An image API may return final bytes, a base64 payload, a streaming event sequence or a queued job ID. Your adapter should map the provider response into explicit internal states such as accepted, processing, complete, failed and canceled.
For Magic Hour, Get Image Details documents queued, rendering, complete, error and canceled states. Downloads appear after completion. The current SDK can wait for completion, but a production service should still persist the project ID so an interrupted worker can resume.
OpenAI image documentation describes image generation and editing through current API routes, including returned image data and streaming options. Treat a completed stream event and a queued provider job as different contracts; do not force them into the same polling loop.
6. Poll with backoff or verify webhooks
For queued work, poll slowly enough to avoid turning one generation into dozens of status requests. Stop only on a documented terminal state and set a total deadline. A local timeout means your worker stopped waiting; it does not prove the provider job failed.
If the provider supports webhooks, verify the signature or shared secret, persist the event before processing and make the handler idempotent. Magic Hour’s webhook event reference states that image events match the image-project response shape, which lets the poller and webhook share one state transition path.
7. Copy outputs before temporary URLs expire
Stream a completed image into storage you control, validate the content type and byte size, compute a checksum and record the source URL expiry. Do not use a temporary provider download URL as the permanent customer asset.
Magic Hour’s input and output guide states that completed download URLs expire after 24 hours and can be refreshed through the project GET endpoint. Download promptly, and never log signed URLs or secrets in user-visible errors.
8. Review before publishing or returning at scale
Automated checks can confirm dimensions, format, alpha, file size and obvious corruption. Human or task-specific review still needs to catch incorrect text, extra objects, identity drift, implausible hands, broken logos, product changes, unsafe content and visual claims unsupported by the brief.
For user-facing generation, show a clear processing state and recoverable error. Preserve the prompt and accepted prior output when a retry fails. Do not label a timed-out or partially downloaded job as complete.
9. Measure accepted-output economics
Record provider spend, retries, latency, failure class, reviewer time, correction time and acceptance result. Calculate total generation and review cost divided by accepted images. Then track the relevant downstream result—published assets, qualified visits, activation or purchases—separately.
A cheaper endpoint can cost more if it creates more rejected images. A faster endpoint can hurt the product if it loses reference fidelity or required text. Optimize the bottleneck in the real acceptance data.
A minimal production data model
Request: internal ID, user, normalized input hash, created time and idempotency key.
Provider job: provider, endpoint, model, exact parameters, provider job ID and status.
Output: controlled storage key, checksum, dimensions, format and source URL expiry.
Evaluation: accepted or rejected, reason codes, reviewer, corrections and final asset ID.
Economics: quoted or charged units, attempts, latency and review time.
Pre-launch checklist
Secrets: key is server-side, scoped, rotatable and absent from logs.
Reliability: request IDs, uncertain-result recovery, bounded retries, terminal states and deadlines are implemented.
Storage: temporary outputs are copied, verified and retained under the required policy.
Safety and rights: inputs, prompt, provider terms, model and final approval evidence are retained.
Operations: rate limits, budget ceiling, error classes, cancellation and support lookup by request ID are defined.
Measurement: acceptance rate and cost per accepted image are visible before volume increases.
Frequently asked questions
It is a programmatic interface that accepts a text description and returns or schedules an image-generation result. Some endpoints also accept reference images or support editing. The API platform, endpoint and underlying model should be recorded separately.
The client can start the workflow through your backend, but a long-lived provider secret should not be embedded in public client code. The backend should authenticate the user, apply quotas and call the provider.
Retry only documented transient failures with bounded backoff. For an uncertain timeout, first check whether the original request created a provider job. Use an internal idempotency key or stored request hash so one user action does not create duplicate paid work.
Choose from the current image API comparison by the exact model access, editing and reference inputs, lifecycle, deployment, output contract, rights and accepted-image cost your product needs.





