ℹ️ Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 0 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://ai.google.dev/gemini-api/docs/structured-output |
| Last Crawled | 2026-04-07 05:50:06 (3 hours ago) |
| First Indexed | 2024-08-14 21:09:57 (1 year ago) |
| HTTP Status Code | 200 |
| Meta Title | Structured outputs | Gemini API | Google AI for Developers |
| Meta Description | Learn how to generate structured JSON output with the Gemini API. |
| Meta Canonical | null |
| Boilerpipe Text | Skip to main content
Gemini API
Docs
API reference
Get API key
Cookbook
Community
Get started
Overview
Quickstart
API keys
Libraries
Pricing
Interactions API
Coding agent setup
Models
All models
Gemini 3
Nano Banana
Veo
Lyria 3
Lyria Real
Time
Imagen
Text-to-speech
Embeddings
Robotics
Core capabilities
Text
Documents
Structured outputs
Function calling
Long context
Agents
Overview
Deep Research Agent
Tools
Overview
Google Search
Google Maps
Code execution
URL context
Computer Use
File Search
Combine Tools and Function calling
Live API
Overview
Capabilities
Tool use
Session management
Ephemeral tokens
Best practices
Optimization
Overview
Batch API
Flex inference
Priority inference
Context caching
Guides
Open
AI compatibility
Media resolution
Token counting
Prompt engineering
Resources
Release notes
Deprecations
Rate limits
Billing info
Migrate to Gen AI SDK
API troubleshooting
Partner and library integrations
Policies
Terms of service
Available regions
Abuse monitoring
Feedback information
On this page
Streaming
Structured outputs with tools
JSON schema support
Type-specific properties
Model support
Structured outputs vs. function calling
Best practices
Limitations
You can configure Gemini models to generate responses that adhere to a provided JSON
Schema. This ensures predictable, type-safe results and simplifies extracting
structured data from unstructured text.
Using structured outputs is ideal for:
Data extraction:
Pull specific information like names and dates from text.
Structured classification:
Classify text into predefined categories.
Agentic workflows:
Generate structured inputs for tools or APIs.
In addition to supporting JSON Schema in the REST API, the Google GenAI SDKs
make it easy to define schemas using
Pydantic
(Python) and
Zod
(JavaScript).
This example demonstrates how to extract structured data from text using basic
JSON Schema types like
object
,
array
,
string
, and
integer
.
from
google
import
genai
from
pydantic
import
BaseModel
,
Field
from
typing
import
List
,
Optional
class
Ingredient
(
BaseModel
):
name
:
str
=
Field
(
description
=
"Name of the ingredient."
)
quantity
:
str
=
Field
(
description
=
"Quantity of the ingredient, including units."
)
class
Recipe
(
BaseModel
):
recipe_name
:
str
=
Field
(
description
=
"The name of the recipe."
)
prep_time_minutes
:
Optional
[
int
]
=
Field
(
description
=
"Optional time in minutes to prepare the recipe."
)
ingredients
:
List
[
Ingredient
]
instructions
:
List
[
str
]
client
=
genai
.
Client
()
prompt
=
"""
Please extract the recipe from the following text.
The user wants to make delicious chocolate chip cookies.
They need 2 and 1/4 cups of all-purpose flour, 1 teaspoon of baking soda,
1 teaspoon of salt, 1 cup of unsalted butter (softened), 3/4 cup of granulated sugar,
3/4 cup of packed brown sugar, 1 teaspoon of vanilla extract, and 2 large eggs.
For the best part, they'll need 2 cups of semisweet chocolate chips.
First, preheat the oven to 375°F (190°C). Then, in a small bowl, whisk together the flour,
baking soda, and salt. In a large bowl, cream together the butter, granulated sugar, and brown sugar
until light and fluffy. Beat in the vanilla and eggs, one at a time. Gradually beat in the dry
ingredients until just combined. Finally, stir in the chocolate chips. Drop by rounded tablespoons
onto ungreased baking sheets and bake for 9 to 11 minutes.
"""
response
=
client
.
models
.
generate_content
(
model
=
"gemini-3-flash-preview"
,
contents
=
prompt
,
config
=
{
"response_mime_type"
:
"application/json"
,
"response_json_schema"
:
Recipe
.
model_json_schema
(),
},
)
recipe
=
Recipe
.
model_validate_json
(
response
.
text
)
print
(
recipe
)
import
{
GoogleGenAI
}
from
"@google/genai"
;
import
{
z
}
from
"zod"
;
import
{
zodToJsonSchema
}
from
"zod-to-json-schema"
;
const
ingredientSchema
=
z
.
object
({
name
:
z
.
string
().
describe
(
"Name of the ingredient."
),
quantity
:
z
.
string
().
describe
(
"Quantity of the ingredient, including units."
),
});
const
recipeSchema
=
z
.
object
({
recipe_name
:
z
.
string
().
describe
(
"The name of the recipe."
),
prep_time_minutes
:
z
.
number
().
optional
().
describe
(
"Optional time in minutes to prepare the recipe."
),
ingredients
:
z
.
array
(
ingredientSchema
),
instructions
:
z
.
array
(
z
.
string
()),
});
const
ai
=
new
GoogleGenAI
({});
const
prompt
=
`
Please extract the recipe from the following text.
The user wants to make delicious chocolate chip cookies.
They need 2 and 1/4 cups of all-purpose flour, 1 teaspoon of baking soda,
1 teaspoon of salt, 1 cup of unsalted butter (softened), 3/4 cup of granulated sugar,
3/4 cup of packed brown sugar, 1 teaspoon of vanilla extract, and 2 large eggs.
For the best part, they'll need 2 cups of semisweet chocolate chips.
First, preheat the oven to 375°F (190°C). Then, in a small bowl, whisk together the flour,
baking soda, and salt. In a large bowl, cream together the butter, granulated sugar, and brown sugar
until light and fluffy. Beat in the vanilla and eggs, one at a time. Gradually beat in the dry
ingredients until just combined. Finally, stir in the chocolate chips. Drop by rounded tablespoons
onto ungreased baking sheets and bake for 9 to 11 minutes.
`
;
const
response
=
await
ai
.
models
.
generateContent
({
model
:
"gemini-3-flash-preview"
,
contents
:
prompt
,
config
:
{
responseMimeType
:
"application/json"
,
responseJsonSchema
:
zodToJsonSchema
(
recipeSchema
),
},
});
const
recipe
=
recipeSchema
.
parse
(
JSON
.
parse
(
response
.
text
));
console
.
log
(
recipe
);
package
main
import
(
"context"
"fmt"
"log"
"google.golang.org/genai"
)
func
main
()
{
ctx
:=
context
.
Background
()
client
,
err
:=
genai
.
NewClient
(
ctx
,
nil
)
if
err
!=
nil
{
log
.
Fatal
(
err
)
}
prompt
:=
`
Please extract the recipe from the following text.
The user wants to make delicious chocolate chip cookies.
They need 2 and 1/4 cups of all-purpose flour, 1 teaspoon of baking soda,
1 teaspoon of salt, 1 cup of unsalted butter (softened), 3/4 cup of granulated sugar,
3/4 cup of packed brown sugar, 1 teaspoon of vanilla extract, and 2 large eggs.
For the best part, they'll need 2 cups of semisweet chocolate chips.
First, preheat the oven to 375°F (190°C). Then, in a small bowl, whisk together the flour,
baking soda, and salt. In a large bowl, cream together the butter, granulated sugar, and brown sugar
until light and fluffy. Beat in the vanilla and eggs, one at a time. Gradually beat in the dry
ingredients until just combined. Finally, stir in the chocolate chips. Drop by rounded tablespoons
onto ungreased baking sheets and bake for 9 to 11 minutes.
`
config
:=
&
genai
.
GenerateContentConfig
{
ResponseMIMEType
:
"application/json"
,
ResponseJsonSchema
:
map
[
string
]
any
{
"type"
:
"object"
,
"properties"
:
map
[
string
]
any
{
"recipe_name"
:
map
[
string
]
any
{
"type"
:
"string"
,
"description"
:
"The name of the recipe."
,
},
"prep_time_minutes"
:
map
[
string
]
any
{
"type"
:
"integer"
,
"description"
:
"Optional time in minutes to prepare the recipe."
,
},
"ingredients"
:
map
[
string
]
any
{
"type"
:
"array"
,
"items"
:
map
[
string
]
any
{
"type"
:
"object"
,
"properties"
:
map
[
string
]
any
{
"name"
:
map
[
string
]
any
{
"type"
:
"string"
,
"description"
:
"Name of the ingredient."
,
},
"quantity"
:
map
[
string
]
any
{
"type"
:
"string"
,
"description"
:
"Quantity of the ingredient, including units."
,
},
},
"required"
:
[]
string
{
"name"
,
"quantity"
},
},
},
"instructions"
:
map
[
string
]
any
{
"type"
:
"array"
,
"items"
:
map
[
string
]
any
{
"type"
:
"string"
},
},
},
"required"
:
[]
string
{
"recipe_name"
,
"ingredients"
,
"instructions"
},
},
}
result
,
err
:=
client
.
Models
.
GenerateContent
(
ctx
,
"gemini-3-flash-preview"
,
genai
.
Text
(
prompt
),
config
,
)
if
err
!=
nil
{
log
.
Fatal
(
err
)
}
fmt
.
Println
(
result
.
Text
())
}
curl
"https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent"
\
-H
"x-goog-api-key:
$GEMINI_API_KEY
"
\
-H
'Content-Type: application/json'
\
-X
POST
\
-d
'{
"contents": [{
"parts":[
{ "text": "Please extract the recipe from the following text.\nThe user wants to make delicious chocolate chip cookies.\nThey need 2 and 1/4 cups of all-purpose flour, 1 teaspoon of baking soda,\n1 teaspoon of salt, 1 cup of unsalted butter (softened), 3/4 cup of granulated sugar,\n3/4 cup of packed brown sugar, 1 teaspoon of vanilla extract, and 2 large eggs.\nFor the best part, they will need 2 cups of semisweet chocolate chips.\nFirst, preheat the oven to 375°F (190°C). Then, in a small bowl, whisk together the flour,\nbaking soda, and salt. In a large bowl, cream together the butter, granulated sugar, and brown sugar\nuntil light and fluffy. Beat in the vanilla and eggs, one at a time. Gradually beat in the dry\ningredients until just combined. Finally, stir in the chocolate chips. Drop by rounded tablespoons\nonto ungreased baking sheets and bake for 9 to 11 minutes." }
]
}],
"generationConfig": {
"responseMimeType": "application/json",
"responseJsonSchema": {
"type": "object",
"properties": {
"recipe_name": {
"type": "string",
"description": "The name of the recipe."
},
"prep_time_minutes": {
"type": "integer",
"description": "Optional time in minutes to prepare the recipe."
},
"ingredients": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": { "type": "string", "description": "Name of the ingredient."},
"quantity": { "type": "string", "description": "Quantity of the ingredient, including units."}
},
"required": ["name", "quantity"]
}
},
"instructions": {
"type": "array",
"items": { "type": "string" }
}
},
"required": ["recipe_name", "ingredients", "instructions"]
}
}
}'
Example Response:
{
"recipe_name"
:
"Delicious Chocolate Chip Cookies"
,
"ingredients"
:
[
{
"name"
:
"all-purpose flour"
,
"quantity"
:
"2 and 1/4 cups"
},
{
"name"
:
"baking soda"
,
"quantity"
:
"1 teaspoon"
},
{
"name"
:
"salt"
,
"quantity"
:
"1 teaspoon"
},
{
"name"
:
"unsalted butter (softened)"
,
"quantity"
:
"1 cup"
},
{
"name"
:
"granulated sugar"
,
"quantity"
:
"3/4 cup"
},
{
"name"
:
"packed brown sugar"
,
"quantity"
:
"3/4 cup"
},
{
"name"
:
"vanilla extract"
,
"quantity"
:
"1 teaspoon"
},
{
"name"
:
"large eggs"
,
"quantity"
:
"2"
},
{
"name"
:
"semisweet chocolate chips"
,
"quantity"
:
"2 cups"
}
],
"instructions"
:
[
"Preheat the oven to 375°F (190°C)."
,
"In a small bowl, whisk together the flour, baking soda, and salt."
,
"In a large bowl, cream together the butter, granulated sugar, and brown sugar until light and fluffy."
,
"Beat in the vanilla and eggs, one at a time."
,
"Gradually beat in the dry ingredients until just combined."
,
"Stir in the chocolate chips."
,
"Drop by rounded tablespoons onto ungreased baking sheets and bake for 9 to 11 minutes."
]
}
Streaming
You can stream structured outputs, which allows you to start processing the
response as it's being generated, without having to wait for the entire output
to be complete. This can improve the perceived performance of your application.
The streamed chunks will be valid partial JSON strings, which can be
concatenated to form the final, complete JSON object.
from
google
import
genai
from
pydantic
import
BaseModel
,
Field
from
typing
import
Literal
class
Feedback
(
BaseModel
):
sentiment
:
Literal
[
"positive"
,
"neutral"
,
"negative"
]
summary
:
str
client
=
genai
.
Client
()
prompt
=
"The new UI is incredibly intuitive and visually appealing. Great job. Add a very long summary to test streaming!"
response_stream
=
client
.
models
.
generate_content_stream
(
model
=
"gemini-3-flash-preview"
,
contents
=
prompt
,
config
=
{
"response_mime_type"
:
"application/json"
,
"response_json_schema"
:
Feedback
.
model_json_schema
(),
},
)
for
chunk
in
response_stream
:
print
(
chunk
.
candidates
[
0
]
.
content
.
parts
[
0
]
.
text
)
import
{
GoogleGenAI
}
from
"@google/genai"
;
import
{
z
}
from
"zod"
;
import
{
zodToJsonSchema
}
from
"zod-to-json-schema"
;
const
ai
=
new
GoogleGenAI
({});
const
prompt
=
"The new UI is incredibly intuitive and visually appealing. Great job! Add a very long summary to test streaming!"
;
const
feedbackSchema
=
z
.
object
({
sentiment
:
z
.
enum
([
"positive"
,
"neutral"
,
"negative"
]),
summary
:
z
.
string
(),
});
const
stream
=
await
ai
.
models
.
generateContentStream
({
model
:
"gemini-3-flash-preview"
,
contents
:
prompt
,
config
:
{
responseMimeType
:
"application/json"
,
responseJsonSchema
:
zodToJsonSchema
(
feedbackSchema
),
},
});
for
await
(
const
chunk
of
stream
)
{
console
.
log
(
chunk
.
candidates
[
0
].
content
.
parts
[
0
].
text
)
}
Structured outputs with tools
Gemini 3 lets you combine Structured Outputs with built-in tools, including
Grounding with Google Search
,
URL Context
,
Code Execution
,
File Search
, and
Function Calling
.
from
google
import
genai
from
pydantic
import
BaseModel
,
Field
from
typing
import
List
class
MatchResult
(
BaseModel
):
winner
:
str
=
Field
(
description
=
"The name of the winner."
)
final_match_score
:
str
=
Field
(
description
=
"The final match score."
)
scorers
:
List
[
str
]
=
Field
(
description
=
"The name of the scorer."
)
client
=
genai
.
Client
()
response
=
client
.
models
.
generate_content
(
model
=
"gemini-3.1-pro-preview"
,
contents
=
"Search for all details for the latest Euro."
,
config
=
{
"tools"
:
[
{
"google_search"
:
{}},
{
"url_context"
:
{}}
],
"response_mime_type"
:
"application/json"
,
"response_json_schema"
:
MatchResult
.
model_json_schema
(),
},
)
result
=
MatchResult
.
model_validate_json
(
response
.
text
)
print
(
result
)
import
{
GoogleGenAI
}
from
"@google/genai"
;
import
{
z
}
from
"zod"
;
import
{
zodToJsonSchema
}
from
"zod-to-json-schema"
;
const
ai
=
new
GoogleGenAI
({});
const
matchSchema
=
z
.
object
({
winner
:
z
.
string
().
describe
(
"The name of the winner."
),
final_match_score
:
z
.
string
().
describe
(
"The final score."
),
scorers
:
z
.
array
(
z
.
string
()).
describe
(
"The name of the scorer."
)
});
async
function
run
()
{
const
response
=
await
ai
.
models
.
generateContent
({
model
:
"gemini-3.1-pro-preview"
,
contents
:
"Search for all details for the latest Euro."
,
config
:
{
tools
:
[
{
googleSearch
:
{}
},
{
urlContext
:
{}
}
],
responseMimeType
:
"application/json"
,
responseJsonSchema
:
zodToJsonSchema
(
matchSchema
),
},
});
const
match
=
matchSchema
.
parse
(
JSON
.
parse
(
response
.
text
));
console
.
log
(
match
);
}
run
();
curl
"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-pro-preview:generateContent"
\
-H
"x-goog-api-key:
$GEMINI_API_KEY
"
\
-H
'Content-Type: application/json'
\
-X
POST
\
-d
'{
"contents": [{
"parts": [{"text": "Search for all details for the latest Euro."}]
}],
"tools": [
{"googleSearch": {}},
{"urlContext": {}}
],
"generationConfig": {
"responseMimeType": "application/json",
"responseJsonSchema": {
"type": "object",
"properties": {
"winner": {"type": "string", "description": "The name of the winner."},
"final_match_score": {"type": "string", "description": "The final score."},
"scorers": {
"type": "array",
"items": {"type": "string"},
"description": "The name of the scorer."
}
},
"required": ["winner", "final_match_score", "scorers"]
}
}
}'
JSON schema support
To generate a JSON object, set the
response_mime_type
in the generation configuration to
application/json
and provide a
response_json_schema
. The schema must be a valid
JSON Schema
that describes the desired output format.
The model will then generate a response that is a syntactically valid JSON string matching the provided schema. When using structured outputs, the model will produce outputs in the same order as the keys in the schema.
Gemini's structured output mode supports a subset of the
JSON Schema
specification.
The following values of
type
are supported:
string
: For text.
number
: For floating-point numbers.
integer
: For whole numbers.
boolean
: For true/false values.
object
: For structured data with key-value pairs.
array
: For lists of items.
null
: To allow a property to be null, include
"null"
in the type array (e.g.,
{"type": ["string", "null"]}
).
These descriptive properties help guide the model:
title
: A short description of a property.
description
: A longer and more detailed description of a property.
Type-specific properties
For
object
values:
properties
: An object where each key is a property name and each value is a schema for that property.
required
: An array of strings, listing which properties are mandatory.
additionalProperties
: Controls whether properties not listed in
properties
are allowed. Can be a boolean or a schema.
For
string
values:
enum
: Lists a specific set of possible strings for classification tasks.
format
: Specifies a syntax for the string, such as
date-time
,
date
,
time
.
For
number
and
integer
values:
enum
: Lists a specific set of possible numeric values.
minimum
: The minimum inclusive value.
maximum
: The maximum inclusive value.
For
array
values:
items
: Defines the schema for all items in the array.
prefixItems
: Defines a list of schemas for the first N items, allowing for tuple-like structures.
minItems
: The minimum number of items in the array.
maxItems
: The maximum number of items in the array.
Model support
The following models support structured output:
Model
Structured Outputs
Gemini 3.1 Pro Preview
✔️
Gemini 3 Flash Preview
✔️
Gemini 2.5 Pro
✔️
Gemini 2.5 Flash
✔️
Gemini 2.5 Flash-Lite
✔️
Gemini 2.0 Flash
✔️*
Gemini 2.0 Flash-Lite
✔️*
* Note that Gemini 2.0 requires an explicit
propertyOrdering
list within the JSON input to define the preferred structure. You can find an example in this
cookbook
.
Structured outputs vs.
function calling
Both structured outputs and function calling use JSON schemas, but they serve different purposes:
Feature
Primary Use Case
Structured Outputs
Formatting the final response to the user.
Use this when you want the model's
answer
to be in a specific format (e.g., extracting data from a document to save to a database).
Function Calling
Taking action during the conversation.
Use this when the model needs to
ask you
to perform a task (e.g., "get current weather") before it can provide a final answer.
Best practices
Clear descriptions:
Use the
description
field in your schema to provide clear instructions to the model about what each property represents. This is crucial for guiding the model's output.
Strong typing:
Use specific types (
integer
,
string
,
enum
) whenever possible. If a parameter has a limited set of valid values, use an
enum
.
Prompt engineering:
Clearly state in your prompt what you want the model to do. For example, "Extract the following information from the text..." or "Classify this feedback according to the provided schema...".
Validation:
While structured output guarantees syntactically correct JSON, it does not guarantee the values are semantically correct. Always validate the final output in your application code before using it.
Error handling:
Implement robust error handling in your application to gracefully manage cases where the model's output, while schema-compliant, may not meet your business logic requirements.
Limitations
Schema subset:
Not all features of the JSON Schema specification are supported. The model ignores unsupported properties.
Schema complexity:
The API may reject very large or deeply nested schemas. If you encounter errors, try simplifying your schema by shortening property names, reducing nesting, or limiting the number of constraints.
Except as otherwise noted, the content of this page is licensed under the
Creative Commons Attribution 4.0 License
, and code samples are licensed under the
Apache 2.0 License
. For details, see the
Google Developers Site Policies
. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2026-02-26 UTC.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2026-02-26 UTC."],[],[]] |
| Markdown | [Skip to main content](https://ai.google.dev/gemini-api/docs/structured-output#main-content)
[](https://ai.google.dev/)
- [English](https://ai.google.dev/gemini-api/docs/structured-output)
- [Deutsch](https://ai.google.dev/gemini-api/docs/structured-output?hl=de)
- [Español – América Latina](https://ai.google.dev/gemini-api/docs/structured-output?hl=es-419)
- [Français](https://ai.google.dev/gemini-api/docs/structured-output?hl=fr)
- [Indonesia](https://ai.google.dev/gemini-api/docs/structured-output?hl=id)
- [Italiano](https://ai.google.dev/gemini-api/docs/structured-output?hl=it)
- [Polski](https://ai.google.dev/gemini-api/docs/structured-output?hl=pl)
- [Português – Brasil](https://ai.google.dev/gemini-api/docs/structured-output?hl=pt-br)
- [Shqip](https://ai.google.dev/gemini-api/docs/structured-output?hl=sq)
- [Tiếng Việt](https://ai.google.dev/gemini-api/docs/structured-output?hl=vi)
- [Türkçe](https://ai.google.dev/gemini-api/docs/structured-output?hl=tr)
- [Русский](https://ai.google.dev/gemini-api/docs/structured-output?hl=ru)
- [עברית](https://ai.google.dev/gemini-api/docs/structured-output?hl=he)
- [العربيّة](https://ai.google.dev/gemini-api/docs/structured-output?hl=ar)
- [فارسی](https://ai.google.dev/gemini-api/docs/structured-output?hl=fa)
- [हिंदी](https://ai.google.dev/gemini-api/docs/structured-output?hl=hi)
- [বাংলা](https://ai.google.dev/gemini-api/docs/structured-output?hl=bn)
- [ภาษาไทย](https://ai.google.dev/gemini-api/docs/structured-output?hl=th)
- [中文 – 简体](https://ai.google.dev/gemini-api/docs/structured-output?hl=zh-cn)
- [中文 – 繁體](https://ai.google.dev/gemini-api/docs/structured-output?hl=zh-tw)
- [日本語](https://ai.google.dev/gemini-api/docs/structured-output?hl=ja)
- [한국어](https://ai.google.dev/gemini-api/docs/structured-output?hl=ko)
[Get API key](https://aistudio.google.com/apikey) [Cookbook](https://github.com/google-gemini/cookbook) [Community](https://discuss.ai.google.dev/c/gemini-api/)
[Sign in](https://ai.google.dev/_d/signin?continue=https%3A%2F%2Fai.google.dev%2Fgemini-api%2Fdocs%2Fstructured-output%3Fexample%3Drecipe&prompt=select_account)
[Docs](https://ai.google.dev/gemini-api/docs)
[API reference](https://ai.google.dev/api)
More
[](https://ai.google.dev/)
- [Gemini API](https://ai.google.dev/gemini-api/docs)
- [Docs](https://ai.google.dev/gemini-api/docs)
- [API reference](https://ai.google.dev/api)
- [Get API key](https://aistudio.google.com/apikey)
- [Cookbook](https://github.com/google-gemini/cookbook)
- [Community](https://discuss.ai.google.dev/c/gemini-api/)
- Get started
- [Overview](https://ai.google.dev/gemini-api/docs)
- [Quickstart](https://ai.google.dev/gemini-api/docs/quickstart)
- [API keys](https://ai.google.dev/gemini-api/docs/api-key)
- [Libraries](https://ai.google.dev/gemini-api/docs/libraries)
- [Pricing](https://ai.google.dev/gemini-api/docs/pricing)
- [Interactions API](https://ai.google.dev/gemini-api/docs/interactions)
- [Coding agent setup](https://ai.google.dev/gemini-api/docs/coding-agents)
- Models
- [All models](https://ai.google.dev/gemini-api/docs/models)
- [Gemini 3](https://ai.google.dev/gemini-api/docs/gemini-3)
- [Nano Banana](https://ai.google.dev/gemini-api/docs/image-generation)
- [Veo](https://ai.google.dev/gemini-api/docs/video)
- [Lyria 3](https://ai.google.dev/gemini-api/docs/music-generation)
- [Lyria Real Time](https://ai.google.dev/gemini-api/docs/realtime-music-generation)
- [Imagen](https://ai.google.dev/gemini-api/docs/imagen)
- [Text-to-speech](https://ai.google.dev/gemini-api/docs/speech-generation)
- [Embeddings](https://ai.google.dev/gemini-api/docs/embeddings)
- [Robotics](https://ai.google.dev/gemini-api/docs/robotics-overview)
- Core capabilities
- [Text](https://ai.google.dev/gemini-api/docs/text-generation)
- Image
- [Image generation 🍌](https://ai.google.dev/gemini-api/docs/image-generation)
- [Image understanding](https://ai.google.dev/gemini-api/docs/image-understanding)
- Video
- [Video generation](https://ai.google.dev/gemini-api/docs/video)
- [Video understanding](https://ai.google.dev/gemini-api/docs/video-understanding)
- [Documents](https://ai.google.dev/gemini-api/docs/document-processing)
- Speech and audio
- [Speech generation](https://ai.google.dev/gemini-api/docs/speech-generation)
- [Audio understanding](https://ai.google.dev/gemini-api/docs/audio)
- Thinking
- [Thinking](https://ai.google.dev/gemini-api/docs/thinking)
- [Thought signatures](https://ai.google.dev/gemini-api/docs/thought-signatures)
- [Structured outputs](https://ai.google.dev/gemini-api/docs/structured-output)
- [Function calling](https://ai.google.dev/gemini-api/docs/function-calling)
- [Long context](https://ai.google.dev/gemini-api/docs/long-context)
- Agents
- [Overview](https://ai.google.dev/gemini-api/docs/agents)
- [Deep Research Agent](https://ai.google.dev/gemini-api/docs/deep-research)
- Tools
- [Overview](https://ai.google.dev/gemini-api/docs/tools)
- [Google Search](https://ai.google.dev/gemini-api/docs/google-search)
- [Google Maps](https://ai.google.dev/gemini-api/docs/maps-grounding)
- [Code execution](https://ai.google.dev/gemini-api/docs/code-execution)
- [URL context](https://ai.google.dev/gemini-api/docs/url-context)
- [Computer Use](https://ai.google.dev/gemini-api/docs/computer-use)
- [File Search](https://ai.google.dev/gemini-api/docs/file-search)
- [Combine Tools and Function calling](https://ai.google.dev/gemini-api/docs/tool-combination)
- Live API
- [Overview](https://ai.google.dev/gemini-api/docs/live-api)
- Get started
- [Get started using the GenAI SDK](https://ai.google.dev/gemini-api/docs/live-api/get-started-sdk)
- [Get started using raw WebSockets](https://ai.google.dev/gemini-api/docs/live-api/get-started-websocket)
- [Capabilities](https://ai.google.dev/gemini-api/docs/live-api/capabilities)
- [Tool use](https://ai.google.dev/gemini-api/docs/live-api/tools)
- [Session management](https://ai.google.dev/gemini-api/docs/live-api/session-management)
- [Ephemeral tokens](https://ai.google.dev/gemini-api/docs/live-api/ephemeral-tokens)
- [Best practices](https://ai.google.dev/gemini-api/docs/live-api/best-practices)
- Optimization
- [Overview](https://ai.google.dev/gemini-api/docs/optimization)
- [Batch API](https://ai.google.dev/gemini-api/docs/batch-api)
- [Flex inference](https://ai.google.dev/gemini-api/docs/flex-inference)
- [Priority inference](https://ai.google.dev/gemini-api/docs/priority-inference)
- [Context caching](https://ai.google.dev/gemini-api/docs/caching)
- Guides
- File input
- [Input methods](https://ai.google.dev/gemini-api/docs/file-input-methods)
- [Files API](https://ai.google.dev/gemini-api/docs/files)
- [Open AI compatibility](https://ai.google.dev/gemini-api/docs/openai)
- [Media resolution](https://ai.google.dev/gemini-api/docs/media-resolution)
- [Token counting](https://ai.google.dev/gemini-api/docs/tokens)
- [Prompt engineering](https://ai.google.dev/gemini-api/docs/prompting-strategies)
- Logs and datasets
- [Get started with logs](https://ai.google.dev/gemini-api/docs/logs-datasets)
- [Data logging and sharing](https://ai.google.dev/gemini-api/docs/logs-policy)
- Safety
- [Safety settings](https://ai.google.dev/gemini-api/docs/safety-settings)
- [Safety guidance](https://ai.google.dev/gemini-api/docs/safety-guidance)
- Frameworks
- [LangChain & LangGraph](https://ai.google.dev/gemini-api/docs/langgraph-example)
- [CrewAI](https://ai.google.dev/gemini-api/docs/crewai-example)
- [LlamaIndex](https://ai.google.dev/gemini-api/docs/llama-index)
- [Vercel AI SDK](https://ai.google.dev/gemini-api/docs/vercel-ai-sdk-example)
- [Temporal](https://ai.google.dev/gemini-api/docs/temporal-example)
- Resources
- [Release notes](https://ai.google.dev/gemini-api/docs/changelog)
- [Deprecations](https://ai.google.dev/gemini-api/docs/deprecations)
- [Rate limits](https://ai.google.dev/gemini-api/docs/rate-limits)
- [Billing info](https://ai.google.dev/gemini-api/docs/billing)
- [Migrate to Gen AI SDK](https://ai.google.dev/gemini-api/docs/migrate)
- [API troubleshooting](https://ai.google.dev/gemini-api/docs/troubleshooting)
- [Partner and library integrations](https://ai.google.dev/gemini-api/docs/partner-integration)
- Google AI Studio
- [Quickstart](https://ai.google.dev/gemini-api/docs/ai-studio-quickstart)
- [Vibe code in Build mode](https://ai.google.dev/gemini-api/docs/aistudio-build-mode)
- [Developing Full-Stack Apps](https://ai.google.dev/gemini-api/docs/aistudio-fullstack)
- [Troubleshooting](https://ai.google.dev/gemini-api/docs/troubleshoot-ai-studio)
- [Access for Workspace users](https://ai.google.dev/gemini-api/docs/workspace)
- Google Cloud Platform
- [VertexAI Gemini API](https://ai.google.dev/gemini-api/docs/migrate-to-cloud)
- [OAuth authentication](https://ai.google.dev/gemini-api/docs/oauth)
- Policies
- [Terms of service](https://ai.google.dev/gemini-api/terms)
- [Available regions](https://ai.google.dev/gemini-api/docs/available-regions)
- [Abuse monitoring](https://ai.google.dev/gemini-api/docs/usage-policies)
- [Feedback information](https://ai.google.dev/gemini-api/docs/feedback-policies)
- On this page
- [Streaming](https://ai.google.dev/gemini-api/docs/structured-output#streaming)
- [Structured outputs with tools](https://ai.google.dev/gemini-api/docs/structured-output#structured_outputs_with_tools)
- [JSON schema support](https://ai.google.dev/gemini-api/docs/structured-output#json_schema_support)
- [Type-specific properties](https://ai.google.dev/gemini-api/docs/structured-output#type-specific_properties)
- [Model support](https://ai.google.dev/gemini-api/docs/structured-output#model_support)
- [Structured outputs vs. function calling](https://ai.google.dev/gemini-api/docs/structured-output#structured_outputs_vs_function_calling)
- [Best practices](https://ai.google.dev/gemini-api/docs/structured-output#best_practices)
- [Limitations](https://ai.google.dev/gemini-api/docs/structured-output#limitations)
Try the new high-speed, cost-effective [Veo 3.1 Lite](https://ai.google.dev/gemini-api/docs/models/veo-3.1-lite-generate-preview) model for video generation at scale.
- [Home](https://ai.google.dev/)
- [Gemini API](https://ai.google.dev/gemini-api)
- [Docs](https://ai.google.dev/gemini-api/docs)
Was this helpful?
Send feedback
# Structured outputs
- On this page
- [Streaming](https://ai.google.dev/gemini-api/docs/structured-output#streaming)
- [Structured outputs with tools](https://ai.google.dev/gemini-api/docs/structured-output#structured_outputs_with_tools)
- [JSON schema support](https://ai.google.dev/gemini-api/docs/structured-output#json_schema_support)
- [Type-specific properties](https://ai.google.dev/gemini-api/docs/structured-output#type-specific_properties)
- [Model support](https://ai.google.dev/gemini-api/docs/structured-output#model_support)
- [Structured outputs vs. function calling](https://ai.google.dev/gemini-api/docs/structured-output#structured_outputs_vs_function_calling)
- [Best practices](https://ai.google.dev/gemini-api/docs/structured-output#best_practices)
- [Limitations](https://ai.google.dev/gemini-api/docs/structured-output#limitations)
You can configure Gemini models to generate responses that adhere to a provided JSON Schema. This ensures predictable, type-safe results and simplifies extracting structured data from unstructured text.
Using structured outputs is ideal for:
- **Data extraction:** Pull specific information like names and dates from text.
- **Structured classification:** Classify text into predefined categories.
- **Agentic workflows:** Generate structured inputs for tools or APIs.
In addition to supporting JSON Schema in the REST API, the Google GenAI SDKs make it easy to define schemas using [Pydantic](https://docs.pydantic.dev/latest/) (Python) and [Zod](https://zod.dev/) (JavaScript).
Recipe Extractor Content Moderation Recursive Structures
This example demonstrates how to extract structured data from text using basic JSON Schema types like `object`, `array`, `string`, and `integer`.
[Python](https://ai.google.dev/gemini-api/docs/structured-output#python)
[JavaScript](https://ai.google.dev/gemini-api/docs/structured-output#javascript)
[Go](https://ai.google.dev/gemini-api/docs/structured-output#go)
[REST](https://ai.google.dev/gemini-api/docs/structured-output#rest)
More
```
from google import genai
from pydantic import BaseModel, Field
from typing import List, Optional
class Ingredient(BaseModel):
name: str = Field(description="Name of the ingredient.")
quantity: str = Field(description="Quantity of the ingredient, including units.")
class Recipe(BaseModel):
recipe_name: str = Field(description="The name of the recipe.")
prep_time_minutes: Optional[int] = Field(description="Optional time in minutes to prepare the recipe.")
ingredients: List[Ingredient]
instructions: List[str]
client = genai.Client()
prompt = """
Please extract the recipe from the following text.
The user wants to make delicious chocolate chip cookies.
They need 2 and 1/4 cups of all-purpose flour, 1 teaspoon of baking soda,
1 teaspoon of salt, 1 cup of unsalted butter (softened), 3/4 cup of granulated sugar,
3/4 cup of packed brown sugar, 1 teaspoon of vanilla extract, and 2 large eggs.
For the best part, they'll need 2 cups of semisweet chocolate chips.
First, preheat the oven to 375°F (190°C). Then, in a small bowl, whisk together the flour,
baking soda, and salt. In a large bowl, cream together the butter, granulated sugar, and brown sugar
until light and fluffy. Beat in the vanilla and eggs, one at a time. Gradually beat in the dry
ingredients until just combined. Finally, stir in the chocolate chips. Drop by rounded tablespoons
onto ungreased baking sheets and bake for 9 to 11 minutes.
"""
response = client.models.generate_content(
model="gemini-3-flash-preview",
contents=prompt,
config={
"response_mime_type": "application/json",
"response_json_schema": Recipe.model_json_schema(),
},
)
recipe = Recipe.model_validate_json(response.text)
print(recipe)
```
```
import { GoogleGenAI } from "@google/genai";
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
const ingredientSchema = z.object({
name: z.string().describe("Name of the ingredient."),
quantity: z.string().describe("Quantity of the ingredient, including units."),
});
const recipeSchema = z.object({
recipe_name: z.string().describe("The name of the recipe."),
prep_time_minutes: z.number().optional().describe("Optional time in minutes to prepare the recipe."),
ingredients: z.array(ingredientSchema),
instructions: z.array(z.string()),
});
const ai = new GoogleGenAI({});
const prompt = `
Please extract the recipe from the following text.
The user wants to make delicious chocolate chip cookies.
They need 2 and 1/4 cups of all-purpose flour, 1 teaspoon of baking soda,
1 teaspoon of salt, 1 cup of unsalted butter (softened), 3/4 cup of granulated sugar,
3/4 cup of packed brown sugar, 1 teaspoon of vanilla extract, and 2 large eggs.
For the best part, they'll need 2 cups of semisweet chocolate chips.
First, preheat the oven to 375°F (190°C). Then, in a small bowl, whisk together the flour,
baking soda, and salt. In a large bowl, cream together the butter, granulated sugar, and brown sugar
until light and fluffy. Beat in the vanilla and eggs, one at a time. Gradually beat in the dry
ingredients until just combined. Finally, stir in the chocolate chips. Drop by rounded tablespoons
onto ungreased baking sheets and bake for 9 to 11 minutes.
`;
const response = await ai.models.generateContent({
model: "gemini-3-flash-preview",
contents: prompt,
config: {
responseMimeType: "application/json",
responseJsonSchema: zodToJsonSchema(recipeSchema),
},
});
const recipe = recipeSchema.parse(JSON.parse(response.text));
console.log(recipe);
```
```
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
prompt := `
Please extract the recipe from the following text.
The user wants to make delicious chocolate chip cookies.
They need 2 and 1/4 cups of all-purpose flour, 1 teaspoon of baking soda,
1 teaspoon of salt, 1 cup of unsalted butter (softened), 3/4 cup of granulated sugar,
3/4 cup of packed brown sugar, 1 teaspoon of vanilla extract, and 2 large eggs.
For the best part, they'll need 2 cups of semisweet chocolate chips.
First, preheat the oven to 375°F (190°C). Then, in a small bowl, whisk together the flour,
baking soda, and salt. In a large bowl, cream together the butter, granulated sugar, and brown sugar
until light and fluffy. Beat in the vanilla and eggs, one at a time. Gradually beat in the dry
ingredients until just combined. Finally, stir in the chocolate chips. Drop by rounded tablespoons
onto ungreased baking sheets and bake for 9 to 11 minutes.
`
config := &genai.GenerateContentConfig{
ResponseMIMEType: "application/json",
ResponseJsonSchema: map[string]any{
"type": "object",
"properties": map[string]any{
"recipe_name": map[string]any{
"type": "string",
"description": "The name of the recipe.",
},
"prep_time_minutes": map[string]any{
"type": "integer",
"description": "Optional time in minutes to prepare the recipe.",
},
"ingredients": map[string]any{
"type": "array",
"items": map[string]any{
"type": "object",
"properties": map[string]any{
"name": map[string]any{
"type": "string",
"description": "Name of the ingredient.",
},
"quantity": map[string]any{
"type": "string",
"description": "Quantity of the ingredient, including units.",
},
},
"required": []string{"name", "quantity"},
},
},
"instructions": map[string]any{
"type": "array",
"items": map[string]any{"type": "string"},
},
},
"required": []string{"recipe_name", "ingredients", "instructions"},
},
}
result, err := client.Models.GenerateContent(
ctx,
"gemini-3-flash-preview",
genai.Text(prompt),
config,
)
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Text())
}
```
```
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [{
"parts":[
{ "text": "Please extract the recipe from the following text.\nThe user wants to make delicious chocolate chip cookies.\nThey need 2 and 1/4 cups of all-purpose flour, 1 teaspoon of baking soda,\n1 teaspoon of salt, 1 cup of unsalted butter (softened), 3/4 cup of granulated sugar,\n3/4 cup of packed brown sugar, 1 teaspoon of vanilla extract, and 2 large eggs.\nFor the best part, they will need 2 cups of semisweet chocolate chips.\nFirst, preheat the oven to 375°F (190°C). Then, in a small bowl, whisk together the flour,\nbaking soda, and salt. In a large bowl, cream together the butter, granulated sugar, and brown sugar\nuntil light and fluffy. Beat in the vanilla and eggs, one at a time. Gradually beat in the dry\ningredients until just combined. Finally, stir in the chocolate chips. Drop by rounded tablespoons\nonto ungreased baking sheets and bake for 9 to 11 minutes." }
]
}],
"generationConfig": {
"responseMimeType": "application/json",
"responseJsonSchema": {
"type": "object",
"properties": {
"recipe_name": {
"type": "string",
"description": "The name of the recipe."
},
"prep_time_minutes": {
"type": "integer",
"description": "Optional time in minutes to prepare the recipe."
},
"ingredients": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": { "type": "string", "description": "Name of the ingredient."},
"quantity": { "type": "string", "description": "Quantity of the ingredient, including units."}
},
"required": ["name", "quantity"]
}
},
"instructions": {
"type": "array",
"items": { "type": "string" }
}
},
"required": ["recipe_name", "ingredients", "instructions"]
}
}
}'
```
**Example Response:**
```
{
"recipe_name": "Delicious Chocolate Chip Cookies",
"ingredients": [
{
"name": "all-purpose flour",
"quantity": "2 and 1/4 cups"
},
{
"name": "baking soda",
"quantity": "1 teaspoon"
},
{
"name": "salt",
"quantity": "1 teaspoon"
},
{
"name": "unsalted butter (softened)",
"quantity": "1 cup"
},
{
"name": "granulated sugar",
"quantity": "3/4 cup"
},
{
"name": "packed brown sugar",
"quantity": "3/4 cup"
},
{
"name": "vanilla extract",
"quantity": "1 teaspoon"
},
{
"name": "large eggs",
"quantity": "2"
},
{
"name": "semisweet chocolate chips",
"quantity": "2 cups"
}
],
"instructions": [
"Preheat the oven to 375°F (190°C).",
"In a small bowl, whisk together the flour, baking soda, and salt.",
"In a large bowl, cream together the butter, granulated sugar, and brown sugar until light and fluffy.",
"Beat in the vanilla and eggs, one at a time.",
"Gradually beat in the dry ingredients until just combined.",
"Stir in the chocolate chips.",
"Drop by rounded tablespoons onto ungreased baking sheets and bake for 9 to 11 minutes."
]
}
```
## Streaming
You can stream structured outputs, which allows you to start processing the response as it's being generated, without having to wait for the entire output to be complete. This can improve the perceived performance of your application.
The streamed chunks will be valid partial JSON strings, which can be concatenated to form the final, complete JSON object.
[Python](https://ai.google.dev/gemini-api/docs/structured-output#python)
[JavaScript](https://ai.google.dev/gemini-api/docs/structured-output#javascript)
More
```
from google import genai
from pydantic import BaseModel, Field
from typing import Literal
class Feedback(BaseModel):
sentiment: Literal["positive", "neutral", "negative"]
summary: str
client = genai.Client()
prompt = "The new UI is incredibly intuitive and visually appealing. Great job. Add a very long summary to test streaming!"
response_stream = client.models.generate_content_stream(
model="gemini-3-flash-preview",
contents=prompt,
config={
"response_mime_type": "application/json",
"response_json_schema": Feedback.model_json_schema(),
},
)
for chunk in response_stream:
print(chunk.candidates[0].content.parts[0].text)
```
```
import { GoogleGenAI } from "@google/genai";
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
const ai = new GoogleGenAI({});
const prompt = "The new UI is incredibly intuitive and visually appealing. Great job! Add a very long summary to test streaming!";
const feedbackSchema = z.object({
sentiment: z.enum(["positive", "neutral", "negative"]),
summary: z.string(),
});
const stream = await ai.models.generateContentStream({
model: "gemini-3-flash-preview",
contents: prompt,
config: {
responseMimeType: "application/json",
responseJsonSchema: zodToJsonSchema(feedbackSchema),
},
});
for await (const chunk of stream) {
console.log(chunk.candidates[0].content.parts[0].text)
}
```
## Structured outputs with tools
**Preview:** This feature is available only to Gemini 3 series models, `gemini-3.1-pro-preview` and `gemini-3-flash-preview`.
Gemini 3 lets you combine Structured Outputs with built-in tools, including [Grounding with Google Search](https://ai.google.dev/gemini-api/docs/google-search), [URL Context](https://ai.google.dev/gemini-api/docs/url-context), [Code Execution](https://ai.google.dev/gemini-api/docs/code-execution), [File Search](https://ai.google.dev/gemini-api/docs/file-search#structured-output), and [Function Calling](https://ai.google.dev/gemini-api/docs/function-calling).
[Python](https://ai.google.dev/gemini-api/docs/structured-output#python)
[JavaScript](https://ai.google.dev/gemini-api/docs/structured-output#javascript)
[REST](https://ai.google.dev/gemini-api/docs/structured-output#rest)
More
```
from google import genai
from pydantic import BaseModel, Field
from typing import List
class MatchResult(BaseModel):
winner: str = Field(description="The name of the winner.")
final_match_score: str = Field(description="The final match score.")
scorers: List[str] = Field(description="The name of the scorer.")
client = genai.Client()
response = client.models.generate_content(
model="gemini-3.1-pro-preview",
contents="Search for all details for the latest Euro.",
config={
"tools": [
{"google_search": {}},
{"url_context": {}}
],
"response_mime_type": "application/json",
"response_json_schema": MatchResult.model_json_schema(),
},
)
result = MatchResult.model_validate_json(response.text)
print(result)
```
```
import { GoogleGenAI } from "@google/genai";
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
const ai = new GoogleGenAI({});
const matchSchema = z.object({
winner: z.string().describe("The name of the winner."),
final_match_score: z.string().describe("The final score."),
scorers: z.array(z.string()).describe("The name of the scorer.")
});
async function run() {
const response = await ai.models.generateContent({
model: "gemini-3.1-pro-preview",
contents: "Search for all details for the latest Euro.",
config: {
tools: [
{ googleSearch: {} },
{ urlContext: {} }
],
responseMimeType: "application/json",
responseJsonSchema: zodToJsonSchema(matchSchema),
},
});
const match = matchSchema.parse(JSON.parse(response.text));
console.log(match);
}
run();
```
```
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-pro-preview:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [{
"parts": [{"text": "Search for all details for the latest Euro."}]
}],
"tools": [
{"googleSearch": {}},
{"urlContext": {}}
],
"generationConfig": {
"responseMimeType": "application/json",
"responseJsonSchema": {
"type": "object",
"properties": {
"winner": {"type": "string", "description": "The name of the winner."},
"final_match_score": {"type": "string", "description": "The final score."},
"scorers": {
"type": "array",
"items": {"type": "string"},
"description": "The name of the scorer."
}
},
"required": ["winner", "final_match_score", "scorers"]
}
}
}'
```
## JSON schema support
To generate a JSON object, set the `response_mime_type` in the generation configuration to `application/json` and provide a `response_json_schema`. The schema must be a valid [JSON Schema](https://json-schema.org/) that describes the desired output format.
The model will then generate a response that is a syntactically valid JSON string matching the provided schema. When using structured outputs, the model will produce outputs in the same order as the keys in the schema.
Gemini's structured output mode supports a subset of the [JSON Schema](https://json-schema.org/) specification.
The following values of `type` are supported:
- **`string`**: For text.
- **`number`**: For floating-point numbers.
- **`integer`**: For whole numbers.
- **`boolean`**: For true/false values.
- **`object`**: For structured data with key-value pairs.
- **`array`**: For lists of items.
- **`null`**: To allow a property to be null, include `"null"` in the type array (e.g., `{"type": ["string", "null"]}`).
These descriptive properties help guide the model:
- **`title`**: A short description of a property.
- **`description`**: A longer and more detailed description of a property.
### Type-specific properties
**For `object` values:**
- **`properties`**: An object where each key is a property name and each value is a schema for that property.
- **`required`**: An array of strings, listing which properties are mandatory.
- **`additionalProperties`**: Controls whether properties not listed in `properties` are allowed. Can be a boolean or a schema.
**For `string` values:**
- **`enum`**: Lists a specific set of possible strings for classification tasks.
- **`format`**: Specifies a syntax for the string, such as `date-time`, `date`, `time`.
**For `number` and `integer` values:**
- **`enum`**: Lists a specific set of possible numeric values.
- **`minimum`**: The minimum inclusive value.
- **`maximum`**: The maximum inclusive value.
**For `array` values:**
- **`items`**: Defines the schema for all items in the array.
- **`prefixItems`**: Defines a list of schemas for the first N items, allowing for tuple-like structures.
- **`minItems`**: The minimum number of items in the array.
- **`maxItems`**: The maximum number of items in the array.
## Model support
The following models support structured output:
| Model | Structured Outputs |
|---|---|
| Gemini 3.1 Pro Preview | ✔️ |
| Gemini 3 Flash Preview | ✔️ |
| Gemini 2.5 Pro | ✔️ |
| Gemini 2.5 Flash | ✔️ |
| Gemini 2.5 Flash-Lite | ✔️ |
| Gemini 2.0 Flash | ✔️\* |
| Gemini 2.0 Flash-Lite | ✔️\* |
*\* Note that Gemini 2.0 requires an explicit `propertyOrdering` list within the JSON input to define the preferred structure. You can find an example in this [cookbook](https://github.com/google-gemini/cookbook/blob/main/examples/Pdf_structured_outputs_on_invoices_and_forms.ipynb).*
## Structured outputs vs. function calling
Both structured outputs and function calling use JSON schemas, but they serve different purposes:
| Feature | Primary Use Case |
|---|---|
| **Structured Outputs** | **Formatting the final response to the user.** Use this when you want the model's *answer* to be in a specific format (e.g., extracting data from a document to save to a database). |
| **Function Calling** | **Taking action during the conversation.** Use this when the model needs to *ask you* to perform a task (e.g., "get current weather") before it can provide a final answer. |
## Best practices
- **Clear descriptions:** Use the `description` field in your schema to provide clear instructions to the model about what each property represents. This is crucial for guiding the model's output.
- **Strong typing:** Use specific types (`integer`, `string`, `enum`) whenever possible. If a parameter has a limited set of valid values, use an `enum`.
- **Prompt engineering:** Clearly state in your prompt what you want the model to do. For example, "Extract the following information from the text..." or "Classify this feedback according to the provided schema...".
- **Validation:** While structured output guarantees syntactically correct JSON, it does not guarantee the values are semantically correct. Always validate the final output in your application code before using it.
- **Error handling:** Implement robust error handling in your application to gracefully manage cases where the model's output, while schema-compliant, may not meet your business logic requirements.
## Limitations
- **Schema subset:** Not all features of the JSON Schema specification are supported. The model ignores unsupported properties.
- **Schema complexity:** The API may reject very large or deeply nested schemas. If you encounter errors, try simplifying your schema by shortening property names, reducing nesting, or limiting the number of constraints.
Was this helpful?
Send feedback
Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2026-02-26 UTC.
- [Terms](https://policies.google.com/terms)
- [Privacy](https://policies.google.com/privacy)
- [Manage cookies](https://ai.google.dev/gemini-api/docs/structured-output)
- [English](https://ai.google.dev/gemini-api/docs/structured-output)
- [Deutsch](https://ai.google.dev/gemini-api/docs/structured-output?hl=de)
- [Español – América Latina](https://ai.google.dev/gemini-api/docs/structured-output?hl=es-419)
- [Français](https://ai.google.dev/gemini-api/docs/structured-output?hl=fr)
- [Indonesia](https://ai.google.dev/gemini-api/docs/structured-output?hl=id)
- [Italiano](https://ai.google.dev/gemini-api/docs/structured-output?hl=it)
- [Polski](https://ai.google.dev/gemini-api/docs/structured-output?hl=pl)
- [Português – Brasil](https://ai.google.dev/gemini-api/docs/structured-output?hl=pt-br)
- [Shqip](https://ai.google.dev/gemini-api/docs/structured-output?hl=sq)
- [Tiếng Việt](https://ai.google.dev/gemini-api/docs/structured-output?hl=vi)
- [Türkçe](https://ai.google.dev/gemini-api/docs/structured-output?hl=tr)
- [Русский](https://ai.google.dev/gemini-api/docs/structured-output?hl=ru)
- [עברית](https://ai.google.dev/gemini-api/docs/structured-output?hl=he)
- [العربيّة](https://ai.google.dev/gemini-api/docs/structured-output?hl=ar)
- [فارسی](https://ai.google.dev/gemini-api/docs/structured-output?hl=fa)
- [हिंदी](https://ai.google.dev/gemini-api/docs/structured-output?hl=hi)
- [বাংলা](https://ai.google.dev/gemini-api/docs/structured-output?hl=bn)
- [ภาษาไทย](https://ai.google.dev/gemini-api/docs/structured-output?hl=th)
- [中文 – 简体](https://ai.google.dev/gemini-api/docs/structured-output?hl=zh-cn)
- [中文 – 繁體](https://ai.google.dev/gemini-api/docs/structured-output?hl=zh-tw)
- [日本語](https://ai.google.dev/gemini-api/docs/structured-output?hl=ja)
- [한국어](https://ai.google.dev/gemini-api/docs/structured-output?hl=ko) |
| Readable Markdown | [Skip to main content](https://ai.google.dev/gemini-api/docs/structured-output#main-content)
- [Gemini API](https://ai.google.dev/gemini-api/docs)
- [Docs](https://ai.google.dev/gemini-api/docs)
- [API reference](https://ai.google.dev/api)
- [Get API key](https://aistudio.google.com/apikey)
- [Cookbook](https://github.com/google-gemini/cookbook)
- [Community](https://discuss.ai.google.dev/c/gemini-api/)
- Get started
- [Overview](https://ai.google.dev/gemini-api/docs)
- [Quickstart](https://ai.google.dev/gemini-api/docs/quickstart)
- [API keys](https://ai.google.dev/gemini-api/docs/api-key)
- [Libraries](https://ai.google.dev/gemini-api/docs/libraries)
- [Pricing](https://ai.google.dev/gemini-api/docs/pricing)
- [Interactions API](https://ai.google.dev/gemini-api/docs/interactions)
- [Coding agent setup](https://ai.google.dev/gemini-api/docs/coding-agents)
- Models
- [All models](https://ai.google.dev/gemini-api/docs/models)
- [Gemini 3](https://ai.google.dev/gemini-api/docs/gemini-3)
- [Nano Banana](https://ai.google.dev/gemini-api/docs/image-generation)
- [Veo](https://ai.google.dev/gemini-api/docs/video)
- [Lyria 3](https://ai.google.dev/gemini-api/docs/music-generation)
- [Lyria Real Time](https://ai.google.dev/gemini-api/docs/realtime-music-generation)
- [Imagen](https://ai.google.dev/gemini-api/docs/imagen)
- [Text-to-speech](https://ai.google.dev/gemini-api/docs/speech-generation)
- [Embeddings](https://ai.google.dev/gemini-api/docs/embeddings)
- [Robotics](https://ai.google.dev/gemini-api/docs/robotics-overview)
- Core capabilities
- [Text](https://ai.google.dev/gemini-api/docs/text-generation)
- [Documents](https://ai.google.dev/gemini-api/docs/document-processing)
- [Structured outputs](https://ai.google.dev/gemini-api/docs/structured-output)
- [Function calling](https://ai.google.dev/gemini-api/docs/function-calling)
- [Long context](https://ai.google.dev/gemini-api/docs/long-context)
- Agents
- [Overview](https://ai.google.dev/gemini-api/docs/agents)
- [Deep Research Agent](https://ai.google.dev/gemini-api/docs/deep-research)
- Tools
- [Overview](https://ai.google.dev/gemini-api/docs/tools)
- [Google Search](https://ai.google.dev/gemini-api/docs/google-search)
- [Google Maps](https://ai.google.dev/gemini-api/docs/maps-grounding)
- [Code execution](https://ai.google.dev/gemini-api/docs/code-execution)
- [URL context](https://ai.google.dev/gemini-api/docs/url-context)
- [Computer Use](https://ai.google.dev/gemini-api/docs/computer-use)
- [File Search](https://ai.google.dev/gemini-api/docs/file-search)
- [Combine Tools and Function calling](https://ai.google.dev/gemini-api/docs/tool-combination)
- Live API
- [Overview](https://ai.google.dev/gemini-api/docs/live-api)
- [Capabilities](https://ai.google.dev/gemini-api/docs/live-api/capabilities)
- [Tool use](https://ai.google.dev/gemini-api/docs/live-api/tools)
- [Session management](https://ai.google.dev/gemini-api/docs/live-api/session-management)
- [Ephemeral tokens](https://ai.google.dev/gemini-api/docs/live-api/ephemeral-tokens)
- [Best practices](https://ai.google.dev/gemini-api/docs/live-api/best-practices)
- Optimization
- [Overview](https://ai.google.dev/gemini-api/docs/optimization)
- [Batch API](https://ai.google.dev/gemini-api/docs/batch-api)
- [Flex inference](https://ai.google.dev/gemini-api/docs/flex-inference)
- [Priority inference](https://ai.google.dev/gemini-api/docs/priority-inference)
- [Context caching](https://ai.google.dev/gemini-api/docs/caching)
- Guides
- [Open AI compatibility](https://ai.google.dev/gemini-api/docs/openai)
- [Media resolution](https://ai.google.dev/gemini-api/docs/media-resolution)
- [Token counting](https://ai.google.dev/gemini-api/docs/tokens)
- [Prompt engineering](https://ai.google.dev/gemini-api/docs/prompting-strategies)
- Resources
- [Release notes](https://ai.google.dev/gemini-api/docs/changelog)
- [Deprecations](https://ai.google.dev/gemini-api/docs/deprecations)
- [Rate limits](https://ai.google.dev/gemini-api/docs/rate-limits)
- [Billing info](https://ai.google.dev/gemini-api/docs/billing)
- [Migrate to Gen AI SDK](https://ai.google.dev/gemini-api/docs/migrate)
- [API troubleshooting](https://ai.google.dev/gemini-api/docs/troubleshooting)
- [Partner and library integrations](https://ai.google.dev/gemini-api/docs/partner-integration)
- Policies
- [Terms of service](https://ai.google.dev/gemini-api/terms)
- [Available regions](https://ai.google.dev/gemini-api/docs/available-regions)
- [Abuse monitoring](https://ai.google.dev/gemini-api/docs/usage-policies)
- [Feedback information](https://ai.google.dev/gemini-api/docs/feedback-policies)
- On this page
- [Streaming](https://ai.google.dev/gemini-api/docs/structured-output#streaming)
- [Structured outputs with tools](https://ai.google.dev/gemini-api/docs/structured-output#structured_outputs_with_tools)
- [JSON schema support](https://ai.google.dev/gemini-api/docs/structured-output#json_schema_support)
- [Type-specific properties](https://ai.google.dev/gemini-api/docs/structured-output#type-specific_properties)
- [Model support](https://ai.google.dev/gemini-api/docs/structured-output#model_support)
- [Structured outputs vs. function calling](https://ai.google.dev/gemini-api/docs/structured-output#structured_outputs_vs_function_calling)
- [Best practices](https://ai.google.dev/gemini-api/docs/structured-output#best_practices)
- [Limitations](https://ai.google.dev/gemini-api/docs/structured-output#limitations)
You can configure Gemini models to generate responses that adhere to a provided JSON Schema. This ensures predictable, type-safe results and simplifies extracting structured data from unstructured text.
Using structured outputs is ideal for:
- **Data extraction:** Pull specific information like names and dates from text.
- **Structured classification:** Classify text into predefined categories.
- **Agentic workflows:** Generate structured inputs for tools or APIs.
In addition to supporting JSON Schema in the REST API, the Google GenAI SDKs make it easy to define schemas using [Pydantic](https://docs.pydantic.dev/latest/) (Python) and [Zod](https://zod.dev/) (JavaScript).
This example demonstrates how to extract structured data from text using basic JSON Schema types like `object`, `array`, `string`, and `integer`.
```
from google import genai
from pydantic import BaseModel, Field
from typing import List, Optional
class Ingredient(BaseModel):
name: str = Field(description="Name of the ingredient.")
quantity: str = Field(description="Quantity of the ingredient, including units.")
class Recipe(BaseModel):
recipe_name: str = Field(description="The name of the recipe.")
prep_time_minutes: Optional[int] = Field(description="Optional time in minutes to prepare the recipe.")
ingredients: List[Ingredient]
instructions: List[str]
client = genai.Client()
prompt = """
Please extract the recipe from the following text.
The user wants to make delicious chocolate chip cookies.
They need 2 and 1/4 cups of all-purpose flour, 1 teaspoon of baking soda,
1 teaspoon of salt, 1 cup of unsalted butter (softened), 3/4 cup of granulated sugar,
3/4 cup of packed brown sugar, 1 teaspoon of vanilla extract, and 2 large eggs.
For the best part, they'll need 2 cups of semisweet chocolate chips.
First, preheat the oven to 375°F (190°C). Then, in a small bowl, whisk together the flour,
baking soda, and salt. In a large bowl, cream together the butter, granulated sugar, and brown sugar
until light and fluffy. Beat in the vanilla and eggs, one at a time. Gradually beat in the dry
ingredients until just combined. Finally, stir in the chocolate chips. Drop by rounded tablespoons
onto ungreased baking sheets and bake for 9 to 11 minutes.
"""
response = client.models.generate_content(
model="gemini-3-flash-preview",
contents=prompt,
config={
"response_mime_type": "application/json",
"response_json_schema": Recipe.model_json_schema(),
},
)
recipe = Recipe.model_validate_json(response.text)
print(recipe)
```
```
import { GoogleGenAI } from "@google/genai";
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
const ingredientSchema = z.object({
name: z.string().describe("Name of the ingredient."),
quantity: z.string().describe("Quantity of the ingredient, including units."),
});
const recipeSchema = z.object({
recipe_name: z.string().describe("The name of the recipe."),
prep_time_minutes: z.number().optional().describe("Optional time in minutes to prepare the recipe."),
ingredients: z.array(ingredientSchema),
instructions: z.array(z.string()),
});
const ai = new GoogleGenAI({});
const prompt = `
Please extract the recipe from the following text.
The user wants to make delicious chocolate chip cookies.
They need 2 and 1/4 cups of all-purpose flour, 1 teaspoon of baking soda,
1 teaspoon of salt, 1 cup of unsalted butter (softened), 3/4 cup of granulated sugar,
3/4 cup of packed brown sugar, 1 teaspoon of vanilla extract, and 2 large eggs.
For the best part, they'll need 2 cups of semisweet chocolate chips.
First, preheat the oven to 375°F (190°C). Then, in a small bowl, whisk together the flour,
baking soda, and salt. In a large bowl, cream together the butter, granulated sugar, and brown sugar
until light and fluffy. Beat in the vanilla and eggs, one at a time. Gradually beat in the dry
ingredients until just combined. Finally, stir in the chocolate chips. Drop by rounded tablespoons
onto ungreased baking sheets and bake for 9 to 11 minutes.
`;
const response = await ai.models.generateContent({
model: "gemini-3-flash-preview",
contents: prompt,
config: {
responseMimeType: "application/json",
responseJsonSchema: zodToJsonSchema(recipeSchema),
},
});
const recipe = recipeSchema.parse(JSON.parse(response.text));
console.log(recipe);
```
```
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
prompt := `
Please extract the recipe from the following text.
The user wants to make delicious chocolate chip cookies.
They need 2 and 1/4 cups of all-purpose flour, 1 teaspoon of baking soda,
1 teaspoon of salt, 1 cup of unsalted butter (softened), 3/4 cup of granulated sugar,
3/4 cup of packed brown sugar, 1 teaspoon of vanilla extract, and 2 large eggs.
For the best part, they'll need 2 cups of semisweet chocolate chips.
First, preheat the oven to 375°F (190°C). Then, in a small bowl, whisk together the flour,
baking soda, and salt. In a large bowl, cream together the butter, granulated sugar, and brown sugar
until light and fluffy. Beat in the vanilla and eggs, one at a time. Gradually beat in the dry
ingredients until just combined. Finally, stir in the chocolate chips. Drop by rounded tablespoons
onto ungreased baking sheets and bake for 9 to 11 minutes.
`
config := &genai.GenerateContentConfig{
ResponseMIMEType: "application/json",
ResponseJsonSchema: map[string]any{
"type": "object",
"properties": map[string]any{
"recipe_name": map[string]any{
"type": "string",
"description": "The name of the recipe.",
},
"prep_time_minutes": map[string]any{
"type": "integer",
"description": "Optional time in minutes to prepare the recipe.",
},
"ingredients": map[string]any{
"type": "array",
"items": map[string]any{
"type": "object",
"properties": map[string]any{
"name": map[string]any{
"type": "string",
"description": "Name of the ingredient.",
},
"quantity": map[string]any{
"type": "string",
"description": "Quantity of the ingredient, including units.",
},
},
"required": []string{"name", "quantity"},
},
},
"instructions": map[string]any{
"type": "array",
"items": map[string]any{"type": "string"},
},
},
"required": []string{"recipe_name", "ingredients", "instructions"},
},
}
result, err := client.Models.GenerateContent(
ctx,
"gemini-3-flash-preview",
genai.Text(prompt),
config,
)
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Text())
}
```
```
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [{
"parts":[
{ "text": "Please extract the recipe from the following text.\nThe user wants to make delicious chocolate chip cookies.\nThey need 2 and 1/4 cups of all-purpose flour, 1 teaspoon of baking soda,\n1 teaspoon of salt, 1 cup of unsalted butter (softened), 3/4 cup of granulated sugar,\n3/4 cup of packed brown sugar, 1 teaspoon of vanilla extract, and 2 large eggs.\nFor the best part, they will need 2 cups of semisweet chocolate chips.\nFirst, preheat the oven to 375°F (190°C). Then, in a small bowl, whisk together the flour,\nbaking soda, and salt. In a large bowl, cream together the butter, granulated sugar, and brown sugar\nuntil light and fluffy. Beat in the vanilla and eggs, one at a time. Gradually beat in the dry\ningredients until just combined. Finally, stir in the chocolate chips. Drop by rounded tablespoons\nonto ungreased baking sheets and bake for 9 to 11 minutes." }
]
}],
"generationConfig": {
"responseMimeType": "application/json",
"responseJsonSchema": {
"type": "object",
"properties": {
"recipe_name": {
"type": "string",
"description": "The name of the recipe."
},
"prep_time_minutes": {
"type": "integer",
"description": "Optional time in minutes to prepare the recipe."
},
"ingredients": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": { "type": "string", "description": "Name of the ingredient."},
"quantity": { "type": "string", "description": "Quantity of the ingredient, including units."}
},
"required": ["name", "quantity"]
}
},
"instructions": {
"type": "array",
"items": { "type": "string" }
}
},
"required": ["recipe_name", "ingredients", "instructions"]
}
}
}'
```
**Example Response:**
```
{
"recipe_name": "Delicious Chocolate Chip Cookies",
"ingredients": [
{
"name": "all-purpose flour",
"quantity": "2 and 1/4 cups"
},
{
"name": "baking soda",
"quantity": "1 teaspoon"
},
{
"name": "salt",
"quantity": "1 teaspoon"
},
{
"name": "unsalted butter (softened)",
"quantity": "1 cup"
},
{
"name": "granulated sugar",
"quantity": "3/4 cup"
},
{
"name": "packed brown sugar",
"quantity": "3/4 cup"
},
{
"name": "vanilla extract",
"quantity": "1 teaspoon"
},
{
"name": "large eggs",
"quantity": "2"
},
{
"name": "semisweet chocolate chips",
"quantity": "2 cups"
}
],
"instructions": [
"Preheat the oven to 375°F (190°C).",
"In a small bowl, whisk together the flour, baking soda, and salt.",
"In a large bowl, cream together the butter, granulated sugar, and brown sugar until light and fluffy.",
"Beat in the vanilla and eggs, one at a time.",
"Gradually beat in the dry ingredients until just combined.",
"Stir in the chocolate chips.",
"Drop by rounded tablespoons onto ungreased baking sheets and bake for 9 to 11 minutes."
]
}
```
## Streaming
You can stream structured outputs, which allows you to start processing the response as it's being generated, without having to wait for the entire output to be complete. This can improve the perceived performance of your application.
The streamed chunks will be valid partial JSON strings, which can be concatenated to form the final, complete JSON object.
```
from google import genai
from pydantic import BaseModel, Field
from typing import Literal
class Feedback(BaseModel):
sentiment: Literal["positive", "neutral", "negative"]
summary: str
client = genai.Client()
prompt = "The new UI is incredibly intuitive and visually appealing. Great job. Add a very long summary to test streaming!"
response_stream = client.models.generate_content_stream(
model="gemini-3-flash-preview",
contents=prompt,
config={
"response_mime_type": "application/json",
"response_json_schema": Feedback.model_json_schema(),
},
)
for chunk in response_stream:
print(chunk.candidates[0].content.parts[0].text)
```
```
import { GoogleGenAI } from "@google/genai";
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
const ai = new GoogleGenAI({});
const prompt = "The new UI is incredibly intuitive and visually appealing. Great job! Add a very long summary to test streaming!";
const feedbackSchema = z.object({
sentiment: z.enum(["positive", "neutral", "negative"]),
summary: z.string(),
});
const stream = await ai.models.generateContentStream({
model: "gemini-3-flash-preview",
contents: prompt,
config: {
responseMimeType: "application/json",
responseJsonSchema: zodToJsonSchema(feedbackSchema),
},
});
for await (const chunk of stream) {
console.log(chunk.candidates[0].content.parts[0].text)
}
```
## Structured outputs with tools
Gemini 3 lets you combine Structured Outputs with built-in tools, including [Grounding with Google Search](https://ai.google.dev/gemini-api/docs/google-search), [URL Context](https://ai.google.dev/gemini-api/docs/url-context), [Code Execution](https://ai.google.dev/gemini-api/docs/code-execution), [File Search](https://ai.google.dev/gemini-api/docs/file-search#structured-output), and [Function Calling](https://ai.google.dev/gemini-api/docs/function-calling).
```
from google import genai
from pydantic import BaseModel, Field
from typing import List
class MatchResult(BaseModel):
winner: str = Field(description="The name of the winner.")
final_match_score: str = Field(description="The final match score.")
scorers: List[str] = Field(description="The name of the scorer.")
client = genai.Client()
response = client.models.generate_content(
model="gemini-3.1-pro-preview",
contents="Search for all details for the latest Euro.",
config={
"tools": [
{"google_search": {}},
{"url_context": {}}
],
"response_mime_type": "application/json",
"response_json_schema": MatchResult.model_json_schema(),
},
)
result = MatchResult.model_validate_json(response.text)
print(result)
```
```
import { GoogleGenAI } from "@google/genai";
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
const ai = new GoogleGenAI({});
const matchSchema = z.object({
winner: z.string().describe("The name of the winner."),
final_match_score: z.string().describe("The final score."),
scorers: z.array(z.string()).describe("The name of the scorer.")
});
async function run() {
const response = await ai.models.generateContent({
model: "gemini-3.1-pro-preview",
contents: "Search for all details for the latest Euro.",
config: {
tools: [
{ googleSearch: {} },
{ urlContext: {} }
],
responseMimeType: "application/json",
responseJsonSchema: zodToJsonSchema(matchSchema),
},
});
const match = matchSchema.parse(JSON.parse(response.text));
console.log(match);
}
run();
```
```
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-pro-preview:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [{
"parts": [{"text": "Search for all details for the latest Euro."}]
}],
"tools": [
{"googleSearch": {}},
{"urlContext": {}}
],
"generationConfig": {
"responseMimeType": "application/json",
"responseJsonSchema": {
"type": "object",
"properties": {
"winner": {"type": "string", "description": "The name of the winner."},
"final_match_score": {"type": "string", "description": "The final score."},
"scorers": {
"type": "array",
"items": {"type": "string"},
"description": "The name of the scorer."
}
},
"required": ["winner", "final_match_score", "scorers"]
}
}
}'
```
## JSON schema support
To generate a JSON object, set the `response_mime_type` in the generation configuration to `application/json` and provide a `response_json_schema`. The schema must be a valid [JSON Schema](https://json-schema.org/) that describes the desired output format.
The model will then generate a response that is a syntactically valid JSON string matching the provided schema. When using structured outputs, the model will produce outputs in the same order as the keys in the schema.
Gemini's structured output mode supports a subset of the [JSON Schema](https://json-schema.org/) specification.
The following values of `type` are supported:
- **`string`**: For text.
- **`number`**: For floating-point numbers.
- **`integer`**: For whole numbers.
- **`boolean`**: For true/false values.
- **`object`**: For structured data with key-value pairs.
- **`array`**: For lists of items.
- **`null`**: To allow a property to be null, include `"null"` in the type array (e.g., `{"type": ["string", "null"]}`).
These descriptive properties help guide the model:
- **`title`**: A short description of a property.
- **`description`**: A longer and more detailed description of a property.
### Type-specific properties
**For `object` values:**
- **`properties`**: An object where each key is a property name and each value is a schema for that property.
- **`required`**: An array of strings, listing which properties are mandatory.
- **`additionalProperties`**: Controls whether properties not listed in `properties` are allowed. Can be a boolean or a schema.
**For `string` values:**
- **`enum`**: Lists a specific set of possible strings for classification tasks.
- **`format`**: Specifies a syntax for the string, such as `date-time`, `date`, `time`.
**For `number` and `integer` values:**
- **`enum`**: Lists a specific set of possible numeric values.
- **`minimum`**: The minimum inclusive value.
- **`maximum`**: The maximum inclusive value.
**For `array` values:**
- **`items`**: Defines the schema for all items in the array.
- **`prefixItems`**: Defines a list of schemas for the first N items, allowing for tuple-like structures.
- **`minItems`**: The minimum number of items in the array.
- **`maxItems`**: The maximum number of items in the array.
## Model support
The following models support structured output:
| Model | Structured Outputs |
|---|---|
| Gemini 3.1 Pro Preview | ✔️ |
| Gemini 3 Flash Preview | ✔️ |
| Gemini 2.5 Pro | ✔️ |
| Gemini 2.5 Flash | ✔️ |
| Gemini 2.5 Flash-Lite | ✔️ |
| Gemini 2.0 Flash | ✔️\* |
| Gemini 2.0 Flash-Lite | ✔️\* |
*\* Note that Gemini 2.0 requires an explicit `propertyOrdering` list within the JSON input to define the preferred structure. You can find an example in this [cookbook](https://github.com/google-gemini/cookbook/blob/main/examples/Pdf_structured_outputs_on_invoices_and_forms.ipynb).*
## Structured outputs vs. function calling
Both structured outputs and function calling use JSON schemas, but they serve different purposes:
| Feature | Primary Use Case |
|---|---|
| **Structured Outputs** | **Formatting the final response to the user.** Use this when you want the model's *answer* to be in a specific format (e.g., extracting data from a document to save to a database). |
| **Function Calling** | **Taking action during the conversation.** Use this when the model needs to *ask you* to perform a task (e.g., "get current weather") before it can provide a final answer. |
## Best practices
- **Clear descriptions:** Use the `description` field in your schema to provide clear instructions to the model about what each property represents. This is crucial for guiding the model's output.
- **Strong typing:** Use specific types (`integer`, `string`, `enum`) whenever possible. If a parameter has a limited set of valid values, use an `enum`.
- **Prompt engineering:** Clearly state in your prompt what you want the model to do. For example, "Extract the following information from the text..." or "Classify this feedback according to the provided schema...".
- **Validation:** While structured output guarantees syntactically correct JSON, it does not guarantee the values are semantically correct. Always validate the final output in your application code before using it.
- **Error handling:** Implement robust error handling in your application to gracefully manage cases where the model's output, while schema-compliant, may not meet your business logic requirements.
## Limitations
- **Schema subset:** Not all features of the JSON Schema specification are supported. The model ignores unsupported properties.
- **Schema complexity:** The API may reject very large or deeply nested schemas. If you encounter errors, try simplifying your schema by shortening property names, reducing nesting, or limiting the number of constraints.
Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2026-02-26 UTC. |
| Shard | 189 (laksa) |
| Root Hash | 1013294096244278789 |
| Unparsed URL | dev,google!ai,/gemini-api/docs/structured-output s443 |