Gemini 3.1 Flash Image Preview
Integrate
gemini-3.1-flash-image-preview
# Run the model; wait up to 20 s for the finished result in the same call
curl -X POST "https://api.doitong.com/v1/run/gemini-3.1-flash-image-preview?wait=20" \
-H "Authorization: Bearer $DOITONG_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "A red fox trots through fresh snow at sunrise, soft golden light, shallow depth of field"
}'
# Still "queued" or "running"? Poll with the id from the response:
curl "https://api.doitong.com/v1/requests/REQUEST_ID?wait=20" \
-H "Authorization: Bearer $DOITONG_API_KEY"
const API = "https://api.doitong.com/v1";
const headers = {
"Authorization": "Bearer " + process.env.DOITONG_API_KEY,
"Content-Type": "application/json",
};
// Run the model; wait up to 20 s for the finished result in the same call
let res = await fetch(API + "/run/gemini-3.1-flash-image-preview?wait=20", {
method: "POST",
headers,
body: JSON.stringify({
"prompt": "A red fox trots through fresh snow at sunrise, soft golden light, shallow depth of field"
}),
});
let request = await res.json();
if (!res.ok) throw new Error(request.error.code + ": " + request.error.message);
// Not finished yet: long-poll until it is
while (request.status === "queued" || request.status === "running") {
res = await fetch(API + "/requests/" + request.id + "?wait=20", { headers });
request = await res.json();
}
if (request.status !== "succeeded") throw new Error(JSON.stringify(request.error));
console.log(request.outputs.map((o) => o.url), request.cost.credits + " API credits ($" + request.cost.usd + ")");
import os
import requests
API = "https://api.doitong.com/v1"
headers = {"Authorization": "Bearer " + os.environ["DOITONG_API_KEY"]}
payload = {
"prompt": "A red fox trots through fresh snow at sunrise, soft golden light, shallow depth of field",
}
# Run the model; wait up to 20 s for the finished result in the same call
r = requests.post(API + "/run/gemini-3.1-flash-image-preview", params={"wait": 20}, json=payload, headers=headers)
request = r.json()
if not r.ok:
raise RuntimeError(request["error"]["code"] + ": " + request["error"]["message"])
# Not finished yet: long-poll until it is
while request["status"] in ("queued", "running"):
request = requests.get(API + "/requests/" + request["id"], params={"wait": 20}, headers=headers).json()
if request["status"] != "succeeded":
raise RuntimeError(request["error"])
print([o["url"] for o in request["outputs"]], request["cost"]["credits"], "API credits", "$" + request["cost"]["usd"])
# 1. Connect once (Claude Code; Cursor, VS Code, Claude Desktop: https://doitong.com/developers/docs/mcp)
claude mcp add --transport http doitong-models https://api.doitong.com/v1/mcp \
--header "Authorization: Bearer $DOITONG_API_KEY"
# 2. Your agent calls the "run" tool with:
{
"model_id": "gemini-3.1-flash-image-preview",
"input": {
"prompt": "A red fox trots through fresh snow at sunrise, soft golden light, shallow depth of field"
}
}
Call the Gemini 3.1 Flash Image Preview model (gemini-3.1-flash-image-preview) through the Doitong API. Docs for agents: https://doitong.com/developers/models/gemini-3.1-flash-image-preview.md
POST https://api.doitong.com/v1/run/gemini-3.1-flash-image-preview?wait=20
Authorization: Bearer $DOITONG_API_KEY
Content-Type: application/json
{
"prompt": "A red fox trots through fresh snow at sunrise, soft golden light, shallow depth of field"
}
If the response status is "queued" or "running", poll GET https://api.doitong.com/v1/requests/REQUEST_ID?wait=20 until it is "succeeded"; the files are in outputs[].url. POST https://api.doitong.com/v1/quote/gemini-3.1-flash-image-preview with the same body returns the exact price before the run.
This request: $0.08 80 API credits Run it on this page
Your new API key. It is shown only now and is already in the code and in the API key field below. Keep it secret: never put it in code that runs in a browser.
Made on Doitong
Public works made with Gemini 3.1 Flash Image Preview by the Doitong community. Reuse a prompt in one click.
Яркая и радостная сцена в детской. Папа склонился над пеленальным столиком, развлекая Саю яркой погремушкой в форме солнца. Ракурс снизу, со стороны ребенка, подчеркивает масштаб и значимость фигуры отца. Освещение дневное, контрастное и веселое. Вокруг разбросаны мягкие кубики и яркие игрушки....
Strong rule: style --- 3D Pixar ---. Финальный кадр: Сая погружена в глубокий сон, и на её личике появляется едва уловимая, блаженная улыбка. Папа продолжает баюкать её на руках, его темный силуэт четко выделяется на фоне большого окна, за которым мерцает ночное звездное небо. Камера установлена...
Strong rule: style --- 3D Pixar ---. Ярко освещенный современный супермаркет с бесконечными рядами полок. Марина сидит за кассовым аппаратом, её движения механические. На переднем плане — лента с продуктами: молоко, хлеб, консервы. Освещение резкое, люминесцентное, создающее холодную атмосферу....
Strong rule: style --- Реалистичная 3D-анимация в духе Pixar, но без м... ---. Дневное кафе с большими окнами. Пасмурный свет, нейтральная палитра: серые улицы, мягкие тени. На столе две чашки, ложечки, салфетки. Аня в бежевом тренче и белом топе, Олег в тёмной куртке/свитере. Они сидят напротив,...
Art style: Cinematic Realistic. Интерьер роскошного банкетного зала в загородном особняке, заполненного нарядными гостями. В воздухе парят золотистые конфетти, повсюду видны хрустальные бокалы с шампанским. Освещение яркое, с динамичными вспышками света, создающими атмосферу праздника. В центре...
Art style: Cinematic Realistic. Un dormitorio en penumbra durante la noche, iluminado solo por la luz azulada de la luna que entra por las persianas. Elena está sentada en el borde de la cama, meciendo a un bebé envuelto en una manta blanca que llora. Javier duerme profundamente al otro lado de...
Art style: 3D анимация в стиле Pixar. Девочка с распущенными волосами с ножницами стоит перед зеркалом в ванной, рядом на раковине сидит рыжий кот. Держит левой рукой длинную прядь в районе челки, а левой ее начинает отстригать ножницами. Бирюзовая плитка на фоне, мягкое освещение. Лицо девочки...
Art style: Cinematográfico realista. Marcos abraza a Elena por los hombros en el sofá, ella permanece rígida. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ FINAL STYLE ENFORCEMENT (this is the authoritative rendering directive — it overrides any style wording elsewhere in the prompt): Render this image...
Финальная сцена у окна на закате. Папа держит Саю на уровне своего лица, они смотрят друг другу в глаза. Небо за окном окрашено в невероятные розовые, оранжевые и фиолетовые цвета в стиле Pixar. Контурный свет подчеркивает силуэты героев. Папа нежно целует Саю в лобик. Композиция сбалансированная...
Strong rule: style --- 3D Pixar ---. Финальный кадр: Сая погружена в глубокий сон, и на её личике появляется едва уловимая, блаженная улыбка. Папа продолжает баюкать её на руках, его темный силуэт четко выделяется на фоне большого окна, за которым мерцает ночное звездное небо. Камера установлена...
Strong rule: style --- Реалистичный ---. Уютная детская комната в глубоких сумерках, освещенная мягким янтарным светом настенного ночника в форме полумесяца. Молодой отец сидит в массивном деревянном кресле-качалке, бережно прижимая к груди крошечного младенца. На стенах видны нежные обои с...
Strong rule: style --- 3D Pixar ---. Крупный план лица Мирры, смотрящей прямо в объектив камеры с легким прищуром. Она находится в полумраке роскошной комнаты, где единственный источник теплого света находится сбоку, создавая глубокие тени на одной стороне её лица. Её взгляд пронзительный,...
Strong rule: style --- 3D Pixar ---. Экстремально крупный план глаз Мирры, которые занимают почти всё пространство экрана. Изумрудная радужка прорисована с невероятной детализацией, видны мельчайшие узоры и яркое отражение невидимого окна. Ресницы длинные, густые и идеально разделенные. Освещение...
Strong rule: style --- Кинематографичный, фотореалистичный ---. Крупный план Веры в салоне Mercedes. Мягкая подсветка интерьера. За окном в движении проносится холодная Москва. Вера нервно смеётся, и одновременно на её глазах выступают слёзы. Она отворачивается к окну, чтобы скрыть эмоции, затем...
Art style: Pixar-like 3D. 🎬 STAGING CONTRACT WORLD MAP: праздничный стол (festive table), большой торт со свечами (large cake with candles), хрустальный бокал (crystal glass). BLOCKING: Vladimir_Senior sits at the center of the праздничный стол, screen-center, midground, FACING...
Strong rule: style --- 3D Pixar ---. Та же ночная детская с ночником и лунным светом через шторы, игрушки на полке, мягкий плед на кроватке, атмосфера тепла и уюта, уязвимости. Средний план с лёгкого высокого угла, фокусируясь на маме. Освещение от ночника создаёт мягкие тени на лице, подчёркивая...
Build a request
Controls are generated from the model schema. The code and the price update as you change them.
/run/gemini-3.1-flash-image-preview?wait=20
quote → $0.08
# Run the model; wait up to 20 s for the finished result in the same call
curl -X POST "https://api.doitong.com/v1/run/gemini-3.1-flash-image-preview?wait=20" \
-H "Authorization: Bearer $DOITONG_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "A red fox trots through fresh snow at sunrise, soft golden light, shallow depth of field"
}'
# Still "queued" or "running"? Poll with the id from the response:
curl "https://api.doitong.com/v1/requests/REQUEST_ID?wait=20" \
-H "Authorization: Bearer $DOITONG_API_KEY"
const API = "https://api.doitong.com/v1";
const headers = {
"Authorization": "Bearer " + process.env.DOITONG_API_KEY,
"Content-Type": "application/json",
};
// Run the model; wait up to 20 s for the finished result in the same call
let res = await fetch(API + "/run/gemini-3.1-flash-image-preview?wait=20", {
method: "POST",
headers,
body: JSON.stringify({
"prompt": "A red fox trots through fresh snow at sunrise, soft golden light, shallow depth of field"
}),
});
let request = await res.json();
if (!res.ok) throw new Error(request.error.code + ": " + request.error.message);
// Not finished yet: long-poll until it is
while (request.status === "queued" || request.status === "running") {
res = await fetch(API + "/requests/" + request.id + "?wait=20", { headers });
request = await res.json();
}
if (request.status !== "succeeded") throw new Error(JSON.stringify(request.error));
console.log(request.outputs.map((o) => o.url), request.cost.credits + " API credits ($" + request.cost.usd + ")");
import os
import requests
API = "https://api.doitong.com/v1"
headers = {"Authorization": "Bearer " + os.environ["DOITONG_API_KEY"]}
payload = {
"prompt": "A red fox trots through fresh snow at sunrise, soft golden light, shallow depth of field",
}
# Run the model; wait up to 20 s for the finished result in the same call
r = requests.post(API + "/run/gemini-3.1-flash-image-preview", params={"wait": 20}, json=payload, headers=headers)
request = r.json()
if not r.ok:
raise RuntimeError(request["error"]["code"] + ": " + request["error"]["message"])
# Not finished yet: long-poll until it is
while request["status"] in ("queued", "running"):
request = requests.get(API + "/requests/" + request["id"], params={"wait": 20}, headers=headers).json()
if request["status"] != "succeeded":
raise RuntimeError(request["error"])
print([o["url"] for o in request["outputs"]], request["cost"]["credits"], "API credits", "$" + request["cost"]["usd"])
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "run",
"arguments": {
"model_id": "gemini-3.1-flash-image-preview",
"input": {
"prompt": "A red fox trots through fresh snow at sunrise, soft golden light, shallow depth of field"
},
"wait_seconds": 20
}
}
}
Run this request
Your key stays in this browser: it is sent only to the Doitong API and saved (localStorage) only if you tick Remember. Get an API key
About Gemini 3.1 Flash Image Preview
Generates images from a `prompt`, with `resolution` of 0.5K, 1K, 2K or 4K and aspect ratios including extreme ones such as 8:1 and 1:8. Optional `system_prompt`, `enable_web_search` and `thinking_level` (minimal or high) shape the generation. Produces 1 to 4 images in PNG, JPEG or WebP.
Parameters
Send either the canonical name or the native name, not both. Canonical names
promptrequired
num_imagesoptional
num_outputs
seedoptional
aspect_ratiooptional
output_formatoptional
safety_toleranceoptional
system_promptoptional
resolutionoptional
limit_generationsoptional
enable_web_searchoptional
thinking_leveloptional
Output
{
"id": "req_8k2m4q7x1z9c3v5b6n0p2r4t",
"object": "request",
"model": "gemini-3.1-flash-image-preview",
"status": "succeeded",
"created_at": "2026-10-20T12:00:00Z",
"started_at": "2026-10-20T12:00:02Z",
"completed_at": "2026-10-20T12:00:09Z",
"queue_position": null,
"cost": {
"credits": 80,
"usd": "0.08",
"charged": 80,
"refunded": 0
},
"input": {
"prompt": "A red fox trots through fresh snow at sunrise, soft golden light, shallow depth of field"
},
"output": {
"images": [
{
"url": "https://content.doitong.com/dev-api/2026/10/20/req_8k2m4q7x1z9c3v5b6n0p2r4t/0-output.jpeg",
"content_type": "image/jpeg",
"file_name": "0-output.jpeg",
"file_size": 1843200,
"width": 1024,
"height": 768
}
],
"description": "string"
},
"outputs": [
{
"type": "image",
"url": "https://content.doitong.com/dev-api/2026/10/20/req_8k2m4q7x1z9c3v5b6n0p2r4t/0-output.jpeg",
"content_type": "image/jpeg",
"file_size": 1843200,
"width": 1024,
"height": 768,
"stored": true
}
],
"error": null,
"metrics": {
"inference_seconds": 6.8
},
"urls": {
"self": "https://api.doitong.com/v1/requests/req_8k2m4q7x1z9c3v5b6n0p2r4t",
"cancel": "https://api.doitong.com/v1/requests/req_8k2m4q7x1z9c3v5b6n0p2r4t/cancel"
}
}
Fields of output
- images
- array of object {url, content_type, file_name, file_size, width, height}Images produced by the model.
- description
- stringDescription accompanying the generated images.
Other Gemini 3.1 Flash Image Preview variants
More models: Text to Image
For AI agents: this page as Markdown is at https://doitong.com/developers/models/gemini-3.1-flash-image-preview.md. All models and guides: https://doitong.com/developers/llms.txt







