> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.labric.co/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.labric.co/_mcp/server.

# Batch Write

POST https://platform.labric.co/api/v1/tools/batch-write
Content-Type: application/json

Write records to multiple tables in a single transaction.

Supports:
- Batch references: Use "_ref" to label records, "@refname" to reference them
- Natural keys: Use human-readable values for foreign keys (e.g., recipe name)
- Automatic FK ordering: Tables are inserted in dependency order
- Upsert mode: Update existing records based on match columns
- Dry run: Validate without committing changes

Committed writes are recorded against a job execution (created automatically
if not supplied) and the job_execution_id is returned, so the write can be
reverted as a unit.

Reference: https://docs.labric.co/api-reference/labric-api/tools/batch-write

## OpenAPI Specification

```yaml
openapi: 3.1.0
info:
  title: openapi-tools
  version: 1.0.0
paths:
  /api/v1/tools/batch-write:
    post:
      operationId: batch_write
      summary: Batch Write
      description: >-
        Write records to multiple tables in a single transaction.


        Supports:

        - Batch references: Use "_ref" to label records, "@refname" to reference
        them

        - Natural keys: Use human-readable values for foreign keys (e.g., recipe
        name)

        - Automatic FK ordering: Tables are inserted in dependency order

        - Upsert mode: Update existing records based on match columns

        - Dry run: Validate without committing changes


        Committed writes are recorded against a job execution (created
        automatically

        if not supplied) and the job_execution_id is returned, so the write can
        be

        reverted as a unit.
      tags:
        - tools
      parameters:
        - name: Authorization
          in: header
          description: Bearer authentication
          required: true
          schema:
            type: string
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BatchWriteResponse'
        '400':
          description: Bad Request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorSchema'
        '401':
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorSchema'
        '403':
          description: Forbidden
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorSchema'
        '404':
          description: Not Found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorSchema'
        '422':
          description: Unprocessable Content
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ValidationErrorSchema'
        '500':
          description: Internal Server Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorSchema'
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/BatchWriteRequest'
servers:
  - url: https://platform.labric.co
    description: https://platform.labric.co
components:
  schemas:
    BatchWriteOptionsMode:
      type: string
      enum:
        - insert
        - upsert
      default: insert
      description: >-
        'insert' creates new records, and fails if the record already exists.
        'upsert' creates or updates based on match_on columns.
      title: BatchWriteOptionsMode
    BatchWriteOptions:
      type: object
      properties:
        mode:
          $ref: '#/components/schemas/BatchWriteOptionsMode'
          default: insert
          description: >-
            'insert' creates new records, and fails if the record already
            exists. 'upsert' creates or updates based on match_on columns.
        match_on:
          type:
            - object
            - 'null'
          additionalProperties:
            type: array
            items:
              type: string
          description: >-
            For upsert: which columns to match on, per table. Example:
            {"production_run": ["run_code"]}
        dry_run:
          type: boolean
          default: false
          description: If True, validate without committing changes.
        return_records:
          type: boolean
          default: false
          description: If True, include created/updated records in response.
        job_execution_id:
          type:
            - string
            - 'null'
          format: uuid
          description: >-
            Existing job execution to attach this write to. If omitted, a new
            one is created and returned, so the write can be reverted as a unit.
        job_name:
          type:
            - string
            - 'null'
          description: >-
            Name for the auto-created job. Defaults to 'Off-Platform Manual
            Job'.
      description: Options for controlling batch write behavior.
      title: BatchWriteOptions
    BatchWriteRequest:
      type: object
      properties:
        tables:
          type: object
          additionalProperties:
            type: array
            items:
              type: object
              additionalProperties:
                description: Any type
          description: Map of table_name to list of records to insert.
        options:
          oneOf:
            - $ref: '#/components/schemas/BatchWriteOptions'
            - type: 'null'
          description: Optional write options (mode, match_on, dry_run, return_records).
      required:
        - tables
      description: |-
        Request body for batch write.

        Example:
            {
                "tables": {
                    "production_run": [
                        {"_ref": "run1", "run_code": "RUN-001", "recipe": "croissant"},
                    ],
                    "baked_item": [
                        {"production_run": "@run1", "item_number": 1, "weight": 65.2},
                    ]
                },
                "options": {"mode": "upsert", "match_on": {"production_run": ["run_code"]}}
            }
      title: BatchWriteRequest
    TableSummary:
      type: object
      properties:
        created:
          type: integer
          default: 0
          description: Number of records created.
        updated:
          type: integer
          default: 0
          description: Number of records updated.
      description: Summary of operations for a single table.
      title: TableSummary
    WritePlan:
      type: object
      properties:
        insert_order:
          type: array
          items:
            type: string
          description: Order in which tables will be inserted.
        operations:
          type: array
          items:
            type: object
            additionalProperties:
              description: Any type
          description: Operations that would be performed.
      required:
        - insert_order
        - operations
      description: Execution plan returned by dry_run.
      title: WritePlan
    BatchWriteResponse:
      type: object
      properties:
        success:
          type: boolean
          default: true
          description: Whether the operation succeeded.
        job_execution_id:
          type:
            - string
            - 'null'
          description: >-
            The job execution this write was recorded under. Use it to revert
            the write as a unit. Null for dry runs.
        summary:
          type: object
          additionalProperties:
            $ref: '#/components/schemas/TableSummary'
          description: Count of created/updated records per table.
        refs:
          type: object
          additionalProperties:
            type: string
          description: Map of _ref labels to their created IDs.
        records:
          type:
            - object
            - 'null'
          additionalProperties:
            type: array
            items:
              type: object
              additionalProperties:
                description: Any type
          description: Created/updated records (only if return_records=True).
        plan:
          oneOf:
            - $ref: '#/components/schemas/WritePlan'
            - type: 'null'
          description: Execution plan (only if dry_run=True).
      required:
        - summary
        - refs
      description: Response from a successful batch write.
      title: BatchWriteResponse
    ErrorSchema:
      type: object
      properties:
        detail:
          type: string
      required:
        - detail
      title: ErrorSchema
    ValidationErrorSchema:
      type: object
      properties:
        detail:
          type: array
          items:
            type: object
            additionalProperties:
              description: Any type
      required:
        - detail
      description: Shape of Ninja's built-in 422 request-validation error response.
      title: ValidationErrorSchema
  securitySchemes:
    ApiKeyAuth:
      type: http
      scheme: bearer

```

