Skip to content
ajan.io

Docs menu

On this page

Update Attachment in Knowledge Folder

Replace an existing file in a Knowledge base with a new version

Updates an existing file (attachment) in a Knowledge base by replacing it with a new version. The old file is removed and the new file is processed and embedded.

Before You Start

  • API key scope: Requires an API key with the KNOWLEDGE_FOLDER_API scope. The API key itself needs the Editor role on the Knowledge base. See Share Knowledge bases with the API for setup instructions.
  • Knowledge bases: The Knowledge Folder API manages resources that appear as Knowledge bases in the Library.

Base URL

https://api.ajan.io

Request Format

This endpoint accepts multipart/form-data requests with the file attached.

Path Parameters

ParameterTypeRequiredDescription
folderIdstringYesThe ID of the Knowledge base

Form Fields

FieldTypeRequiredDescription
attachmentIdstringYesThe ID of the attachment to update
filefileYesThe new file to upload. See size limits below.
urlstringNoURL shown to users when this file is used in an answer

File size limits depend on the file type: 10 MB for plain text, Markdown, JSON, and VTT files; 30 MB for XML files; and 256 MB for other supported document types. See the supported file types reference for supported formats.

Examples

Update with cURL

bash
curl -X PATCH "https://api.ajan.io/knowledge/{folderId}" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -F "attachmentId=att_abc123def456" \
  -F "file=@/path/to/new-document.pdf"

Update with JavaScript

javascript
const FormData = require("form-data");
const fs = require("fs");
const axios = require("axios");

async function updateAttachment(folderId, attachmentId, filePath) {
  const form = new FormData();
  form.append("attachmentId", attachmentId);
  form.append("file", fs.createReadStream(filePath));

  const response = await axios.patch(
    `https://api.ajan.io/knowledge/${folderId}`,
    form,
    {
      headers: {
        Authorization: "Bearer YOUR_API_KEY",
        ...form.getHeaders(),
      },
    }
  );

  return response.data;
}

// Example usage
try {
  const result = await updateAttachment(
    "folder_abc123",
    "att_xyz789",
    "/path/to/updated-report.pdf"
  );
  console.log("Attachment updated:", result);
} catch (error) {
  console.error("Failed to update:", error.response?.data?.message);
}

Update with Source URL

javascript
const FormData = require("form-data");
const fs = require("fs");
const axios = require("axios");

async function updateAttachmentWithUrl(folderId, attachmentId, filePath, sourceUrl) {
  const form = new FormData();
  form.append("attachmentId", attachmentId);
  form.append("file", fs.createReadStream(filePath));
  form.append("url", sourceUrl);

  const response = await axios.patch(
    `https://api.ajan.io/knowledge/${folderId}`,
    form,
    {
      headers: {
        Authorization: "Bearer YOUR_API_KEY",
        ...form.getHeaders(),
      },
    }
  );

  return response.data;
}

Response Format

Success Response (200 OK)

typescript
{
  status: "success";
  result: {
    id: string;          // Unique attachment ID
    name: string;        // Original filename
    mimeType: string;    // MIME type of the file
    createdAt: string;   // ISO 8601 timestamp
    updatedAt: string;   // ISO 8601 timestamp
    url: string | null;  // Source URL if provided
  };
}

Example Response

json
{
  "status": "success",
  "result": {
    "id": "att_abc123def456",
    "name": "updated-report.pdf",
    "mimeType": "application/pdf",
    "createdAt": "2025-01-15T10:30:00.000Z",
    "updatedAt": "2025-01-20T14:45:00.000Z",
    "url": null
  }
}

File Validation Response (400 Bad Request)

If the replacement file fails validation, the API returns the reason in message:

json
{
  "message": "The file \"updated-report.pdf\" is declared as a PDF but its content does not start with the expected PDF header.",
  "code": "BAD_REQUEST"
}

Error Handling

javascript
try {
  const response = await updateAttachment(folderId, attachmentId, filePath);
} catch (error) {
  if (error.response) {
    console.error(error.response.data.message ?? "Update failed");
  }
}
StatusMeaning
400Invalid request or file validation failure
401Invalid or missing API key
403API key does not have access to the Knowledge base
404Knowledge base or attachment not found
408Upload timed out
413File exceeds the size limit
429Rate limit exceeded
500Unexpected server error
503Storage capacity exceeded

Processing Status

After updating, the new file is processed asynchronously. Use the Retrieve Files endpoint to check processing status. The syncStatus field indicates the current state:

  • UPLOADING - File is being uploaded
  • UPLOADED - File is uploaded and queued for processing
  • EXTRACTING - Text is being extracted from the file
  • EMBEDDING - Embeddings are being generated
  • SYNCED - File is ready for search
  • ACTION_FAILED, EXTRACTION_FAILED, EMBEDDING_FAILED, TIMEOUT - Processing failed

