> ## Documentation Index
> Fetch the complete documentation index at: https://docs.genai.scale.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Get a Delivery JSON Schema

> Retrieve a delivery JSON schema by its unique identifier. Delivery JSON schemas define the structure and validation rules for task responses.


> [accordion] Authentication
>
> Every request sent to Scale's API requires authentication. In short, your API Key is the Bearer token. See the [Authentication](https://docs.genai.scale.com/get-started/authentication.md) section for more details.

> [!TIP]
>
> ### Required query parameters
>
> You must provide:
>
> * `schema_id` - Schema IDs are globally unique and used to validate delivery data structures.

## Overview

Retrieves a delivery JSON schema by its unique identifier. Delivery JSON schemas define the structure and validation rules for task responses in customer applications.

### Use Cases

* **Validate delivery data**: Ensure your delivery data conforms to the expected structure
* **Data integration**: Understand the structure of delivery data for integration purposes

### Response

Returns a JSON object containing the complete schema definition including:

* `id` - Unique MongoDB ObjectId identifier for the schema
* `name` - Human-readable name of the schema
* `createdBy` / `updatedBy` - User IDs of creators/updaters
* `createdAt` / `updatedAt` - Timestamps
* `json` - Stringified JSON Schema definition containing validation rules and structure

> [!NOTE]
>
> The `json` field contains a **stringified JSON Schema** that needs to be parsed before use. Parse it with `JSON.parse()` in JavaScript or `json.loads()` in Python.

### Error Responses

* **400 Bad Request**:
  * Missing `schema_id` parameter
  * Malformed `schema_id` (invalid MongoDB ObjectId format)
* **404 Not Found**: Schema with the specified ID does not exist
* **401 Unauthorized**: Invalid or missing authentication token

### Example Code

