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

# Upload a knowledge document

POST https://api.rasen.ai/v1/knowledge/sources/upload
Content-Type: multipart/form-data

Multipart upload starts ingestion. Maximum 20 MiB. PDF, plain text, Markdown or DOCX only; uploaded content is not automatically verified truth. Explicit multipart owner fields are required. Agent-owned upload adds to the owner agent library and changes its publication ETag. Workspace upload does not attach.

Reference: https://docs.rasen.ai/enterprise/api-reference/knowledge-sources/upload

## Authentication

- `Authorization` header (bearer token, required) — An organisation-owned key whose secret starts ra_org_. The Owner or an Admin of an organisation that Rasen has invited makes it in the app; no API operation makes, changes, rotates or revokes a key. On a workspace operation send the workspace ID in the Rasen-Workspace header; without it the answer is 400 invalid_request with details.field Rasen-Workspace. A workspace outside the organisation or outside the key's workspace list is 404 not_found. An organisation that is not invited gets 403 organisation_api_not_enabled.

## Request

### Headers

- `Idempotency-Key` (string, required) — Stable key per logical intent, 1–255 printable characters. Persist it before sending. Retry the same key/body after an uncertain result for 24 hours. A changed body conflicts. Beyond retention, reconcile the resource before retrying; this is not permanent deduplication. Current authorization is rechecked on replay. Evaluation order: authenticate and check current authorization; look up intent; replay its stored receipt before checking the current revision; only a new intent evaluates If-Match and executes. Fingerprint includes method, path, body and original If-Match. A changed request returns idempotency_key_reused. The server stores only a keyed (HMAC) fingerprint, and no error or response ever returns a fingerprint or hash of a request. In-flight intent returns 409 idempotency_in_progress with Retry-After; retry the same intent after reconciliation. Receipts describe that attempt, not current resource state. A replay returns the original status code and body, with the response header Idempotent-Replayed: true.
- `Rasen-Workspace` (string, required) — The ID of the workspace that this operation acts in. It must be a workspace of the key's organisation and in the key's workspace list. A missing, empty or malformed value is 400 invalid_request with details.field Rasen-Workspace; a workspace outside the organisation or the key's workspace list is the hidden 404 not_found.

### Body (multipart/form-data)

This endpoint expects a multipart form containing a file.

- `name` (string, required)
- `file` (file, required) — Single supported document. Maximum 20 MiB. PDF, plain text, Markdown or DOCX only.
- `owner_type` (enum, required)
- `owner_agent_id` (string, optional) — Opaque agent identifier. Do not parse its contents.
- `resource_key` (string, optional) — Optional caller-chosen resource key: an opaque external identifier that matches your own record (for example a CRM ID, a configuration-file ID or a UUID) to this resource. Rasen still generates the canonical id; use id in paths and references. Case-sensitive, compared exactly, never normalized or parsed. 1-128 characters from A-Z a-z 0-9 . _ : ~ - and starting with a letter or digit; UUIDs and ULIDs are valid. Unique per resource type within one workspace; separate environment workspaces can reuse the same key. Set only at creation and immutable afterwards. A create with a key that already exists returns 409 resource_key_conflict with details.existing_id; it never updates or returns the existing resource. Not an Idempotency-Key: that header identifies one request intent for 24 hours, and a same-intent replay returns its original receipt before the resource-key check runs. Uniqueness includes archived resources. A key becomes free again only after its resource is permanently deleted or erased (a deleted secret or a deleted knowledge source); archive never frees it.

## Response

### 202

Upload a knowledge document.