OpenAPI

openapi: 3.0.0
info:
  title: ajan API
  version: 3.0.0
servers:
  - url: https://api.ajan.io
    description: Production
security:
  - bearerAuth: []
paths:
  /knowledge/{folderId}:
    patch:
      summary: Update a file in a knowledge folder
      parameters:
        - name: folderId
          in: path
          required: true
          description: The ID of the knowledge folder
          schema:
            type: string
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              properties:
                file:
                  type: string
                  format: binary
                  description: The new file to upload
                url:
                  type: string
                  description: >-
                    URL that is shown to the user if the file is used in an
                    answer
                attachmentId:
                  type: string
                  description: The ID of the attachment to update
      responses:
        '200':
          description: Attachment updated successfully
        '400':
          description: Invalid request or file validation failed
          content:
            application/json:
              schema:
                oneOf:
                  - type: object
                    additionalProperties: false
                    required:
                      - message
                      - code
                    properties:
                      message:
                        type: string
                        example: >-
                          The file "updated-report.pdf" is declared as a PDF but
                          its content does not start with the expected PDF
                          header.
                      code:
                        type: string
                        enum:
                          - BAD_REQUEST
                  - type: object
                    additionalProperties: false
                    required:
                      - message
                      - errors
                    properties:
                      message:
                        type: string
                        example: Invalid request
                      errors:
                        type: array
                        items:
                          type: object
        '401':
          description: Invalid or missing API key
          content:
            application/json:
              schema:
                type: object
                required:
                  - message
                properties:
                  message:
                    type: string
                    example: The provided API key is invalid.
        '403':
          description: API key does not have access to the knowledge folder
          content:
            application/json:
              schema:
                oneOf:
                  - type: object
                    additionalProperties: false
                    required:
                      - message
                      - code
                    properties:
                      message:
                        type: string
                        example: >-
                          Knowledge folder not shared with this API key. Please
                          share the folder with the API key in the ajan App
                          to upload or update files.
                      code:
                        type: string
                        enum:
                          - FORBIDDEN
                  - type: object
                    additionalProperties: false
                    required:
                      - message
                      - error
                      - details
                    properties:
                      message:
                        type: string
                        example: Insufficient API key permissions.
                      error:
                        type: string
                        enum:
                          - INSUFFICIENT_SCOPES
                      details:
                        type: object
                        required:
                          - required
                          - missing
                        properties:
                          required:
                            type: array
                            items:
                              type: string
                              example: KNOWLEDGE_FOLDER_API
                          missing:
                            type: array
                            items:
                              type: string
                              example: KNOWLEDGE_FOLDER_API
                  - type: object
                    additionalProperties: false
                    required:
                      - message
                    properties:
                      message:
                        type: string
                        example: Forbidden
        '404':
          description: Knowledge folder or attachment not found
          content:
            application/json:
              schema:
                type: object
                required:
                  - message
                  - code
                properties:
                  message:
                    type: string
                    example: >-
                      Attachment with ID '550e8400-e29b-41d4-a716-446655440000'
                      not found in this knowledge folder.
                  code:
                    type: string
                    enum:
                      - NOT_FOUND
        '408':
          description: Upload timed out
          content:
            application/json:
              schema:
                type: object
                required:
                  - message
                  - code
                properties:
                  message:
                    type: string
                    example: >-
                      Upload request timed out. Please try again with a smaller
                      file or check your connection.
                  code:
                    type: string
                    enum:
                      - REQUEST_TIMEOUT
        '413':
          description: File exceeds the size limit
          content:
            application/json:
              schema:
                type: object
                required:
                  - message
                  - code
                properties:
                  message:
                    type: string
                    example: >-
                      File size exceeds the maximum allowed size of 256MB.
                      Please upload a smaller file.
                  code:
                    type: string
                    enum:
                      - PAYLOAD_TOO_LARGE
        '429':
          description: Rate limit exceeded
          content:
            application/json:
              schema:
                type: object
                required:
                  - message
                properties:
                  message:
                    type: string
                    example: >-
                      You have exceeded the maximum number of requests per
                      minute (50)
                  code:
                    type: string
                    enum:
                      - TOO_MANY_REQUESTS
        '500':
          description: Unexpected server error
          content:
            application/json:
              schema:
                type: object
                required:
                  - message
                properties:
                  message:
                    type: string
                    example: Internal server error
        '503':
          description: Storage capacity exceeded
          content:
            application/json:
              schema:
                type: object
                required:
                  - message
                  - code
                properties:
                  message:
                    type: string
                    example: >-
                      Storage capacity exceeded. Please contact your
                      administrator.
                  code:
                    type: string
                    enum:
                      - SERVICE_UNAVAILABLE
      security:
        - bearerAuth: []
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: API Key
      description: API key as Bearer token. Format "Bearer YOUR_API_KEY"