The Leonardo AI API turns image generation into a job your app can submit and track. The key choice comes first: do you need Leonardo’s image workflow, or will your product later need video and music too?
Use these steps to define the job, create a secure token, send a request, read the result, and decide when Apiframe is a better fit for a wider media pipeline.
Step 1: Define Your Leonardo AI API Workflow
Before you write code, write down the exact generation path your product needs. A clear job flow keeps you from building a simple demo that later has to grow into a system with uploads, queues, retries, or webhooks (automatic notifications when a job finishes).
Start with one narrow task. For example, your app might turn a product description into a square marketing image. Another app may take a photo a user uploaded and apply an edit. Those are different workflows, even though both produce an image.
Pick the input and output
Choose one of these starting points:
- Text to image: send a prompt and receive generated images.
- Image to image: use an existing image as a starting point.
- Inpainting: send an image plus a mask that marks the area to change.
- Upscaling: submit an image when you need a larger or sharper result.
- Text to video or image to video: Leonardo’s Motion models create short clips from a prompt or a still image. They use a separate set of endpoints from the main image call.
The workflow is job based. You submit a generation, wait for it to process, then retrieve the result and its details. For larger jobs, plan for a webhook or a background worker that can check on the job without keeping a user’s browser open.
Also decide where the request runs. Keep it on your server, not in browser code. Your server can protect the key, limit user requests, store job IDs, and apply your own usage rules.
Leonardo’s model list can change, so do not hard-code a model ID without checking the current docs. If your plans include several media types, compare this workflow with our AI image API guide before you commit to one provider. If your app will also edit images, our AI image editing API guide explains what to expect.
Key takeaway: Treat image generation as a background job that finishes later. Define the input, output, user wait time, and failure path before you send your first request.
Step 2: Create Access Credentials and Review the API Docs
Access to the Leonardo AI API starts with an API key and a read through the current endpoint docs. Keep this step separate from your app code so you can change models or replace keys without a rushed release.
Create a server-side key
Open Leonardo’s developer dashboard and find the API access area. Creating a key is free, but generating images uses a paid credit balance. Give each key a name that shows where it belongs, such as “development” or “production.”
Save the key in an environment variable or a secret store. Do not paste it into front-end code, a public repository, a screen recording, or a mobile app. If a key leaks, revoke it and create a new one.
Requests use a bearer token in the authorization header:
Authorization: Bearer YOUR_API_KEYThe base address is https://cloud.leonardo.ai/api/rest/v1. Read the current endpoint page before coding, since model IDs, request fields, and supported features can change.
Read the request shape
Find the generation endpoint first. Note the required prompt field, the modelId field, image size, image count, and any guidance or negative prompt settings. Do not copy every optional field into your first call. A small request is easier to debug.
Then find the result endpoint. The create response returns a generationId. Pass it to the result endpoint to check progress. A finished job shows the status COMPLETE, with the image URLs included once it reaches that state.
Read the error documentation before you build retry logic. A bad request should never be retried over and over, while a temporary service or queue problem may deserve another try.
Write down these values in your project notes:
- API base path
- Generation endpoint
- Result lookup endpoint
- Authentication header
- Required request fields
- Terminal success and failure states
By now, you should have a private development key and a short request map. You do not need a full production setup yet. You only need enough detail to send one controlled job.
Step 3: Send Your First Image Generation Request
Your first call should be small, repeatable, and easy to inspect. Use one prompt, one model ID from the current docs, and a modest image size while you check that everything works.
Build the request
Use a backend script or a command-line tool. The exact endpoint and field names must match the current Leonardo docs, so treat this as a pattern, not a copy-and-paste template.
curl -X POST "API_BASE_PATH/generations" \ -H "Authorization: Bearer $LEONARDO_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "prompt": "A small red cabin beside a quiet alpine lake at sunrise", "modelId": "CURRENT_MODEL_ID", "width": 1024, "height": 1024 }'Replace the model placeholder with an ID from the current model list or docs. Do not assume a model’s display name is also a valid model ID. Providers often use separate display names and machine values.
Keep the first prompt plain. A scene with a subject, place, light, and style is enough to test the call. If the request fails, you want to know whether the problem is the key, the JSON format, the model choice, or the prompt. Our Midjourney prompt guide covers similar prompt basics if you are new to writing them, even though it is written for a different model.
The create response returns a generationId. Save that value right away. Your app should show a “pending” state to the user instead of waiting for the whole render inside the original web request.
Test one change at a time
Once the first job works, change one setting. Try a new prompt before you change the model. Then test a different aspect ratio. This gives you a clean way to spot which field changed the result or caused an error.
Keep the raw request and response in your development logs, but hide the key. Record the generation ID, request time, chosen model, status, and final image URL. Those details help when a user reports a missing image. Images generated through Leonardo’s API do not expire, so you do not need to rush a copy into your own storage the moment a job finishes. Most teams still save a copy for reliability.
If you need reference images, do not send the raw file straight to the generation endpoint. Leonardo’s upload flow works in steps. You request an upload slot, which returns a temporary upload address. You send the file to that address, then pass the returned image ID into the generation request as init_image_id, along with a strength setting such as init_strength.
For image edits, an inpainting flow also needs a mask. A soft mask can blend an edit into its surroundings. A hard mask makes a sharper edge. Test these as separate cases, because a mask can change the result more than a prompt tweak.
Pro tip: Save a known-good request as a test case. When you update a code library or change a model ID, run that test first.
Step 4: Retrieve Results and Handle API Errors
The Leonardo AI API separates job creation from result retrieval. Your app needs to handle that gap cleanly, especially when a user is waiting for an image on a product screen.
Poll without blocking the app
After the create call returns a generationId, poll the result endpoint at a measured interval. Stop when the job reaches a terminal state. A completed job includes output details such as image URLs and generation metadata.
Don't poll forever. Set a time limit for the user-facing request, then move long jobs to a background worker. Your worker can keep checking while the front end shows a pending state. Leonardo also supports webhook callbacks, configured when you create a production API key rather than per request, so set that up if you want to avoid polling for long-running work.
Store the final result in your own record. Save the provider's generation ID beside your internal job ID. That mapping makes support work much easier because you can trace a customer action without exposing internal credentials.
Sort errors by type
- Authentication errors: check the key, header, and environment variable.
- Validation errors: check the JSON field names, values, and model ID.
- Rate or concurrency errors: slow your queue and retry with a delay.
- Service errors: retry a limited number of times, then show a helpful message.
- Generation failures: mark the job as failed and keep the provider’s message for your logs.
Only retry errors that may clear on their own. Retrying a broken request adds load and hides the real bug. For temporary failures, wait a little longer between each try (this is called exponential backoff), with a maximum number of attempts.
Leonardo’s API also has limits on capacity. The number of requests per time window, active jobs, and queued work can each affect delivery. Build a small queue instead of letting every user action hit the provider at once.
For cost control, record the model and output settings with each job. A low-cost preview path can serve the editor, while a final render runs only after the user approves the prompt. If your product accepts user prompts, also read our AI content moderation guide for ways to check generated images and video.
Step 5: Connect Leonardo AI to Your Product with Apiframe
Leonardo is a sensible choice when your product focuses on image and video generation and its creator-focused model library fits the job. To weigh that choice against other providers, our roundup of AI image generator APIs compares model coverage, workflow, and integration effort across several options. But the decision changes when your plans include music alongside image and video.
Apiframe gives product teams one developer-facing API for AI image, video, and music generation. Your app can keep one account setup and one job flow while you test different media paths. Our guide on how to choose an AI media API covers the points worth weighing before you commit either way.
Keep your app behind one adapter
Even if you start with Leonardo, put provider calls behind a small internal service (often called an adapter). Your front end should ask for a generation, not know which vendor handles it.
Your adapter can expose a common request such as:
generate({ mediaType: "image", prompt, model, options
})Inside that service, map the common fields to the selected provider. Return your own job ID to the rest of the app. This keeps the UI stable when you switch models or add another media type.
For an Apiframe image flow, the same pattern applies. You sign in with an X-API-Key header, send a POST request, receive a jobId, then check the job or accept a webhook. The Getting Started with Apiframe guide walks through the first call. This single design becomes more useful when a customer journey crosses media types. A user might generate a product image first, then request a short motion clip, then add music for a campaign draft. Our AI video generation API guide covers the same job pattern for video.
That breadth has a trade-off. Leonardo’s strength is its image focus and creator tools, including a visual web app where you can design a generation and export ready-to-use API code. Apiframe’s strength is a shared interface across media types and models. Pick based on your product flow, not brand recognition alone.
Key takeaway: Put an adapter between your product and any media API. It protects your screens from model changes and makes a later move to multi-media generation much easier.
FAQ
What is the Leonardo AI API?
The Leonardo AI API is an interface for adding image generation and related media jobs to an application. You sign in with a bearer token, submit a generation request, then retrieve the result by generation ID. Depending on the current product, workflows include text-to-image, image editing, uploads, upscaling, and text-to-video or image-to-video through Leonardo’s Motion models.
How do I get a Leonardo API key?
You get a Leonardo API key from the API access area in your account. Creating a key is free, but generating images uses a paid credit balance. Store the key on your backend as a secret. Never expose it in browser code or commit it to source control. Name keys by environment so you can revoke a development key without disrupting production.
Does the Leonardo AI API return images right away?
No. The Leonardo AI API treats generation as a background job. The first response gives you a generation ID. Check the result endpoint, or use a webhook set up on your API key, to find out when the job is done. A background worker is a better choice for long jobs, since it keeps the user’s browser request short.
Can I use Leonardo for image-to-image generation?
Yes. Image-to-image needs an upload step first. The upload endpoint returns a temporary upload address for the file, plus an image ID. You then pass that ID into the generation request as the starting image. Send the file promptly, keep the returned image ID, and reference it in your generation request.
When should I use Apiframe instead?
Use Apiframe when your product needs one API for image, video, and music generation. Leonardo can fit an image and video focused workflow, while Apiframe is built for teams that want a shared interface across media types, including music. Compare the request format, model needs, and result handling before you choose. Our roundup of AI media generation APIs is a useful next read either way.
Conclusion
Start with one small Leonardo generation, keep the key on your server, and build result checking before adding advanced options. If your plans include more than images, test the same job flow through Apiframe early. Next, save one known-good request and use it as the first integration test in your app.