- `id` (string, required) — Opaque kb identifier. Do not parse its contents.
- `name` (string, required)
- `kind` (string, required) — Open response vocabulary. Preserve unknown values; never assume they mean success.
- `state` (string, required) — pending and ingesting are in progress: keep polling. Settled states: ready (usable: add the source to an agent library and publish the agent), failed (read failure; see failure), archived (hidden from new library selection; retained published evidence keeps working). The API reports a source whose text is available to calls as ready; it no longer returns fallback. Open response vocabulary. Preserve unknown values; never assume they mean success.
- `revision` (string, required)
- `created_at` (datetime, required)
- `failure` (string, required, nullable) — Safe registered reason when state is failed. Null otherwise.
- `content_sha256` (string, required, nullable)
- `content_bytes` (integer, required, nullable)
- `media_type` (string, required, nullable)
- `ingested_at` (datetime, required, nullable)
- `updated_at` (datetime, required)
- `owner` (SourceOwnerRead, required)
- `resource_key` (string, required, nullable) — Optional caller-chosen resource key: an opaque external identifier that matches your own record (for example a CRM ID, a configuration-file ID or a UUID) to this resource. Rasen still generates the canonical id; use id in paths and references. Case-sensitive, compared exactly, never normalized or parsed. 1-128 characters from A-Z a-z 0-9 . _ : ~ - and starting with a letter or digit; UUIDs and ULIDs are valid. Unique per resource type within one workspace; separate environment workspaces can reuse the same key. Set only at creation and immutable afterwards. A create with a key that already exists returns 409 resource_key_conflict with details.existing_id; it never updates or returns the existing resource. Not an Idempotency-Key: that header identifies one request intent for 24 hours, and a same-intent replay returns its original receipt before the resource-key check runs. Uniqueness includes archived resources. A key becomes free again only after its resource is permanently deleted or erased (a deleted secret or a deleted knowledge source); archive never frees it.
- `poll_after_seconds` (integer, required, nullable) — Seconds to wait before the next read while state is pending or ingesting. Null when the state is settled.
- `next_step` (string, optional, nullable) — Present on the response to an add: the action that makes the source usable in calls, for example publishing the agent. Null on other responses.

## Errors

### 400 Bad Request Error

Invalid input or cursor. Correct the request.

- `error` (ErrorResponseError, required) — Only code and message are required. Rasen sends details, request_id and retry on every error, but clients must parse an error that lacks them, so a typed error is never lost to a parsing failure.

### 401 Unauthorized Error

Invalid, expired or revoked API key. Creator departure or membership changes do not invalidate a workspace key.

- `error` (ErrorResponseError, required) — Only code and message are required. Rasen sends details, request_id and retry on every error, but clients must parse an error that lacks them, so a typed error is never lost to a parsing failure.

### 403 Forbidden Error

Operation not allowed by current credential or workspace access.

- `error` (ErrorResponseError, required) — Only code and message are required. Rasen sends details, request_id and retry on every error, but clients must parse an error that lacks them, so a typed error is never lost to a parsing failure.

### 409 Conflict Error

Conflict. Not retryable: read the current state, fix the request and send a new request. The one exception is idempotency_in_progress, which carries Retry-After: wait, then resend the identical request with the same Idempotency-Key. The operation lists its codes in x-error-codes; branch on error.code and, for conflict, error.details.reason.

- `error` (ErrorResponseError, required) — Only code and message are required. Rasen sends details, request_id and retry on every error, but clients must parse an error that lacks them, so a typed error is never lost to a parsing failure.

### 413 Content Too Large Error

Body or upload exceeds its allowed limit.

- `error` (ErrorResponseError, required) — Only code and message are required. Rasen sends details, request_id and retry on every error, but clients must parse an error that lacks them, so a typed error is never lost to a parsing failure.

### 415 Unsupported Media Type Error

Unsupported uploaded media type.

- `error` (ErrorResponseError, required) — Only code and message are required. Rasen sends details, request_id and retry on every error, but clients must parse an error that lacks them, so a typed error is never lost to a parsing failure.

### 429 Too Many Requests Error

Rate limited. Respect Retry-After and retry the same intent where permitted.

- `error` (ErrorResponseError, required) — Only code and message are required. Rasen sends details, request_id and retry on every error, but clients must parse an error that lacks them, so a typed error is never lost to a parsing failure.

### 500 Internal Server Error

