All guides

Get schema-constrained JSON back from OpenRouter

Write a json_schema in a Responses request, fixing fields, required items and extra properties, then extract, parse and validate the text locally.

AINavWritten / Updated Sources checked
On this page

At a glance

When a program consumes model output directly, the risks are missing fields, wrong types and extra commentary. OpenRouter structured outputs let you describe the wanted object with a JSON Schema, but the documentation also warns that support depends on the endpoint and enforcement differs by provider. This guide covers writing the request, extracting the result, adding a local validation pass, and stopping when support is missing or the schema is invalid.

Workflow

  1. Write the schema

    Describe the object with properties, required and additionalProperties.

  2. Send the request

    Responses uses text.format, and Chat Completions uses response_format.

  3. Verify the result

    Extract the text, parse the JSON and validate it against the same schema.

Each stage cites official sources.

Before you start

  • An OpenRouter API key stored in a server-side environment variable and placed in the Authorization header when the request is sent.
  • A model and provider that support structured outputs; check the structured_outputs parameter in the Providers section of the model page.
  • Ability to write a simple JSON Schema, and a way to validate JSON locally.

1. Design the returned object first

List the fields your downstream code really needs, giving each a type and a one-line description. The official best practices suggest clear property descriptions to guide the model. Prefer fewer fields and keep only those that will be used.

2. Write the json_schema format block

In a Responses request, put text.format with type json_schema, then name, strict set to true and schema. Inside schema, use type: object, properties and required listing every required field, and set additionalProperties to false to forbid extras. For Chat Completions (/api/v1/chat/completions), use response_format instead, holding type and a json_schema object.

3. Confirm endpoint support

Structured-output support depends on the endpoint. Providers of the same model can differ, and support can change. Check supported parameters on the model page first. This sample does not configure routing preferences. To restrict routing, consult the official Provider Routing documentation for require_parameters: true and its exact request placement before adding it.

4. Send an authenticated non-streaming request

POST to https://openrouter.ai/api/v1/responses. The headers must carry Authorization: Bearer plus the key read from your server-side environment variable, and Content-Type: application/json. The JSON shown in the example is the request body sent with those headers. It holds model, input and text.format, with stream set to false. Use synthetic input. If the request fails, read the error first: an unsupported model fails with an error, and an invalid schema returns one too. Fix the cause before resending, and do not retry the same request in a loop.

5. Extract the text and parse it

In the response output array, search from the end for the item whose type is message. In its content, find the part whose type is output_text, take its text field, and parse it as JSON. Confirm both levels exist before parsing, and treat a missing one as a failure.

6. Validate again locally

Check the parsed result against the same schema: required fields present, types correct, no extra fields. The documentation says strict enforcement varies by provider, with some guaranteeing conformance and others only treating the schema as a strong hint, so setting strict is not a guarantee. If validation fails, discard the result, log it and do not write it downstream.

7. Add streaming or healing only if needed

For streaming, add stream: true. The model streams valid partial JSON, so parse only after the whole stream ends. For non-streaming requests, the Response Healing plugin can reduce the risk of invalid JSON; see the official documentation for it. The plugin does not apply to streaming requests.

Original example

Exercise goal: turn a synthetic ticket text into fixed fields. Headers: Authorization: Bearer <key read from the environment>; Content-Type: application/json Request body (original sample):

json
{
  "model": "openai/gpt-4o",
  "input": "Ticket text: the printer on floor three cannot connect and needs handling this morning. Classify and summarize.",
  "text": {
    "format": {
      "type": "json_schema",
      "name": "ticket_triage",
      "strict": true,
      "schema": {
        "type": "object",
        "properties": {
          "category": { "type": "string", "description": "Problem category" },
          "urgent": { "type": "boolean", "description": "Needs same-day handling" },
          "summary": { "type": "string", "description": "One-sentence summary" }
        },
        "required": ["category", "urgent", "summary"],
        "additionalProperties": false
      }
    }
  },
  "stream": false
}

The text you expect to extract is a JSON object shaped like this (structure only, not real output): { "category": "hardware", "urgent": true, "summary": "Third-floor printer cannot connect" } Handling: take the output_text of the last message in output, parse it, and check that all three fields exist, urgent is a boolean and nothing else is present. If any check fails, discard and log the result.

Completion checks

  • The headers include Authorization and Content-Type, and the body has type json_schema, with name, strict and schema under text.format (or under response_format.json_schema for Chat Completions).
  • required lists every mandatory field and additionalProperties is false.
  • The parsed object passed local schema validation, not merely JSON parsing.
  • On an unsupported-model or invalid-schema error, the request was stopped and fixed rather than retried automatically.

Limits

  • Structured outputs work only on selected models and are judged per provider endpoint. The documentation says exact compliance is not guaranteed on every endpoint, so local validation is essential.
  • Strict modes may restrict which JSON Schema features you can use; follow the chosen provider's documentation.
  • Response Healing applies to non-streaming requests using json_schema. This guide does not cover its configuration and does not promise it repairs every invalid output.

Verification scope

This guide is based on the official OpenRouter structured outputs documentation. We only read the documentation; we did not test login, SDK installation, product API execution, file upload or generated output. The request body and result in the example are original illustrations, so confirm real model and provider support on the official model page.

Article sources

Original editorial content; official descriptions and checking suggestions are distinguished.

  1. OpenRouter · Official sources
    View details