How to Use Gemini API Structured Outputs with JSON Schema and Python

Learn how to use Gemini API Structured Outputs with JSON Schema and Python. Explore Pydantic validation, supported schema features, error handling, and production-ready examples.

How to Use Gemini API Structured Outputs with JSON Schema and Python

Gemini Structured Outputs constrains the response to a supported JSON Schema, making machine-readable output more predictable. However, schema compliance does not guarantee factual accuracy or business-rule correctness. Applications should still validate returned values before storing or processing them. This guide covers schema design, a copy-paste Python example using <code>gemini-3.5-flash-lite</code> (re-verify on Models before deploy), supported vs ignored schema keywords, troubleshooting HTTP 400 / invalid JSON, and how Structured Outputs differs from Function Calling. Primary docs: Structured outputs (verified November 24, 2026).

Using the product from: Gemini API Structured Outputs: Turn Model Replies Into Reliable JSON

What Is Gemini Structured Outputs?

Structured Outputs asks Gemini to return JSON that matches a declared schema (or enum MIME type) instead of free-form prose. Typical uses: order extraction, classification labels, ticket routing fields, and webhook payloads that must deserialize cleanly.

Think in three layers: (1) parseable JSON, (2) structure that matches the supported schema subset, (3) business-correct values. Only layers 1–2 are what constrained decoding improves; layer 3 still needs app validation, golden tests, and retries.

Infographic: What schema-constrained JSON means for API developers

Structured Outputs vs Function Calling

Structured Outputs shapes the model’s final response. Function Calling asks the model to request that your app run a tool or API (Function calling docs). Choose based on whether you need a typed document or a side-effecting action.

ComparisonStructured OutputsFunction Calling
Primary goalFixed-structure JSON responseCall an external tool or function
Typical scenariosExtraction, classification, order parsingDB lookup, API call, side effects
ResultStructured response bodyFunction-call request for your runtime
App must execute an action?Not necessarilyUsually yes
Core techJSON Schema / response schemaFunction declarations
Infographic: How to define a response schema with JSON Schema

How to Define a JSON Schema for Gemini

Keep schemas small and shallow: required fields only, enums for closed vocabularies, and explicit types. Prefer <code>minItems</code>/<code>maxItems</code> when you need array bounds that constrained decoding will enforce. Put long prose instructions in the prompt, not in dozens of nested properties.

If you generate schemas from Pydantic/Zod helpers, remember some Field constraints are stripped by the API—validate those client-side (next section).

Photo: Google GenAI SDK + Python complete example

Gemini Structured Outputs: Supported JSON Schema Features and Limitations

Gemini Structured Outputs supports a subset of JSON Schema. Unsupported counting/length constraints are ignored during constrained decoding rather than always erroring—so client validation is mandatory. Details: official docs.

Schema featureOfficial note (verify on docs)
string, integer, number, boolean, array, object, nullSupported types
enumSupported
additionalPropertiesSupported
minimum / maximumSupported for numbers
minItems / maxItemsSupported and enforced
minLength / maxLengthNot enforced by constrained decoding — validate in app
uniqueItemsNot enforced — dedupe in app if required
minProperties / maxPropertiesNot enforced — validate in app
Very large / deeply nested schemasMay return 400 INVALID_ARGUMENT

Complete Python Example with Pydantic

This example uses <code>gemini-3.5-flash-lite</code> as a currently supported Flash-class model that works with Structured Outputs patterns documented for Gemini 3.x / 4.x series—re-check model cards and structured-output before production. Requires <code>google-genai</code> and <code>pydantic</code>. Last code verification date: <strong>2026-11-24</strong>.