Internal error. The effect may have happened. Retry the same request with the same Idempotency-Key; read the resource before creating a new intent. For an operation that takes an Idempotency-Key, a client retry with the same key is safe: the server replays the stored outcome if the first attempt took effect; if the first attempt had no effect, the retry performs the operation once. Never retry with a new key.

- `error` (ErrorResponseError, required) — Only code and message are required. Rasen sends details, request_id and retry on every error, but clients must parse an error that lacks them, so a typed error is never lost to a parsing failure.

### 503 Service Unavailable Error

Service unavailable. Respect Retry-After where present. For an operation that takes an Idempotency-Key, a client retry with the same key is safe: the server replays the stored outcome if the first attempt took effect; if the first attempt had no effect, the retry performs the operation once. Never retry with a new key.

- `error` (ErrorResponseError, required) — Only code and message are required. Rasen sends details, request_id and retry on every error, but clients must parse an error that lacks them, so a typed error is never lost to a parsing failure.

## Types

### SourceOwnerRead

- `type`: `workspace` (workspace)
- `type`: `agent` (agent)
  - `agent_id` (string, required) — Opaque agent identifier. Do not parse its contents.

### ErrorResponseError

Only code and message are required. Rasen sends details, request_id and retry on every error, but clients must parse an error that lacks them, so a typed error is never lost to a parsing failure.

- `code` (string, required) — Stable code. Branch on code (and details.reason for conflict), never on message. Each code has one HTTP status; see components.x-error-catalog.
- `message` (string, required) — Safe description; no provider payload or submitted secrets.
- `details` (map from string to any, optional) — Safe code-specific details. The public fields for each code are listed in components.x-error-catalog. Details never contain a request fingerprint, a hash of a request, secret material or another tenant's data. forbidden may include required_capabilities (a list).
- `request_id` (string, optional) — Same value as the X-Request-Id header. Quote it to support.
- `retry` (string, optional) — Retry class of this code: no (fix the request or state first), yes (retry the same request and the same Idempotency-Key), retry_after (wait for Retry-After, then retry the same request). Open response vocabulary. Preserve unknown values; never assume they mean success.

## Examples

**Request**

```json
{
  "name": "example",
  "file": "<file: <file bytes>>",
  "owner_type": "workspace"
}
```

**Response**

```json
{
  "id": "kb_01j00000000000000000000000",
  "name": "example",
  "kind": "url",
  "state": "pending",
  "revision": "example",
  "created_at": "2026-09-25T10:00:00Z",
  "failure": null,
  "content_sha256": "example",
  "content_bytes": 0,
  "media_type": "example",
  "ingested_at": "2026-09-25T10:02:00Z",
  "updated_at": "2026-09-25T10:06:00Z",
  "owner": {
    "type": "workspace"
  },
  "resource_key": "3f8e5a0c-9d1b-4c7e-a2f4-6b0d9e1c7a55",
  "poll_after_seconds": 1
}
```

**SDK Code**

```python knowledgeSources_upload_example
import requests

url = "https://api.rasen.ai/v1/knowledge/sources/upload"

files = { "file": "open('<file bytes>', 'rb')" }
payload = {
    "name": "example",
    "owner_type": "workspace",
    "owner_agent_id": ,
    "resource_key": 
}
headers = {
    "Idempotency-Key": "intent-appointment-001",
    "Rasen-Workspace": "ws_01j00000000000000000000000",
    "Authorization": "Bearer <token>"
}

response = requests.post(url, data=payload, files=files, headers=headers)

print(response.json())
```