> [accordion] Retrieve a Schema by ID
>
> ```python theme={null}
> import json
> import requests
>
> API_KEY = 'live_...'
> SCHEMA_ID = '69320cc6425a4bf55273a32b'
>
> def get_schema(schema_id: str):
>     response = requests.get(
>         url="https://api.scale.com/v2/schema",
>         params={"schema_id": schema_id},
>         headers={
>             "Accept": "application/json",
>             "Authorization": f"Bearer {API_KEY}",
>         },
>     )
>
>     if response.status_code == 200:
>         data = response.json()
>         schema_metadata = data['schema']
>
>         # Parse the JSON Schema string
>         json_schema = json.loads(schema_metadata['json'])
>
>         return schema_metadata, json_schema
>     else:
>         print(f"Error: {response.status_code}")
>         print(response.json())
>         return None, None
>
> if __name__ == "__main__":
>     metadata, json_schema = get_schema(SCHEMA_ID)
>     if metadata:
>         print(f"Schema ID: {metadata['id']}")
>         print(f"Schema Name: {metadata['name']}")
>         print(f"Created At: {metadata['createdAt']}")
>         print(f"\nRequired fields: {json_schema.get('required', [])}")
>         print(f"Properties: {list(json_schema.get('properties', {}).keys())}")
> ```
>
> ```javascript theme={null}
> const API_KEY = 'live_...';
> const SCHEMA_ID = '69320cc6425a4bf55273a32b';
>
> async function getSchema(schemaId) {
>   try {
>     const response = await fetch(
>       `https://api.scale.com/v2/schema?schema_id=${schemaId}`,
>       {
>         method: 'GET',
>         headers: {
>           'Accept': 'application/json',
>           'Authorization': `Bearer ${API_KEY}`,
>         },
>       }
>     );
>
>     if (response.ok) {
>       const data = await response.json();
>       const schemaMetadata = data.schema;
>
>       // Parse the JSON Schema string
>       const jsonSchema = JSON.parse(schemaMetadata.json);
>
>       return { metadata: schemaMetadata, jsonSchema };
>     } else {
>       const error = await response.json();
>       console.error(`Error: ${response.status}`, error);
>       return null;
>     }
>   } catch (error) {
>     console.error('Request failed:', error);
>     return null;
>   }
> }
>
> // Usage
> getSchema(SCHEMA_ID).then(result => {
>   if (result) {
>     const { metadata, jsonSchema } = result;
>     console.log('Schema ID:', metadata.id);
>     console.log('Schema Name:', metadata.name);
>     console.log('Created At:', metadata.createdAt);
>     console.log('\nRequired fields:', jsonSchema.required);
>     console.log('Properties:', Object.keys(jsonSchema.properties));
>   }
> });
> ```
>
> ```bash theme={null}
> curl --request GET \
>   --url 'https://api.scale.com/v2/schema?schema_id=69320cc6425a4bf55273a32b' \
>   --header 'Accept: application/json' \
>   --header 'Authorization: Bearer live_...'
> ```

### Validating Data with the Schema

Once you retrieve a schema, you can use it to validate task data:

> [accordion] Validate Task Data Against Schema (Python)
>
> ```python theme={null}
> import json
> import requests
> from jsonschema import validate, ValidationError
>
> API_KEY = 'live_...'
> SCHEMA_ID = '69320cc6425a4bf55273a32b'
>
> # Get the schema
> response = requests.get(
>     url="https://api.scale.com/v2/schema",
>     params={"schema_id": SCHEMA_ID},
>     headers={
>         "Accept": "application/json",
>         "Authorization": f"Bearer {API_KEY}",
>     },
> )
>
> schema_metadata = response.json()['schema']
> json_schema = json.loads(schema_metadata['json'])
>
> # Example task data to validate
> task_data = {
>     "task_id": "task_123",
>     "project": "my_project",
>     "status": "completed",
>     "created_at": "2025-01-13T10:00:00Z",
>     "batch": "batch_456",
>     "prompt_audio_url": "https://example.com/audio.mp3",
>     "natural_response_url": "https://example.com/response.mp3",
>     "natural_response_transcript": "Hello world",
>     "response_reading_url": "https://example.com/reading.mp3",
>     "metadata": {}
> }
>
> # Validate the data
> try:
>     validate(instance=task_data, schema=json_schema)
>     print("✓ Task data is valid!")
> except ValidationError as e:
>     print(f"✗ Validation failed: {e.message}")
> ```

### Integration with Deliveries

Schemas are referenced in delivery objects and can be used to validate the structure of task responses. When working with deliveries, you can:

1. Retrieve the delivery using `/v2/delivery`
2. Extract the `schema_id` from the delivery metadata
3. Fetch the full schema definition using `/v2/schema`
4. Validate task responses against the schema

> [!NOTE]
>
> Schema IDs are immutable once created. If you need to modify a schema, you must create a new schema version with a new ID.


## OpenAPI

````yaml GET /v2/schema
openapi: 3.1.0
info:
  title: GenAI API Spec
  description: 'Data Engine: Generative AI API Specification'
  version: 0.0.1
servers:
  - url: https://api.scale.com
security:
  - bearerAuth: []
  - basicAuth: []
paths:
  /v2/schema:
    get:
      tags:
        - v2
      summary: Get a Delivery JSON Schema
      description: >
        Retrieve a delivery JSON schema by its unique identifier. Delivery JSON
        schemas define the structure and validation rules for task responses.
      operationId: getSchema
      parameters:
        - $ref: '#/components/parameters/schema_id'
      responses:
        '200':
          description: Delivery JSON schema retrieved successfully.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GetSchemaResponse'
              examples:
                Schema Response:
                  value:
                    schema:
                      id: 69320cc6425a4bf55273a32b
                      name: '[FDE] 69310af9143320c1b09c60bb'
                      createdBy: 68a3b49f35187612f3a28630
                      createdAt: '2025-12-04T22:35:50.549Z'
                      updatedBy: 68a3b49f35187612f3a28630
                      updatedAt: '2025-12-04T22:36:34.221Z'
                      json: >-
                        {"$schema":
                        "https://json-schema.org/draft/2020-12/schema", "type":
                        "object", "required": ["task_id", "project", "status"],
                        "properties": {"task_id": {"type": "string",
                        "minLength": 1}, "project": {"type": "string",
                        "minLength": 1}, "status": {"type": "string",
                        "minLength": 1}}}
        '400':
          description: Bad request - invalid or missing schema_id
          content:
            application/json:
              schema:
                type: object
                properties:
                  status_code:
                    type: number
                    example: 400
                  error:
                    type: string
                    example: schema_id is required
        '404':
          description: Schema not found
          content:
            application/json:
              schema:
                type: object
                properties:
                  status_code:
                    type: number
                    example: 404
                  error:
                    type: string
                    example: Schema not found
        '500':
          description: Internal server error
          content:
            application/json:
              schema:
                type: object
                properties:
                  status_code:
                    type: number
                    example: 500
                  error:
                    type: string
                    example: An error has occurred.
      x-codeSamples:
        - lang: python
          label: Python
          source: |
            import json
            import requests

            API_KEY = 'live_...'
            SCHEMA_ID = '69320cc6425a4bf55273a32b'

            response = requests.get(
                url="https://api.scale.com/v2/schema",
                params={"schema_id": SCHEMA_ID},
                headers={
                    "Accept": "application/json",
                    "Authorization": f"Bearer {API_KEY}",
                },
            )

            if response.status_code == 200:
                data = response.json()
                schema_metadata = data['schema']

                # Parse the JSON Schema string
                json_schema = json.loads(schema_metadata['json'])

                print(f"Schema ID: {schema_metadata['id']}")
                print(f"Schema Name: {schema_metadata['name']}")
                print(f"Required fields: {json_schema.get('required', [])}")
            else:
                print(f"Error: {response.status_code}")
        - lang: javascript
          label: JavaScript
          source: |
            const API_KEY = 'live_...';
            const SCHEMA_ID = '69320cc6425a4bf55273a32b';

            async function getSchema(schemaId) {
              const response = await fetch(
                `https://api.scale.com/v2/schema?schema_id=${schemaId}`,
                {
                  method: 'GET',
                  headers: {
                    'Accept': 'application/json',
                    'Authorization': `Bearer ${API_KEY}`,
                  },
                }
              );

              if (response.ok) {
                const data = await response.json();
                const schemaMetadata = data.schema;

                // Parse the JSON Schema string
                const jsonSchema = JSON.parse(schemaMetadata.json);

                console.log('Schema ID:', schemaMetadata.id);
                console.log('Schema Name:', schemaMetadata.name);
                console.log('Required fields:', jsonSchema.required);
              } else {
                console.error('Error:', response.status);
              }
            }

            getSchema(SCHEMA_ID);
        - lang: bash
          label: cURL
          source: |
            curl --request GET \
              --url 'https://api.scale.com/v2/schema?schema_id=69320cc6425a4bf55273a32b' \
              --header 'Accept: application/json' \
              --header 'Authorization: Bearer live_...'