<pre>from google import genai from google.genai import types from pydantic import BaseModel, ValidationError class LineItem(BaseModel): sku: str qty: int class ExtractedOrder(BaseModel): order_id: str currency: str total_cents: int line_items: list[LineItem] needs_human: bool client = genai.Client() # GEMINI_API_KEY / ADC prompt = “””Extract the order fields from this email. Order 8841 / USD / 2x SKU-19 @ 1500 cents each, total 3000 cents. Flag needs_human if anything is ambiguous.””” # Verified against Structured Outputs docs on 2026-11-24. # Re-check https://ai.google.dev/gemini-api/docs/models before deploy — model ids change. response = client.models.generate_content( model=”gemini-3.5-flash-lite”, contents=prompt, config=types.GenerateContentConfig( response_mime_type=”application/json”, response_schema=ExtractedOrder, ), ) raw = response.text or “” try: order = ExtractedOrder.model_validate_json(raw) except ValidationError as exc: raise SystemExit(f”schema/business validation failed: {exc}”) from exc print(order.model_dump_json(indent=2)) </pre>

Do not ship shutdown IDs such as <code>gemini-2.0-flash</code> (retired earlier in 2026). Keep the model id in config so you can rotate without rewriting tutorials in every service.

How to Fix Invalid JSON and HTTP 400

Empty or truncated JSON: check finish/stop reasons, max output tokens, and whether the schema is too large for one call. Split extraction into smaller objects when a single schema is huge.

HTTP 400 INVALID_ARGUMENT: usually an overly complex or deeply nested schema, or unsupported shape after compilation into the constrained-decoding state machine. Simplify properties, reduce nesting, and retest.

Structure OK but business wrong: log schema version + raw text + validation errors; retry with a tighter prompt; send ambiguous rows to a human queue when <code>needs_human</code> is true.

Production Logging and Retry Strategy

Keep a go-live checklist: pin schema version, cap retries, store raw model text for replay, run golden fixtures in CI, and never write unvalidated JSON to primary stores. Treat validation failures as first-class metrics.

ControlAcceptance check
Schema versioningSchema id recorded per request
Pydantic validateInvalid payloads never reach DB
Retry budgetHard max attempts + jitter
Golden testsFixture emails/orders pass in CI
ReplayCan rebuild failure from stored raw JSON

Pricing and Token Costs (not a Structured Outputs fee)

Structured Outputs is not a separate SKU. You pay normal Gemini token charges for the prompt (including schema size toward input) and for the JSON output—plus any thinking tokens if your model uses them, and extra cost from retries. Confirm live rates on Gemini API pricing for the exact model and tier (Standard vs Batch). Do not treat a single dollar figure as “the Structured Outputs price.”

Cost itemWhat to check
Input tokensPrompt + schema overhead for your model
Output tokensReturned JSON size
Thinking tokensIf enabled for that model
RetriesFailed validates / 400s that re-call the API
Service modeStandard vs Batch list prices on pricing page

Research Methodology

This article summarizes Google’s official documentation and implementation guidance for Gemini API Structured Outputs. The examples focus on schema definition, response parsing, and application-level validation (verified November 24, 2026).

Ship schema constraints plus app validation

Use Structured Outputs for predictable JSON shapes, keep schemas inside the supported subset, validate with Pydantic, and rotate model ids as Google retires older Flash/Pro generations. Do not force one structured-output request to serve both machine-readable data and long-form explanations.

FAQ

Does Gemini Structured Output guarantee valid JSON?
It improves adherence to a supported schema, but you must still parse and validate. It does not guarantee factual or business-rule correctness.
Which JSON Schema keywords does Gemini support?
Core types, enum, additionalProperties, numeric min/max, and minItems/maxItems are among the supported/enforced features. minLength/maxLength, uniqueItems, and min/maxProperties are not enforced by constrained decoding—validate in your app.
Why does Gemini return HTTP 400 for structured output?
Often the schema is too large, too deeply nested, or exceeds compilation limits. Simplify the schema and retry; check the error payload for INVALID_ARGUMENT details.
How do I validate output using Pydantic?
Pass a Pydantic model as response_schema (or equivalent), then run model_validate_json on response.text before side effects.
How do Structured Outputs differ from Function Calling?
Structured Outputs constrains the final JSON response. Function Calling requests that your application execute a tool. Use the former for extraction; the latter for actions.
Can Gemini return incomplete structured output?
Yes—truncation, stop reasons, or ignored constraints can yield partial or schema-shaped-but-wrong data. Log finish reasons, validate, and retry or escalate.