```javascript knowledgeSources_upload_example
const url = 'https://api.rasen.ai/v1/knowledge/sources/upload';
const form = new FormData();
form.append('name', 'example');
form.append('file', '<file bytes>');
form.append('owner_type', 'workspace');
form.append('owner_agent_id', '');
form.append('resource_key', '');

const options = {
  method: 'POST',
  headers: {
    'Idempotency-Key': 'intent-appointment-001',
    'Rasen-Workspace': 'ws_01j00000000000000000000000',
    Authorization: 'Bearer <token>'
  }
};

options.body = form;

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

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

url = URI("https://api.rasen.ai/v1/knowledge/sources/upload")

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

request = Net::HTTP::Post.new(url)
request["Idempotency-Key"] = 'intent-appointment-001'
request["Rasen-Workspace"] = 'ws_01j00000000000000000000000'
request["Authorization"] = 'Bearer <token>'
request.body = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"name\"\r\n\r\nexample\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"; filename=\"<file bytes>\"\r\nContent-Type: application/octet-stream\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"owner_type\"\r\n\r\nworkspace\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"owner_agent_id\"\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"resource_key\"\r\n\r\n\r\n-----011000010111000001101001--\r\n"

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

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

HttpResponse<String> response = Unirest.post("https://api.rasen.ai/v1/knowledge/sources/upload")
  .header("Idempotency-Key", "intent-appointment-001")
  .header("Rasen-Workspace", "ws_01j00000000000000000000000")
  .header("Authorization", "Bearer <token>")
  .body("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"name\"\r\n\r\nexample\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"; filename=\"<file bytes>\"\r\nContent-Type: application/octet-stream\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"owner_type\"\r\n\r\nworkspace\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"owner_agent_id\"\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"resource_key\"\r\n\r\n\r\n-----011000010111000001101001--\r\n")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.rasen.ai/v1/knowledge/sources/upload', [
  'multipart' => [
    [
        'name' => 'name',
        'contents' => 'example'
    ],
    [
        'name' => 'file',
        'filename' => '<file bytes>',
        'contents' => null
    ],
    [
        'name' => 'owner_type',
        'contents' => 'workspace'
    ]
  ]
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Idempotency-Key' => 'intent-appointment-001',
    'Rasen-Workspace' => 'ws_01j00000000000000000000000',
  ],
]);

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

```csharp knowledgeSources_upload_example
using RestSharp;

var client = new RestClient("https://api.rasen.ai/v1/knowledge/sources/upload");
var request = new RestRequest(Method.POST);
request.AddHeader("Idempotency-Key", "intent-appointment-001");
request.AddHeader("Rasen-Workspace", "ws_01j00000000000000000000000");
request.AddHeader("Authorization", "Bearer <token>");
request.AddParameter("undefined", "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"name\"\r\n\r\nexample\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"; filename=\"<file bytes>\"\r\nContent-Type: application/octet-stream\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"owner_type\"\r\n\r\nworkspace\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"owner_agent_id\"\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"resource_key\"\r\n\r\n\r\n-----011000010111000001101001--\r\n", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift knowledgeSources_upload_example
import Foundation

let headers = [
  "Idempotency-Key": "intent-appointment-001",
  "Rasen-Workspace": "ws_01j00000000000000000000000",
  "Authorization": "Bearer <token>"
]
let parameters = [
  [
    "name": "name",
    "value": "example"
  ],
  [
    "name": "file",
    "fileName": "<file bytes>"
  ],
  [
    "name": "owner_type",
    "value": "workspace"
  ],
  [
    "name": "owner_agent_id",
    "value": 
  ],
  [
    "name": "resource_key",
    "value": 
  ]
]

let boundary = "---011000010111000001101001"

var body = ""
var error: NSError? = nil
for param in parameters {
  let paramName = param["name"]!
  body += "--\(boundary)\r\n"
  body += "Content-Disposition:form-data; name=\"\(paramName)\""
  if let filename = param["fileName"] {
    let contentType = param["content-type"]!
    let fileContent = String(contentsOfFile: filename, encoding: String.Encoding.utf8)
    if (error != nil) {
      print(error as Any)
    }
    body += "; filename=\"\(filename)\"\r\n"
    body += "Content-Type: \(contentType)\r\n\r\n"
    body += fileContent
  } else if let paramValue = param["value"] {
    body += "\r\n\r\n\(paramValue)"
  }
}

let request = NSMutableURLRequest(url: NSURL(string: "https://api.rasen.ai/v1/knowledge/sources/upload")! 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()
```