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

# Create Edit

> Create an edit.

Fills the form fields of a document according to `instructions` and renders
the values into a PDF. Provide exactly one of `document` (a PDF, DOCX, XLSX,
or PPTX) or `template_id` (an existing edit template) — supplying both or
neither responds with `400`. Returns the created edit with the filled form
data and rendered document; responds with `201`.

Automatically detect fillable regions in a document (or reuse a pre-defined template) and apply the values described in `instructions`. Persisted as an `Edit` resource, retrievable via `GET /v1/edits/{edit_id}`.

Either `document` or `template_id` must be provided; they are mutually exclusive.

<RequestExample>
  ```python Python theme={null}
  from retab import MIMEData, Retab

  client = Retab()

  document = MIMEData(
      filename="form.pdf",
      url="https://my-bucket.s3.us-east-1.amazonaws.com/documents/form.pdf",
  )

  edit = client.edits.create(
      instructions="Name: John Doe, Date of Birth: 1990-01-15, Address: 123 Main Street",
      document=document,
      model="retab-small",
  )

  print(f"Edit ID: {edit.id}")
  for field in edit.output.form_data:
      print(f"{field.key} = {field.value}")

  # Save the filled PDF
  import base64
  with open("filled_form.pdf", "wb") as f:
      f.write(base64.b64decode(edit.output.filled_document.url.split(",", 1)[1]))
  ```

  ```typescript TypeScript theme={null}
  import { Retab } from "@retab/node";

  const client = new Retab({ apiKey: process.env.RETAB_API_KEY });

  const document = {
    filename: "form.pdf",
    url: "https://my-bucket.s3.us-east-1.amazonaws.com/documents/form.pdf",
  };

  const edit = await client.edits.create("Name: John Doe, Date of Birth: 1990-01-15", document, undefined, "retab-small");

  console.log(`Edit ID: ${edit.id}`);
  ```

  ```go Go theme={null}
  package main

  import (
  	"context"
  	"fmt"
  	"log"

  	retab "github.com/retab-dev/retab/clients/go"
  )

  func ptr[T any](v T) *T { return &v }

  func main() {
  	ctx := context.Background()

  	client, err := retab.NewClient("")
  	if err != nil {
  		log.Fatal(err)
  	}

  	document := retab.MIMEData{
  		Filename: "form.pdf",
  		URL:      "https://my-bucket.s3.us-east-1.amazonaws.com/documents/form.pdf",
  	}

  	edit, err := client.Edits.Create(ctx, &retab.EditsCreateParams{
  		Instructions: "Name: John Doe, Date of Birth: 1990-01-15",
  		Document:     document,
  		Model:        ptr("retab-small"),
  	})
  	if err != nil {
  		log.Fatal(err)
  	}

  	fmt.Printf("Edit ID: %s\n", edit.ID)
  }
  ```

  ```ruby Ruby theme={null}
  require 'retab'

  client = Retab::Client.new(api_key: ENV['RETAB_API_KEY'])

  document = {
    filename: 'form.pdf',
    url: 'https://my-bucket.s3.us-east-1.amazonaws.com/documents/form.pdf',
  }

  edit = client.edits.create(
    instructions: 'Name: John Doe, Date of Birth: 1990-01-15, Address: 123 Main Street',
    document: document,
    model: 'retab-small',
  )

  puts "Edit ID: #{edit.id}"
  edit.output.form_data.each do |field|
    puts "#{field.key} = #{field.value}"
  end
  ```

  ```rust Rust theme={null}
  use retab::resources::edits::CreateParams;
  use retab::{MimeData, Retab};

  #[tokio::main]
  async fn main() -> Result<(), Box<dyn std::error::Error>> {
      let client = Retab::new(std::env::var("RETAB_API_KEY")?);

      let document = MimeData::new(
          "form.pdf",
          "https://my-bucket.s3.us-east-1.amazonaws.com/documents/form.pdf",
      );
      let mut params = CreateParams::new("Name: John Doe, Date of Birth: 1990-01-15");
      params.body.document = Some(document);
      params.body.model = Some("retab-small".into());

      let edit = client.edits().create(params).await?;

      println!("Edit ID: {}", edit.id);
      for field in &edit.output.as_ref().unwrap().form_data {
          println!("{} = {}", field.key, field.value.as_deref().unwrap_or(""));
      }
      Ok(())
  }
  ```

  ```php PHP theme={null}
  <?php
  require 'vendor/autoload.php';

  use Retab\Client;

  $client = new Client(apiKey: getenv('RETAB_API_KEY'));

  $result = $client->edits()->create(
      instructions: 'value',
  );
  print_r($result);
  ```

  ```csharp C# theme={null}
  using System;
  using System.Collections.Generic;
  using Retab;
  using RetabClient = Retab.Retab;

  var apiKey = Environment.GetEnvironmentVariable("RETAB_API_KEY")!;
  var client = new RetabClient(apiKey);

  var document = MimeData.FromUrl(new Uri("https://my-bucket.s3.us-east-1.amazonaws.com/documents/form.pdf"));

  var result = await client.Edits.CreateAsync(new EditsCreateOptions
  {
      Instructions = "Name: John Doe, Date of Birth: 1990-01-15",
      Document = document,
      Model = "retab-small",
  });
  Console.WriteLine(result);
  ```

  ```java Java theme={null}
  import com.retab.RetabClient;
  import com.retab.models.MimeData;
  import java.net.URI;
  import java.util.List;
  import java.util.Map;

  public final class Example {
    public static void main(String[] args) throws Exception {
      RetabClient client = new RetabClient(System.getenv("RETAB_API_KEY"));

      MimeData document =
          MimeData.fromUrl(URI.create("https://my-bucket.s3.us-east-1.amazonaws.com/documents/form.pdf"));

      var result =
          client
              .edits()
              .create(
                  "Name: John Doe, Date of Birth: 1990-01-15",
                  document,
                  null,
                  "retab-small",
                  null,
                  null,
                  null);
      System.out.println(result);
    }
  }
  ```

  ```curl cURL theme={null}
  # Option 1: with a document
  curl -X POST \
    'https://api.retab.com/v1/edits' \
    -H "Authorization: Bearer $RETAB_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "instructions": "Name: John Doe, Date of Birth: 1990-01-15",
    "document": {
      "filename": "form.pdf",
      "url": "https://my-bucket.s3.us-east-1.amazonaws.com/documents/form.pdf"
    },
    "model": "retab-small"
  }'

  # Option 2: with a template_id
  curl -X POST \
    'https://api.retab.com/v1/edits' \
    -H "Authorization: Bearer $RETAB_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "instructions": "Name: John Doe",
    "template_id": "edittplt_abc123",
    "model": "retab-small"
  }'
  ```
