Create Document by Text
Creates a document in a knowledge base from raw text. Indexing runs asynchronously; track it with the returned
batch ID via Get Document Indexing Status.1 min read
post/datasets/{dataset_id}/document/create-by-text
Request example
curl --request POST \
--url https://api.dify.ai/v1/datasets/{dataset_id}/document/create-by-text \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '{
"indexing_technique": "high_quality",
"name": "guide.txt",
"text": "Dify is an open-source LLM application development platform. This guide covers building AI applications with workflows, RAG pipelines, and agents."
}'import requests
url = "https://api.dify.ai/v1/datasets/{dataset_id}/document/create-by-text"
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json",
}
payload = {
"indexing_technique": "high_quality",
"name": "guide.txt",
"text": "Dify is an open-source LLM application development platform. This guide covers building AI applications with workflows, RAG pipelines, and agents."
}
response = requests.request("POST", url, headers=headers, json=payload)
print(response.text)const response = await fetch('https://api.dify.ai/v1/datasets/{dataset_id}/document/create-by-text', {
method: 'POST',
headers: {
'Authorization': 'Bearer <token>',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"indexing_technique": "high_quality",
"name": "guide.txt",
"text": "Dify is an open-source LLM application development platform. This guide covers building AI applications with workflows, RAG pipelines, and agents."
})
});
const data = await response.json();
console.log(data);<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => 'https://api.dify.ai/v1/datasets/{dataset_id}/document/create-by-text',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => '{
"indexing_technique": "high_quality",
"name": "guide.txt",
"text": "Dify is an open-source LLM application development platform. This guide covers building AI applications with workflows, RAG pipelines, and agents."
}',
CURLOPT_HTTPHEADER => [
'Authorization: Bearer <token>',
'Content-Type: application/json',
],
]);
$response = curl_exec($curl);
curl_close($curl);
echo $response;package main
import (
"fmt"
"io"
"net/http"
"strings"
)
func main() {
url := "https://api.dify.ai/v1/datasets/{dataset_id}/document/create-by-text"
payload := strings.NewReader("{\n \"indexing_technique\": \"high_quality\",\n \"name\": \"guide.txt\",\n \"text\": \"Dify is an open-source LLM application development platform. This guide covers building AI applications with workflows, RAG pipelines, and agents.\"\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.dify.ai/v1/datasets/{dataset_id}/document/create-by-text"))
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.method("POST", HttpRequest.BodyPublishers.ofString("{\n \"indexing_technique\": \"high_quality\",\n \"name\": \"guide.txt\",\n \"text\": \"Dify is an open-source LLM application development platform. This guide covers building AI applications with workflows, RAG pipelines, and agents.\"\n}"))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());require 'uri'
require 'net/http'
url = URI('https://api.dify.ai/v1/datasets/{dataset_id}/document/create-by-text')
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = url.scheme == 'https'
request = Net::HTTP::Post.new(url)
request['Authorization'] = 'Bearer <token>'
request['Content-Type'] = 'application/json'
request.body = '{
"indexing_technique": "high_quality",
"name": "guide.txt",
"text": "Dify is an open-source LLM application development platform. This guide covers building AI applications with workflows, RAG pipelines, and agents."
}'
response = http.request(request)
puts response.read_bodyResponse
{
"batch": "20250306150245647595",
"document": {
"archived": false,
"created_at": 1741267200,
"created_by": "ad313dd6-ef04-4dd1-a5b0-c0f0b9e2e7e4",
"created_from": "api",
"data_source_detail_dict": {
"upload_file": {
"created_at": 1741267200,
"created_by": "ad313dd6-ef04-4dd1-a5b0-c0f0b9e2e7e4",
"extension": "txt",
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"mime_type": "text/plain",
"name": "guide.txt",
"size": 2048
}
},
"data_source_info": {
"upload_file_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
},
"data_source_type": "upload_file",
"dataset_process_rule_id": "e1f2a3b4-c5d6-7890-ef12-345678901234",
"disabled_at": null,
"disabled_by": null,
"display_status": "indexing",
"doc_form": "text_model",
"doc_metadata": [],
"enabled": true,
"error": null,
"hit_count": 0,
"id": "a8e0e5b5-78c6-4130-a5ce-25feb0e0b4ac",
"indexing_status": "indexing",
"name": "guide.txt",
"need_summary": false,
"position": 1,
"summary_index_status": null,
"tokens": 0,
"word_count": 0
}
}{
"code": "invalid_param",
"message": "indexing_technique is required.",
"status": 400
}{
"code": "provider_not_initialize",
"message": "No valid model provider credentials found. Please go to Settings -> Model Provider to complete your provider credentials.",
"status": 400
}{
"code": "forbidden",
"message": "Dataset api access is not enabled.",
"status": 403
}{
"code": "forbidden",
"message": "The capacity of the vector space has reached the limit of your subscription.",
"status": 403
}{
"code": "forbidden",
"message": "The number of documents has reached the limit of your subscription.",
"status": 403
}{
"code": "forbidden",
"message": "Sorry, you have reached the knowledge base request rate limit of your subscription.",
"status": 403
}{
"code": "forbidden",
"message": "The API key is not authorized to access this knowledge base.",
"status": 403
}{
"code": "not_found",
"message": "Dataset not found.",
"status": 404
}{
"code": "service_unavailable",
"message": "Unable to verify vector space usage right now. Please try again later.",
"status": 503
}post/datasets/{dataset_id}/document/create-by-text
Authorization
Every request authenticates with an API key: Authorization: Bearer {API_KEY}. App endpoints take an app API key; knowledge endpoints take a knowledge base API key (Get Started).
Keep keys server-side; never embed them in client code. Requests with a missing or invalid key fail with HTTP 401 (unauthorized).
Path parameters
Knowledge base ID, from List Knowledge Bases. For a scoped key, copy the ID from the Dify URL.
Body
application/jsontext_model for standard text chunking, hierarchical_model for parent-child chunk structure, qa_model for question-answer pair extraction.Default: "text_model"
Options:
text_modelhierarchical_modelqa_modelEmbedding model provider. Use the
provider field from Get Available Models with model_type=text-embedding.Required when adding the first document to a knowledge base. Subsequent documents inherit the knowledge base's indexing technique if omitted.
high_quality uses embedding models for precise search; economy uses keyword-based indexing.Options:
high_qualityeconomyDocument name.
Original document ID for versioning. Get it from List Documents.
Processing rules for chunking.
Show child attributesHide child attributes
automatic uses built-in rules, custom allows manual configuration, hierarchical enables parent-child chunk structure (use with doc_form: hierarchical_model).Options:
automaticcustomhierarchicalShow child attributesHide child attributes
Show child attributesHide child attributes
Restrict retrieval to chunks whose document metadata matches the given conditions. Conditions are evaluated server-side against document metadata fields.
Show child attributesHide child attributes
List of metadata conditions to evaluate.
Show child attributesHide child attributes
Comparison to apply, by metadata type:
- String or array metadata:
contains,not contains,start with,end with,is,is not,empty,not empty,in,not in - Numeric metadata:
=,≠,>,<,≥,≤ - Time metadata:
before,after
Options:
containsnot containsstart withend withisis notemptynot emptyinnot in=≠><≥≤beforeafterMetadata field name to compare against.
Value to compare against. Type depends on
comparison_operator: string for most string operators, array of strings for in and not in, number for numeric operators, and omitted for empty and not empty.Whether reranking is enabled.
Reranking mode. Required when
reranking_enable is true.Options:
reranking_modelweighted_scoreReranking model configuration.
Show child attributesHide child attributes
Name of the reranking model.
Reranking model provider identifier, formatted as organization/plugin_name/provider_name (e.g. langgenius/cohere/cohere). A bare name like cohere expands to langgenius/<name>/<name> and works only for langgenius-published plugins.
Get valid values from the provider field of Get Available Models with model_type=rerank.
Minimum similarity score for results. Only effective when
score_threshold_enabled is true.Whether score threshold filtering is enabled.
Search method used for retrieval.
Options:
keyword_searchsemantic_searchfull_text_searchhybrid_searchMaximum number of results to return.
Weight configuration for hybrid search.
Show child attributesHide child attributes
Keyword search weight settings.
Show child attributesHide child attributes
Weight assigned to keyword search results.
Semantic search weight settings.
Strategy for balancing semantic and keyword search weights.
Options:
semantic_firstkeyword_firstcustomizedDocument text content.
Responses
application/json
Document created successfully.
Batch ID for tracking indexing progress.
Show child attributesHide child attributes
Whether the document is archived.
Creation timestamp (Unix epoch in seconds).
ID of the user who created the document.
Origin of the document.
api for API creation, web for UI creation.Detailed data source information including file details.
Raw data source information, varies by
data_source_type.How the document was created.
upload_file for file uploads, notion_import for Notion imports.ID of the processing rule applied to this document.
Timestamp when the document was disabled.
null if enabled.ID of the user who disabled the document.
null if enabled.User-facing display status derived from
indexing_status and enabled state.Document chunking mode.
text_model for standard text chunking, hierarchical_model for parent-child structure, qa_model for QA pair extraction.Metadata values assigned to this document.
Whether the document is enabled for retrieval.
Error message if indexing failed.
null when no error.Number of times the document has been matched in retrieval queries.
Unique identifier of the document.
Current indexing status.
waiting for queued, parsing while extracting content, cleaning while removing noise, splitting while chunking, indexing while building vectors, completed when ready, error if failed, paused if manually paused.Document name.
Whether a summary needs to be generated for this document.
Display position of the document in the list.
Status of the summary index for this document.
null if summary indexing is not configured.Total number of tokens in the document.
Total word count of the document.