## Examples



**Request**

```json
{}
```

**Response**

```json
{
  "summary": {},
  "refs": {},
  "success": true,
  "job_execution_id": "a3f1c9e2-4b7d-4f3a-9d2e-8b7f6c9a1d2e",
  "records": {},
  "plan": {
    "insert_order": [
      "production_run"
    ],
    "operations": [
      {}
    ]
  }
}
```

**SDK Code**

```python
import requests

url = "https://platform.labric.co/api/v1/tools/batch-write"

payload = {}
headers = {
    "Authorization": "Bearer <api_key>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript
const url = 'https://platform.labric.co/api/v1/tools/batch-write';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <api_key>', 'Content-Type': 'application/json'},
  body: '{}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://platform.labric.co/api/v1/tools/batch-write"

	payload := strings.NewReader("{}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <api_key>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://platform.labric.co/api/v1/tools/batch-write")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <api_key>'
request["Content-Type"] = 'application/json'
request.body = "{}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://platform.labric.co/api/v1/tools/batch-write")
  .header("Authorization", "Bearer <api_key>")
  .header("Content-Type", "application/json")
  .body("{}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://platform.labric.co/api/v1/tools/batch-write', [
  'body' => '{}',
  'headers' => [
    'Authorization' => 'Bearer <api_key>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://platform.labric.co/api/v1/tools/batch-write");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <api_key>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Authorization": "Bearer <api_key>",
  "Content-Type": "application/json"
]
let parameters = [] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://platform.labric.co/api/v1/tools/batch-write")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```