</RequestExample>

<ResponseExample>
  ```json 200 theme={null}
  {
    "id": "edit_01G34H8J2K",
    "file": {
      "id": "file_6dd6eb00688ad8d1",
      "filename": "form.pdf",
      "mime_type": "application/pdf"
    },
    "model": "retab-small",
    "instructions": "Name: John Doe, Date of Birth: 1990-01-15",
    "template_id": null,
    "config": { "color": "#000080" },
    "output": {
      "form_data": [
        {
          "key": "full_name",
          "description": "Full Name",
          "type": "text",
          "value": "John Doe",
          "bbox": {
            "left": 0.15,
            "top": 0.2,
            "width": 0.35,
            "height": 0.03,
            "page": 1
          }
        }
      ],
      "filled_document": {
        "filename": "form_filled.pdf",
        "url": "data:application/pdf;base64,JVBERi0xLjQK..."
      }
    },
    "usage": { "page_count": 1, "credits": 1.0 },
    "created_at": "2024-03-15T10:30:00Z"
  }
  ```

  ```json 400 theme={null}
  {
    "detail": "Either document or template_id is required"
  }
  ```
</ResponseExample>


## OpenAPI

````yaml POST /v1/edits
openapi: 3.1.0
info:
  title: FastAPI
  version: 0.1.0
