Create Chunks
Create one or more chunks within a document.
1 min read
post/datasets/{dataset_id}/documents/{document_id}/segments
Request example
curl --request POST \
--url https://api.dify.ai/v1/datasets/{dataset_id}/documents/{document_id}/segments \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '{
"segments": [
{
"answer": "<string>",
"attachment_ids": [
"<string>"
],
"content": "<string>",
"keywords": [
"<string>"
]
}
]
}'import requests
url = "https://api.dify.ai/v1/datasets/{dataset_id}/documents/{document_id}/segments"
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json",
}
payload = {
"segments": [
{
"answer": "<string>",
"attachment_ids": [
"<string>"
],
"content": "<string>",
"keywords": [
"<string>"
]
}
]
}
response = requests.request("POST", url, headers=headers, json=payload)
print(response.text)const response = await fetch('https://api.dify.ai/v1/datasets/{dataset_id}/documents/{document_id}/segments', {
method: 'POST',
headers: {
'Authorization': 'Bearer <token>',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"segments": [
{
"answer": "<string>",
"attachment_ids": [
"<string>"
],
"content": "<string>",
"keywords": [
"<string>"
]
}
]
})
});
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}/documents/{document_id}/segments',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => '{
"segments": [
{
"answer": "<string>",
"attachment_ids": [
"<string>"
],
"content": "<string>",
"keywords": [
"<string>"
]
}
]
}',
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}/documents/{document_id}/segments"
payload := strings.NewReader("{\n \"segments\": [\n {\n \"answer\": \"<string>\",\n \"attachment_ids\": [\n \"<string>\"\n ],\n \"content\": \"<string>\",\n \"keywords\": [\n \"<string>\"\n ]\n }\n ]\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}/documents/{document_id}/segments"))
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.method("POST", HttpRequest.BodyPublishers.ofString("{\n \"segments\": [\n {\n \"answer\": \"<string>\",\n \"attachment_ids\": [\n \"<string>\"\n ],\n \"content\": \"<string>\",\n \"keywords\": [\n \"<string>\"\n ]\n }\n ]\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}/documents/{document_id}/segments')
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 = '{
"segments": [
{
"answer": "<string>",
"attachment_ids": [
"<string>"
],
"content": "<string>",
"keywords": [
"<string>"
]
}
]
}'
response = http.request(request)
puts response.read_bodyResponse
{
"data": [
{
"answer": "",
"attachments": [],
"child_chunks": [],
"completed_at": 1741267200,
"content": "Dify is an open-source LLM app development platform.",
"created_at": 1741267200,
"created_by": "ad313dd6-ef04-4dd1-a5b0-c0f0b9e2e7e4",
"disabled_at": null,
"disabled_by": null,
"document_id": "a8e0e5b5-78c6-4130-a5ce-25feb0e0b4ac",
"enabled": true,
"error": null,
"hit_count": 0,
"id": "f3d1c7be-9f3a-40d8-8eb8-3a1ef9c3f2c1",
"index_node_hash": "abc123def456",
"index_node_id": "a1b2c3d4-e5f6-7890-abcd-000000000001",
"indexing_at": 1741267200,
"keywords": [
"dify",
"platform",
"llm"
],
"position": 1,
"sign_content": "",
"status": "completed",
"stopped_at": null,
"summary": null,
"tokens": 12,
"updated_at": 1741267200,
"updated_by": "ad313dd6-ef04-4dd1-a5b0-c0f0b9e2e7e4",
"word_count": 9
}
],
"doc_form": "text_model"
}{
"code": "invalid_param",
"message": "Exceeded maximum segments limit of 1000.",
"status": 400
}{
"code": "provider_not_initialize",
"message": "No Embedding Model available. Please configure a valid provider in the Settings -> Model Provider.",
"status": 400
}{
"error": "1 validation error for SegmentCreatePayload\nsegments.0.content\n String should have at least 1 character [type=string_too_short, input_value='', input_type=str]"
}{
"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": "Sorry, you have reached the knowledge base request rate limit of your subscription.",
"status": 403
}{
"code": "forbidden",
"message": "To unlock this feature and elevate your Dify experience, please upgrade to a paid plan.",
"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": "not_found",
"message": "Document not found.",
"status": 404
}{
"code": "not_found",
"message": "Document is not completed.",
"status": 404
}{
"code": "not_found",
"message": "Document is disabled.",
"status": 404
}{
"code": "service_unavailable",
"message": "Unable to verify vector space usage right now. Please try again later.",
"status": 503
}post/datasets/{dataset_id}/documents/{document_id}/segments
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.
Document ID. Obtain it from List Documents.
Body
application/jsonArray of chunk objects to create.
Items: min 1
Responses
application/json
Chunks created successfully.
List of created chunks.
Show child attributesHide child attributes
Answer content, used in Q&A mode documents.
Files attached to this chunk.
Child chunks belonging to this chunk. Only present for hierarchical mode documents.
Show child attributesHide child attributes
Text content of the child chunk.
Creation timestamp (Unix epoch in seconds).
Unique identifier of the child chunk.
Position of the child chunk within the parent chunk.
ID of the parent chunk this child chunk belongs to.
How the child chunk was created. Child chunks created or updated through the API are always
customized. System-generated child chunks are automatic.Last update timestamp (Unix epoch in seconds).
Word count of the child chunk content.
Timestamp when indexing completed.
null if not yet completed.Text content of the chunk.
Creation timestamp (Unix epoch in seconds).
ID of the user who created the chunk.
Timestamp when the chunk was disabled.
null if enabled.ID of the user who disabled the chunk.
null if enabled.ID of the document this chunk belongs to.
Whether the chunk is enabled for retrieval.
Error message if indexing failed.
null when no error.Number of times this chunk has been matched in retrieval queries.
Unique identifier of the chunk.
Hash of the indexed content, used to detect changes.
ID of the index node in the vector store.
Timestamp when indexing started.
null if not yet started.Keywords associated with this chunk for keyword-based retrieval.
Position of the chunk within the document.
Signed content hash for integrity verification.
Current indexing status of the chunk, e.g.
completed, indexing, error.Timestamp when indexing was stopped.
null if not stopped.AI-generated summary of the chunk content.
null if summary indexing is not enabled.Token count of the chunk content.
Last update timestamp (Unix epoch in seconds).
ID of the user who last updated the chunk.
Word count of the chunk content.
Document chunking mode used by this document.