Building with the API

Get structured JSON output from the Gemini API

3 min read

The Gemini API can return JSON constrained to a schema, so you skip brittle string parsing. With the google-genai SDK you pass a response_format on the Interactions API and hand it your schema. The OpenAI equivalent is structured outputs; if you have not called Gemini yet, start with your first Gemini API request.

1. Install google-genai and pydantic

pip install -U google-genai pydantic

Pydantic gives you a schema and client-side validation in one model.

2. Define the schema as a Pydantic model

from pydantic import BaseModel

class Recipe(BaseModel):
    name: str
    minutes: int
    ingredients: list[str]

A plain Pydantic model whose JSON Schema you send as the response contract.

3. Request JSON with response_format

from google import genai

client = genai.Client()  # reads GEMINI_API_KEY

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input="Give me a recipe for pancakes.",
    response_format={
        "type": "text",
        "mime_type": "application/json",
        "schema": Recipe.model_json_schema(),
    },
)

response_format sets the MIME type to JSON and pins the output to your schema.

4. Parse the response into the typed object

recipe = Recipe.model_validate_json(interaction.output_text)
print(recipe.name, recipe.minutes)

model_validate_json turns the JSON text into a typed Recipe you can use directly.

5. Constrain fields with enums

from typing import Literal
from pydantic import BaseModel

class Ticket(BaseModel):
    priority: Literal["low", "medium", "high"]
    hours: int

A Literal becomes a JSON Schema enum, so the model must pick one of the allowed values.

Gemini enforces enum, minimum, and maximum on numbers, and minItems and maxItems on arrays; constraints like minLength it does not enforce, so keep validating with Pydantic after parsing. Structured output combined with tools is preview and limited to the Gemini 3 series. Model ids change: take the current one from the structured output docs or the models page.

Verify it worked

interaction.output_text should be valid JSON, and model_validate_json should return a Recipe without raising.

If it fails:


Next: OpenAI structured outputs · glossary: structured output.

Open the full interactive version (with copy buttons) ↗

← All guides