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).
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.

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.
| Comparison | Structured Outputs | Function Calling |
|---|---|---|
| Primary goal | Fixed-structure JSON response | Call an external tool or function |
| Typical scenarios | Extraction, classification, order parsing | DB lookup, API call, side effects |
| Result | Structured response body | Function-call request for your runtime |
| App must execute an action? | Not necessarily | Usually yes |
| Core tech | JSON Schema / response schema | Function declarations |

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).

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 feature | Official note (verify on docs) |
|---|---|
| string, integer, number, boolean, array, object, null | Supported types |
| enum | Supported |
| additionalProperties | Supported |
| minimum / maximum | Supported for numbers |
| minItems / maxItems | Supported and enforced |
| minLength / maxLength | Not enforced by constrained decoding — validate in app |
| uniqueItems | Not enforced — dedupe in app if required |
| minProperties / maxProperties | Not enforced — validate in app |
| Very large / deeply nested schemas | May 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.
| Control | Acceptance check |
|---|---|
| Schema versioning | Schema id recorded per request |
| Pydantic validate | Invalid payloads never reach DB |
| Retry budget | Hard max attempts + jitter |
| Golden tests | Fixture emails/orders pass in CI |
| Replay | Can 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 item | What to check |
|---|---|
| Input tokens | Prompt + schema overhead for your model |
| Output tokens | Returned JSON size |
| Thinking tokens | If enabled for that model |
| Retries | Failed validates / 400s that re-call the API |
| Service mode | Standard 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.



