Testing the Google Gemini API: prompts, JSON output and token usage

Testing an LLM API isn't like testing a normal one: the same prompt can give a different answer each time. What you can test is everything around the text: that the call works, that the output has the shape your code parses, that it stays within your token budget, and that the errors look like you expect. Here's that collection for Google's Gemini API.

Step 1: Key and environment

Create a key in Google AI Studio. For tests, use a separate project with a spending cap.

VariableValue
geminiBasehttps://generativelanguage.googleapis.com/v1beta
geminiKeythe API key, marked as secret
geminiModelthe model you use in production, for example a current Flash model

Use API key auth with header name x-goog-api-key and value {{geminiKey}}. Model names change with new releases, so keep yours in one variable. GET {{geminiBase}}/models lists the ones your key can use.

Step 2: A plain prompt

HTTP
POST {{geminiBase}}/models/{{geminiModel}}:generateContent
Content-Type: application/json

{
  "contents": [{"role": "user", "parts": [{"text": "Reply with one word: the capital of France."}]}],
  "generationConfig": {"temperature": 0, "maxOutputTokens": 20}
}
JavaScript
const r = pm.response.json();
const text = r.candidates[0].content.parts.map((p) => p.text || '').join('');
pm.test('answered', () => pm.expect(text.toLowerCase()).to.include('paris'));
pm.test('finished normally', () => pm.expect(r.candidates[0].finishReason).to.equal('STOP'));

Even with temperature: 0, test loosely: "includes paris", not "equals Paris". finishReason is the important field: MAX_TOKENS means the answer was cut off, and SAFETY means it was blocked.

Step 3: JSON your code can parse

HTTP
POST {{geminiBase}}/models/{{geminiModel}}:generateContent
Content-Type: application/json

{
  "contents": [{"parts": [{"text": "Extract the order from: 'Two large pizzas and a cola to 5 Main St'"}]}],
  "generationConfig": {
    "temperature": 0,
    "responseMimeType": "application/json",
    "responseSchema": {
      "type": "OBJECT",
      "properties": {
        "items": {"type": "ARRAY", "items": {"type": "OBJECT", "properties": {"name": {"type": "STRING"}, "quantity": {"type": "INTEGER"}}, "required": ["name", "quantity"]}},
        "address": {"type": "STRING"}
      },
      "required": ["items", "address"]
    }
  }
}
JavaScript
const out = JSON.parse(pm.response.json().candidates[0].content.parts[0].text);
pm.test('shape matches what the app parses', () => {
  pm.expect(out.items).to.be.an('array').that.is.not.empty;
  out.items.forEach((i) => pm.expect(i.quantity).to.be.a('number'));
  pm.expect(out.address).to.include('Main');
});

The JSON comes back as a string inside parts[0].text, so parse it first. This is the test that pays off: when a model update changes the output format, it fails here instead of in production. A JSON Schema assertion on a saved example works too.

Step 4: Token budget

JavaScript
const u = pm.response.json().usageMetadata;
console.log(`prompt ${u.promptTokenCount}, output ${u.candidatesTokenCount}, total ${u.totalTokenCount}`);
pm.test('stays within the token budget', () => pm.expect(u.totalTokenCount).to.be.below(800));

A prompt template that quietly grows (a longer system instruction, a bigger example) shows up here as a failing budget, before it shows up on the invoice.

Step 5: Errors

Statuserror.statusCause
400INVALID_ARGUMENTa malformed body or schema
403PERMISSION_DENIEDbad key, or the API isn't enabled for the project
404NOT_FOUNDthe model name doesn't exist (often a retired model)
429RESOURCE_EXHAUSTEDover the rate or quota limit

The 404 is the one to watch: when a model version is retired, every call fails at once. Run this collection on a schedule and you'll see it first.