servers:
  - url: https://api.retab.com
security: []
paths:
  /v1/edits:
    post:
      tags:
        - Edits
      summary: Create Edit
      description: >-
        Create an edit.


        Fills the form fields of a document according to `instructions` and
        renders

        the values into a PDF. Provide exactly one of `document` (a PDF, DOCX,
        XLSX,

        or PPTX) or `template_id` (an existing edit template) — supplying both
        or

        neither responds with `400`. Returns the created edit with the filled
        form

        data and rendered document; responds with `201`.
      operationId: create_edit
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateEditRequest'
        required: true
      responses:
        '201':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Edit'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
      security:
        - HTTPBearer: []
components:
  schemas:
    CreateEditRequest:
      properties:
        instructions:
          type: string
          title: Instructions
          description: Instructions describing how to fill the form fields.
        document:
          anyOf:
            - $ref: '#/components/schemas/MIMEData'
            - type: 'null'
          title: Document
          description: >-
            Input document (PDF, DOCX, XLSX, or PPTX). Mutually exclusive with
            template_id.
        template_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Template Id
          description: >-
            EditTemplate id to fill. When provided, uses the template's
            pre-defined form fields and empty PDF. Mutually exclusive with
            document.
        model:
          type: string
          title: Model
          description: The model to use for edit inference.
          default: retab-small
        config:
          $ref: '#/components/schemas/EditConfig'
          description: Edit configuration (rendering options).
          default:
            color: '#000080'
        bust_cache:
          type: boolean
          title: Bust Cache
          description: If true, skip the LLM cache and force a fresh completion.
          default: false
        background:
          type: boolean
          title: Background
          description: >-
            If true, run asynchronously: returns immediately with status
            'queued' and an empty output. Poll GET /v1/<primitive>/{id} until
            status is terminal. Mutually exclusive with stream.
          default: false
      type: object
      required:
        - instructions
      title: CreateEditRequest
      description: Public create-edit request body.
    Edit:
      properties:
        id:
          type: string
          title: Id
          description: Unique identifier of the edit.
        file:
          $ref: '#/components/schemas/FileRef'
          description: Information about the source file (input document or template PDF).
        model:
          type: string
          title: Model
          description: Model used for the edit operation.
        instructions:
          anyOf:
            - type: string
            - type: 'null'
          title: Instructions
          description: Free-form instructions supplied with the edit request.
        config:
          $ref: '#/components/schemas/EditConfig'
          description: Configuration used for the edit operation.
        template_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Template Id
          description: >-
            Template id used when the edit was created from a template; null for
            direct-document edits.
        output:
          $ref: '#/components/schemas/EditResult'
          description: >-
            The edit result: filled form fields and the rendered PDF. An empty
            sentinel until status == 'completed'; gate reads on status.
        status:
          type: string
          enum:
            - pending
            - queued
            - in_progress
            - completed
            - failed
            - cancelled
          title: Status
          description: >-
            Lifecycle status. The synchronous path returns 'completed'.
            Background runs progress pending -> queued -> in_progress ->
            completed | failed | cancelled.
          default: pending
        error:
          anyOf:
            - $ref: '#/components/schemas/PrimitiveError'
            - type: 'null'
          description: >-
            Error details when a background run fails; null otherwise. Always
            present so consumers can read it without an existence check.
        filled_document_ref:
          anyOf:
            - $ref: '#/components/schemas/FileRef'
            - type: 'null'
          description: Durable file reference for the filled document, when materialized.
        usage:
          anyOf:
            - $ref: '#/components/schemas/RetabUsage'
            - type: 'null'
          description: Usage information for the edit operation.
        created_at:
          anyOf:
            - type: string
              format: date-time
            - type: 'null'
          title: Created At
      type: object
      required:
        - config
        - file
        - id
        - model
      title: Edit
      description: >-
        An edit result: form-field values written onto a document or template
        PDF.
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
          default: []
      type: object
      title: HTTPValidationError
    MIMEData:
      properties:
        filename:
          type: string
          title: Filename
          description: The filename of the file
          examples:
            - file.pdf
            - image.png
            - data.txt
        url:
          type: string
          title: Url
          description: The URL of the file in base64 format
          examples:
            - data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA...
      additionalProperties: false
      type: object
      required:
        - filename
        - url
      title: MIMEData
      description: A file represented by its `filename` and a base64 data `url`.
    EditConfig:
      properties:
        color:
          anyOf:
            - type: string
            - type: 'null'
          title: Color
          description: Hex code of the color to use for the filled text.
          default: '#000080'
      type: object
      title: EditConfig
    FileRef:
      properties:
        id:
          type: string
          title: Id
          description: ID of the file
        filename:
          type: string
          title: Filename
          description: Filename of the file
        mime_type:
          type: string
          title: Mime Type
          description: MIME type of the file
      type: object
      required:
        - filename
        - id
        - mime_type
      title: FileRef
      description: Public/shared file reference used across SDK and customer-facing APIs.
    EditResult:
      properties:
        form_data:
          items:
            $ref: '#/components/schemas/FormField'
          type: array
          title: Form Data
          description: Filled form fields (positions, descriptions, and filled values).
        filled_document:
          $ref: '#/components/schemas/MIMEData'
          description: PDF with the filled form values rendered in.
      type: object
      required:
        - filled_document
        - form_data
      title: EditResult
    PrimitiveError:
      properties:
        code:
          type: string
          title: Code
          description: Machine-readable error code.
        message:
          type: string
          title: Message
          description: Human-readable error message.
        details:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Details
          description: Optional structured error context.
      type: object
      required:
        - code
        - message
      title: PrimitiveError
    RetabUsage:
      properties:
        credits:
          type: number
          title: Credits
          description: Credits consumed for processing
      type: object
      required:
        - credits
      title: RetabUsage
      description: Usage information for document processing.
    ValidationError:
      properties:
        loc:
          items:
            anyOf:
              - type: string
              - type: integer
          type: array
          title: Location
        msg:
          type: string
          title: Message
        type:
          type: string
          title: Error Type
        input:
          title: Input
          default: null
        ctx:
          type: object
          title: Context
          default: {}
      type: object
      required:
        - loc
        - msg
        - type
      title: ValidationError
    FormField:
      properties:
        bbox:
          $ref: '#/components/schemas/BBox'
          description: Position and size of this field on the page.
        description:
          type: string
          title: Description
          description: >-
            Human-readable description of the field, including label and
            instructions.
        type:
          $ref: '#/components/schemas/FieldType'
          description: 'Type of field. Currently supported: ''text'' and ''checkbox''.'
        key:
          type: string
          title: Key
          description: Stable key identifying the field in the form data.
        value:
          anyOf:
            - type: string
            - type: 'null'
          title: Value
          description: Filled value of the field as text. Null when no filled value is set.
      type: object
      required:
        - bbox
        - description
        - key
        - type
      title: FormField
    BBox:
      properties:
        left:
          type: number
          title: Left
          description: >-
            Left coordinate of the bounding box, relative to page width (0.0 =
            left edge, 1.0 = right edge).
        top:
          type: number
          title: Top
          description: >-
            Top coordinate of the bounding box, relative to page height (0.0 =
            top edge, 1.0 = bottom edge).
        width:
          type: number
          title: Width
          description: Width of the bounding box, relative to page width (0.0–1.0).
        height:
          type: number
          title: Height
          description: Height of the bounding box, relative to page height (0.0–1.0).
        page:
          type: integer
          title: Page
          description: 1-based index of the page where this field appears.
      type: object
      required:
        - height
        - left
        - page
        - top
        - width
      title: BBox
    FieldType:
      type: string
      enum:
        - text
        - checkbox
      title: FieldType
  securitySchemes:
    HTTPBearer:
      type: http
      scheme: bearer

````