Image Generation API Integration: Model Selection, Requests, and Costs
Learn how to evaluate image generation models, configure API access, make Python requests, and manage errors, concurrency, and usage. This guide also covers key security, privacy, and cost considerations before moving an integration into production.
1. Evaluate Model Capabilities Before Integrating
Choosing an image generation model means balancing image quality, response time, and budget. Vendor capability claims often reflect specific test conditions, so they may not translate directly to your application. Validate performance with your own test samples rather than relying on promotional materials alone.
Review the following capabilities before committing to an API.
Resolution and Aspect Ratio
Supported resolutions and aspect ratios vary by provider. Check the options listed in the official documentation rather than assuming every setting is available.
Higher-resolution output generally takes longer to generate and costs more. Choose a resolution that fits the use case instead of always selecting the highest setting.
Chinese Text Rendering
If your application needs Chinese text in generated images, test it explicitly. Results can vary substantially with the font, text length, layout, and background complexity. A poster headline may render correctly while longer body text contains incorrect characters.
Prepare prompts with different text lengths and layouts, then measure the proportion of outputs that render the text correctly.
Subject Consistency
Keeping the same character visually consistent across multiple images is a common requirement for illustrations, storyboards, and branded assets.
Consistency often declines with profile views, occlusion, multiple subjects in one image, and generation across separate batches. To evaluate it, reuse the same reference images and prompts, generate several images in sequence, and manually label whether each output meets your requirements.
Current Information and Web Search
Access to web search or up-to-date information depends on the specific product and whether the relevant features are enabled for that API. Confirm support in the current documentation; do not infer it from the product name.
Build a Reusable Test Set
Prepare approximately 30 prompts covering your main business scenarios. For each test, record:
- Acceptance rate
- Generation time per image
- Cost per image
Reuse this test set when models or prices change to make comparisons easier.
2. Prepare Your Integration
Create a Project and Obtain an API Key
Sign in to the provider’s console or AI Studio, create a project, and obtain an API key. Use separate keys for services with different purposes so they can be audited and revoked independently.
Store API Keys Securely
Keys should never appear in source code, committed configuration files, or logs.
- Store keys in environment variables or a secrets management service.
- Add
.envto.gitignoreto prevent accidental commits. - If a key is exposed, revoke it immediately in the console and generate a replacement.
Configure Quotas and Spending Alerts
Set daily or monthly usage limits for the project where available, and enable spending alerts. These controls can help detect and limit losses caused by runaway loops or misuse.
Install and Pin the SDK Version
For a Python integration, install the official SDK:
pip install google-genai
In production, pin the version you have tested in requirements.txt, using the format google-genai==<tested-version>.
SDK interfaces and parameters can change between releases. Pinning a validated version helps prevent automatic upgrades from breaking production code.
3. Make an Image Generation Request
The following example keeps the model ID, API key, and output path configurable and includes basic error handling.
Before running it, confirm the model ID and supported ImageConfig values in the official documentation.
import osimport iofrom google import genaifrom google.genai import typesfrom PIL import Image# Confirm the model ID in the official documentation.# Read it from an environment variable to simplify version changes.MODEL_ID = os.environ.get("IMAGE_MODEL_ID", "")if not MODEL_ID:raise RuntimeError("IMAGE_MODEL_ID is not set. Confirm the model ID ""in the official documentation first.")# Read the API key from the environment, not from source code.api_key = os.environ.get("GEMINI_API_KEY")if not api_key:raise RuntimeError("The GEMINI_API_KEY environment variable is not set")client = genai.Client(api_key=api_key)def generate_image(prompt: str, out_path: str) -> bool:try:response = client.models.generate_content(model=MODEL_ID,contents=prompt,config=types.GenerateContentConfig(response_modalities=["IMAGE"],image_config=types.ImageConfig(aspect_ratio="1:1",image_size="2K",),),)except Exception as exc:print(f"Request failed: {exc}")return False# Candidates may be absent if a safety policy blocks the request.candidates = response.candidates or []if not candidates or candidates[0].content is None:print("No candidate content returned; a safety policy may have blocked it")return False# Find image data in the returned content parts and save it.for part in candidates[0].content.parts or []:if part.inline_data is not None:image = Image.open(io.BytesIO(part.inline_data.data))image.save(out_path)return Trueprint("No image data returned. Check the response text for details.")return Falseif __name__ == "__main__":ok = generate_image("An orange cat wearing a beret, in an oil painting style","output.png",)print("Generation succeeded" if ok else "Generation failed")
Keep these implementation details in mind:
- External model ID: Model names may change between releases. An environment variable lets you switch models without editing the code.
- External API key: This example reads
GEMINI_API_KEY. Check the documentation for your SDK version for its environment-variable conventions. - Response validation: Do not assume every response contains an image. Blocked requests or invalid parameters may produce no usable content, and indexing an empty response can cause another exception.
- Parameter compatibility: Verify names and supported values for
image_config,aspect_ratio, andimage_sizeagainst the documentation for your installed SDK version.
4. Handle Errors, Retries, and Concurrency
Distinguish Retryable Errors from Non-Retryable Errors
| Error type | Typical cause | Recommended handling |
|---|---|---|
| Network timeout or connection interruption | Network instability or a busy server | Retry with exponential backoff |
| 429 rate limit | Request rate exceeds the quota | Reduce concurrency, wait, and retry |
| 5xx server error | Temporary server-side failure | Retry with exponential backoff |
| 400 parameter error | Invalid parameter values | Correct the parameters; do not retry unchanged |
| Content blocked | The prompt triggers a safety policy | Do not retry unchanged; record the result and revise the prompt |
Exponential Backoff Example
import timedef call_with_retry(fn, max_retries: int = 3):for attempt in range(max_retries + 1):try:return fn()except Exception:# Retry only retryable errors. Add checks based on# the status codes or exception types exposed by the SDK.if attempt == max_retries:raisetime.sleep(2 ** attempt) # Wait 1s, then 2s, then 4s.
This example illustrates the backoff timing, not a complete error-classification strategy. Production code should inspect the exception type or status code and retry only eligible failures. Retrying invalid parameters simply wastes quota.
The retry wrapper also needs the callable to raise an exception. The earlier generate_image function catches request exceptions and returns False, so wrapping that function directly would not trigger these retries.
Rate Limits and Concurrency
Use a queue or semaphore to limit simultaneous requests and keep traffic within your account quotas.
For batch workloads, place tasks in a message queue and process them with a fixed number of workers. Slow processing when 429 responses occur.
Timeouts
Set a timeout for each request so threads do not remain blocked indefinitely. Consult the SDK documentation for the appropriate timeout configuration.
Logging and Archiving
Record the following fields for each request:
- Request time and request ID
- Model ID and generation parameters, including resolution and aspect ratio
- A prompt hash rather than the raw prompt, to reduce sensitive content in logs
- Elapsed time, status code, and error information
Store generated images and their metadata in object storage. Including a prompt hash in filenames can help with retrieval and deduplication.
5. Options for Non-Developers
You do not need to write code to use image generation. Common access options include:
- Provider websites or apps: Enter a description in a conversational interface to generate or edit an image. This is suitable for occasional use.
- Third-party graphical tools: Some tools offer batch processing and templates for frequent generation. Confirm where your data is sent before using them.
- Office or document-platform plugins: Generate illustrations directly inside a document. Review the permissions requested by the plugin, including whether it can read document content.
Whichever option you choose, review the provider’s privacy policy. Confirm whether uploaded images are retained and whether they may be used for model training.
Avoid tools from unknown sources when working with customer information or unpublished assets.
6. Estimate Costs
Start with the Per-Image Price
Use the price per image as the starting point for estimating monthly spending, alongside your expected generation volume.
