Gemini API: JSON Mode Quickstart

The Gemini API can be used to generate a JSON output if you set the schema that you would like to use.

Two methods are available. You can either set the desired output in the prompt or supply a schema to the model separately.

Setup

Install the Google GenAI SDK

Install the Google GenAI SDK from npm.

$ npm install @google/genai

Setup your API key

You can create your API key using Google AI Studio with a single click.

Remember to treat your API key like a password. Don’t accidentally save it in a notebook or source file you later commit to GitHub. In this notebook we will be storing the API key in a .env file. You can also set it as an environment variable or use a secret manager.

Here’s how to set it up in a .env file:

$ touch .env
$ echo "GEMINI_API_KEY=<YOUR_API_KEY>" >> .env
Tip

Another option is to set the API key as an environment variable. You can do this in your terminal with the following command:

$ export GEMINI_API_KEY="<YOUR_API_KEY>"

Load the API key

To load the API key from the .env file, we will use the dotenv package. This package loads environment variables from a .env file into process.env.

$ npm install dotenv

Then, we can load the API key in our code:

const dotenv = require("dotenv") as typeof import("dotenv");

dotenv.config({
  path: "../.env",
});

const GEMINI_API_KEY = process.env.GEMINI_API_KEY ?? "";
if (!GEMINI_API_KEY) {
  throw new Error("GEMINI_API_KEY is not set in the environment variables");
}
console.log("GEMINI_API_KEY is set in the environment variables");
GEMINI_API_KEY is set in the environment variables
Note

In our particular case the .env is is one directory up from the notebook, hence we need to use ../ to go up one directory. If the .env file is in the same directory as the notebook, you can omit it altogether.

│
├── .env
└── quickstarts
    └── JSON_mode.ipynb

Initialize SDK Client

With the new SDK, now you only need to initialize a client with you API key (or OAuth if using Vertex AI). The model is now set in each call.

const google = require("@google/genai") as typeof import("@google/genai");

const ai = new google.GoogleGenAI({ apiKey: GEMINI_API_KEY });

Select a model

Now select the model you want to use in this guide, either by selecting one in the list or writing it down. Keep in mind that some models, like the 2.5 ones are thinking models and thus take slightly more time to respond (cf. thinking notebook for more details and in particular learn how to switch the thiking off).

const tslab = require("tslab") as typeof import("tslab");

const MODEL_ID = "gemini-2.5-flash-preview-05-20";

Set your constrained output in the prompt

For this first example just describe the schema you want back in the prompt:

const json_prompt = `
  List a few popular cookie recipes using this JSON schema:

  Recipe = {'recipe_name': str}
  Return: list[Recipe]
`;

Then activate JSON mode by specifying resposeMimeType in the config parameter:

const json_prompt_response = await ai.models.generateContent({
  model: MODEL_ID,
  contents: json_prompt,
  config: {
    responseMimeType: "application/json",
  },
});
// Parse the JSON response
console.log("JSON Response");
console.log(JSON.parse(json_prompt_response.text!));
JSON Response
[
  { recipe_name: 'Chocolate Chip Cookies' },
  { recipe_name: 'Oatmeal Raisin Cookies' },
  { recipe_name: 'Peanut Butter Cookies' },
  { recipe_name: 'Sugar Cookies' },
  { recipe_name: 'Snickerdoodles' }
]

Supply the schema to the model directly

The newest models (1.5 and beyond) allow you to pass a Schema object directly and the output will strictly follow that schema.

Following the same example as the previous section, here’s that recipe type:

import { Schema, Type } from "@google/genai";

const recipeSchema: Schema = {
  type: Type.OBJECT,
  description: "A recipe object",
  properties: {
    recipeName: {
      type: Type.STRING,
      description: "The name of the recipe",
    },
    recipeDescription: {
      type: Type.STRING,
      description: "A brief description of the recipe",
    },
    recipeIngredients: {
      type: Type.ARRAY,
      description: "A list of ingredients for the recipe",
      items: {
        type: Type.STRING,
        description: "An ingredient for the recipe",
      },
    },
  },
  required: ["recipeName", "recipeDescription", "recipeIngredients"],
};

const listRecipesSchema: Schema = {
  type: Type.ARRAY,
  description: "A list of recipes",
  items: recipeSchema,
};

const json_schema_response = await ai.models.generateContent({
  model: MODEL_ID,
  contents:
    "List a few imaginative cookie recipes along with a one-sentence description as if you were a gourmet restaurant and their main ingredients",
  config: {
    responseMimeType: "application/json",
    responseSchema: listRecipesSchema,
  },
});
console.log("JSON Schema Response");
console.log(JSON.parse(json_schema_response.text!));
JSON Schema Response
[
  {
    recipeDescription: 'A celestial delight, these cookies shimmer with edible glitter and a hint of lavender, promising an otherworldly experience with every ethereal bite.',
    recipeIngredients: [
      'All-purpose flour',
      'Unsalted butter',
      'Granulated sugar',
      'Edible glitter',
      'Culinary lavender',
      'Eggs'
    ],
    recipeName: 'Stardust Serenade Cookies'
  },
  {
    recipeDescription: 'Indulge in the opulent depth of these intensely dark chocolate cookies, encasing a molten truffle heart that melts sensuously on the palate.',
    recipeIngredients: [
      'Dark cocoa powder',
      'Unsalted butter',
      'Brown sugar',
      'Granulated sugar',
      'Chocolate truffles',
      'Sea salt'
    ],
    recipeName: 'Velvet Midnight Truffle Cookies'
  },
  {
    recipeDescription: 'These exquisite biscuits offer a harmonious blend of warm spices and tart dried cranberries, evoking a vibrant tapestry of autumnal flavors.',
    recipeIngredients: [
      'All-purpose flour',
      'Unsalted butter',
      'Brown sugar',
      'Cinnamon',
      'Dried cranberries',
      'Orange zest'
    ],
    recipeName: 'Spiced Ruby Blossom Biscuits'
  }
]

Next Steps

Useful API references:

Check the structured ouput documentation or the GenerationConfig API reference for more details

Continue your discovery of the Gemini API

JSON is not the only way to constrain the output of the model, you can also use an Enum, Function calling and Code execution are other ways to enhance your model by either using your own functions or by letting the model write and run them.