components:
  parameters:
    schema_id:
      name: schema_id
      in: query
      required: true
      description: The unique MongoDB ObjectId of the delivery JSON schema.
      schema:
        type: string
        example: 507f1f77bcf86cd799439011
  schemas:
    GetSchemaResponse:
      type: object
      required:
        - schema
      properties:
        schema:
          type: object
          description: The delivery JSON schema object
          properties:
            id:
              type: string
              description: Unique MongoDB ObjectId identifier for the schema
              example: 69320cc6425a4bf55273a32b
            name:
              type: string
              description: Human-readable name of the schema
              example: '[FDE] 69310af9143320c1b09c60bb'
            createdBy:
              type: string
              description: User ID of the user who created the schema
              example: 68a3b49f35187612f3a28630
            createdAt:
              type: string
              format: date-time
              description: Timestamp when the schema was created
              example: '2025-12-04T22:35:50.549Z'
            updatedBy:
              type: string
              description: User ID of the user who last updated the schema
              example: 68a3b49f35187612f3a28630
            updatedAt:
              type: string
              format: date-time
              description: Timestamp when the schema was last updated
              example: '2025-12-04T22:36:34.221Z'
            json:
              type: string
              description: >-
                The JSON Schema definition as a stringified JSON containing
                validation rules and structure
              example: >-
                {"$schema": "https://json-schema.org/draft/2020-12/schema",
                "type": "object", "properties": {...}}
  securitySchemes:
    bearerAuth:
      description: >-
        Your API Key is the Bearer token. See the
        [Authentication](/get-started/authentication) section to learn how to
        access your key.
      type: http
      scheme: bearer
    basicAuth:
      description: >-
        Basic HTTP Authentication. Your API Key is your username.  Learn more
        about setting up Authentication [here](/get-started/authentication).
      type: http
      scheme: basic

````