1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
use std::collections::HashMap;
use std::path::Path;
use std::time::{Duration, Instant};
use reqwest::multipart::{Form, Part};
use crate::error::DoclingError;
use crate::models::*;
/// Async HTTP client for Docling Serve.
pub struct DoclingClient {
base_url: String,
api_key: Option<String>,
http: reqwest::Client,
}
impl DoclingClient {
/// Create a new client pointing at the given Docling Serve base URL.
///
/// ```rust
/// use docling_rs::DoclingClient;
/// let client = DoclingClient::new("http://127.0.0.1:5001");
/// ```
pub fn new(base_url: impl Into<String>) -> Self {
let base_url = base_url.into();
let base_url = base_url.trim_end_matches('/').to_string();
Self {
base_url,
api_key: None,
http: reqwest::Client::new(),
}
}
/// Create a new client with API key authentication.
///
/// The key is sent as `Authorization: Bearer <key>` on every request
/// to secured endpoints.
pub fn with_api_key(base_url: impl Into<String>, api_key: impl Into<String>) -> Self {
let base_url = base_url.into();
let base_url = base_url.trim_end_matches('/').to_string();
Self {
base_url,
api_key: Some(api_key.into()),
http: reqwest::Client::new(),
}
}
// ========================================================================
// Internal helpers
// ========================================================================
/// Build a full URL from a path.
fn url(&self, path: &str) -> String {
format!("{}{}", self.base_url, path)
}
/// Apply authorization header if an API key is configured.
fn auth(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
match &self.api_key {
Some(key) => req.bearer_auth(key),
None => req,
}
}
/// Send a request and handle non-success status codes by reading the
/// body and returning a structured `DoclingError::Api`.
async fn handle_response(
&self,
response: reqwest::Response,
) -> Result<reqwest::Response, DoclingError> {
let status = response.status();
if status.is_success() {
Ok(response)
} else {
let status_code = status.as_u16();
let body = response.text().await.unwrap_or_default();
Err(DoclingError::Api { status_code, body })
}
}
/// Poll an async task until it completes, fails, or times out.
///
/// This is the shared implementation used by both [`wait_for_conversion`]
/// and [`wait_for_file_conversion`] to avoid duplicated polling logic.
async fn poll_until_complete(
&self,
task_id: &str,
timeout: Duration,
poll_interval_secs: Option<f64>,
) -> Result<ConvertDocumentResponse, DoclingError> {
let poll_wait = poll_interval_secs.unwrap_or(5.0);
let start = Instant::now();
loop {
if start.elapsed() > timeout {
return Err(DoclingError::Timeout {
task_id: task_id.to_string(),
elapsed_secs: start.elapsed().as_secs_f64(),
});
}
let status = self.poll_task_status(task_id, Some(poll_wait)).await?;
match status.task_status.as_str() {
"SUCCESS" => {
return self.get_task_result(task_id).await;
}
"FAILURE" => {
return Err(DoclingError::TaskFailed {
task_id: task_id.to_string(),
status: "FAILURE".to_string(),
});
}
// PENDING, STARTED, or any other status — keep polling
_ => continue,
}
}
}
// ========================================================================
// Health & Version
// ========================================================================
/// Check if the Docling Serve instance is healthy.
///
/// `GET /health`
pub async fn health(&self) -> Result<HealthCheckResponse, DoclingError> {
let resp = self.http.get(self.url("/health")).send().await?;
let resp = self.handle_response(resp).await?;
let body = resp.json::<HealthCheckResponse>().await?;
Ok(body)
}
/// Get version information from the Docling Serve instance.
///
/// `GET /version`
pub async fn version(&self) -> Result<HashMap<String, serde_json::Value>, DoclingError> {
let resp = self.http.get(self.url("/version")).send().await?;
let resp = self.handle_response(resp).await?;
let body = resp.json::<HashMap<String, serde_json::Value>>().await?;
Ok(body)
}
// ========================================================================
// Synchronous URL conversion
// ========================================================================
/// Convert a document from a URL (synchronous).
///
/// This is the simplest way to convert a document. The call blocks (async)
/// until the conversion is complete and returns the result directly.
///
/// `POST /v1/convert/source`
///
/// # Arguments
/// * `url` — The HTTP URL of the document to convert.
/// * `options` — Optional conversion options. Pass `None` for server defaults.
///
/// # Example
/// ```rust,no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = docling_rs::client::DoclingClient::new("http://127.0.0.1:5001");
/// let result = client
/// .convert_source("https://arxiv.org/pdf/2206.01062", None)
/// .await?;
/// if let Some(md) = &result.document.md_content {
/// println!("{}", md);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn convert_source(
&self,
url: &str,
options: Option<ConvertDocumentsRequestOptions>,
) -> Result<ConvertDocumentResponse, DoclingError> {
let request_body = ConvertDocumentsRequest {
sources: vec![Source::Http {
url: url.to_string(),
headers: None,
}],
options,
target: None, // defaults to InBody
};
let req = self.auth(
self.http
.post(self.url("/v1/convert/source"))
.json(&request_body),
);
let resp = req.send().await?;
let resp = self.handle_response(resp).await?;
let body = resp.json::<ConvertDocumentResponse>().await?;
Ok(body)
}
/// Convert documents from multiple sources (synchronous).
///
/// `POST /v1/convert/source`
///
/// Use this when you need full control over sources, options, and target.
pub async fn convert(
&self,
request: &ConvertDocumentsRequest,
) -> Result<ConvertDocumentResponse, DoclingError> {
let req = self.auth(
self.http
.post(self.url("/v1/convert/source"))
.json(request),
);
let resp = req.send().await?;
let resp = self.handle_response(resp).await?;
let body = resp.json::<ConvertDocumentResponse>().await?;
Ok(body)
}
// ========================================================================
// Async URL conversion
// ========================================================================
/// Submit a document for asynchronous conversion.
///
/// Returns a `TaskStatusResponse` containing the `task_id` which can be
/// used to poll for status and retrieve results.
///
/// `POST /v1/convert/source/async`
pub async fn convert_source_async(
&self,
url: &str,
options: Option<ConvertDocumentsRequestOptions>,
) -> Result<TaskStatusResponse, DoclingError> {
let request_body = ConvertDocumentsRequest {
sources: vec![Source::Http {
url: url.to_string(),
headers: None,
}],
options,
target: None,
};
let req = self.auth(
self.http
.post(self.url("/v1/convert/source/async"))
.json(&request_body),
);
let resp = req.send().await?;
let resp = self.handle_response(resp).await?;
let body = resp.json::<TaskStatusResponse>().await?;
Ok(body)
}
/// Submit a full request for asynchronous conversion.
///
/// `POST /v1/convert/source/async`
pub async fn convert_async(
&self,
request: &ConvertDocumentsRequest,
) -> Result<TaskStatusResponse, DoclingError> {
let req = self.auth(
self.http
.post(self.url("/v1/convert/source/async"))
.json(request),
);
let resp = req.send().await?;
let resp = self.handle_response(resp).await?;
let body = resp.json::<TaskStatusResponse>().await?;
Ok(body)
}
// ========================================================================
// Task polling & result retrieval
// ========================================================================
/// Poll the status of an async task.
///
/// `GET /v1/status/poll/{task_id}?wait=N`
///
/// # Arguments
/// * `task_id` — The task ID from `convert_source_async`.
/// * `wait_secs` — Optional long-poll duration. The server will hold the
/// connection open for up to this many seconds waiting for completion.
/// Pass `None` or `Some(0.0)` for an immediate status check.
pub async fn poll_task_status(
&self,
task_id: &str,
wait_secs: Option<f64>,
) -> Result<TaskStatusResponse, DoclingError> {
let mut url = self.url(&format!("/v1/status/poll/{}", task_id));
if let Some(w) = wait_secs {
url = format!("{}?wait={}", url, w);
}
let req = self.auth(self.http.get(&url));
let resp = req.send().await?;
let resp = self.handle_response(resp).await?;
let body = resp.json::<TaskStatusResponse>().await?;
Ok(body)
}
/// Retrieve the result of a completed async task.
///
/// `GET /v1/result/{task_id}`
///
/// This should only be called after `poll_task_status` indicates the
/// task has completed (status = "SUCCESS").
pub async fn get_task_result(
&self,
task_id: &str,
) -> Result<ConvertDocumentResponse, DoclingError> {
let req = self.auth(
self.http
.get(self.url(&format!("/v1/result/{}", task_id))),
);
let resp = req.send().await?;
let resp = self.handle_response(resp).await?;
let body = resp.json::<ConvertDocumentResponse>().await?;
Ok(body)
}
// ========================================================================
// Convenience: submit URL + wait
// ========================================================================
/// Submit an async conversion and wait for it to complete.
///
/// This is a convenience method that combines `convert_source_async`,
/// polling via `poll_task_status`, and `get_task_result` into a single
/// call. The method polls using server-side long-polling for efficiency.
///
/// # Arguments
/// * `url` — The HTTP URL of the document to convert.
/// * `options` — Optional conversion options.
/// * `timeout` — Maximum time to wait for completion.
/// * `poll_interval_secs` — Server-side long-poll wait time per request.
/// Defaults to 5 seconds if `None`.
///
/// # Example
/// ```rust,no_run
/// # use std::time::Duration;
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = docling_rs::client::DoclingClient::new("http://127.0.0.1:5001");
/// let result = client
/// .wait_for_conversion(
/// "https://arxiv.org/pdf/2206.01062",
/// None,
/// Duration::from_secs(300),
/// None,
/// )
/// .await?;
/// println!("Status: {:?}", result.status);
/// # Ok(())
/// # }
/// ```
pub async fn wait_for_conversion(
&self,
url: &str,
options: Option<ConvertDocumentsRequestOptions>,
timeout: Duration,
poll_interval_secs: Option<f64>,
) -> Result<ConvertDocumentResponse, DoclingError> {
let task = self.convert_source_async(url, options).await?;
self.poll_until_complete(&task.task_id, timeout, poll_interval_secs)
.await
}
// ========================================================================
// Multipart file upload
// ========================================================================
/// Build a `multipart/form-data` form from file paths and conversion options.
///
/// Each file is read from disk and attached as a binary part named `files`.
/// Each conversion option (if set) is added as a text form field using the
/// same field names as the OpenAPI spec. Array fields (e.g. `from_formats`,
/// `to_formats`, `ocr_lang`) are sent as repeated form fields, which is how
/// FastAPI parses multipart list parameters.
async fn build_file_multipart(
&self,
file_paths: &[impl AsRef<Path>],
options: Option<&ConvertDocumentsRequestOptions>,
target_type: Option<&TargetName>,
) -> Result<Form, DoclingError> {
let mut form = Form::new();
// Attach each file as a binary part
for path in file_paths {
let path = path.as_ref();
let bytes = tokio::fs::read(path).await.map_err(DoclingError::Io)?;
let filename = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| "file".to_string());
// Guess MIME type from extension
let mime = match path.extension().and_then(|e| e.to_str()) {
Some("pdf") => "application/pdf",
Some("docx") => {
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
}
Some("pptx") => {
"application/vnd.openxmlformats-officedocument.presentationml.presentation"
}
Some("xlsx") => {
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
}
Some("html") | Some("htm") => "text/html",
Some("md") => "text/markdown",
Some("csv") => "text/csv",
Some("json") => "application/json",
Some("xml") => "application/xml",
Some("png") => "image/png",
Some("jpg") | Some("jpeg") => "image/jpeg",
Some("tiff") | Some("tif") => "image/tiff",
Some("bmp") => "image/bmp",
Some("webp") => "image/webp",
Some("mp3") => "audio/mpeg",
Some("wav") => "audio/wav",
Some("vtt") => "text/vtt",
_ => "application/octet-stream",
};
let part = Part::bytes(bytes)
.file_name(filename)
.mime_str(mime)
.unwrap();
form = form.part("files", part);
}
// Add target_type
if let Some(tt) = target_type {
form = form.text("target_type", tt.to_string());
}
// Add options as flat form fields
if let Some(opts) = options {
// Array fields — sent as repeated form fields for FastAPI
if let Some(ref fmts) = opts.from_formats {
for fmt in fmts {
form = form.text("from_formats", fmt.to_string());
}
}
if let Some(ref fmts) = opts.to_formats {
for fmt in fmts {
form = form.text("to_formats", fmt.to_string());
}
}
if let Some(ref langs) = opts.ocr_lang {
for lang in langs {
form = form.text("ocr_lang", lang.clone());
}
}
if let Some(ref range) = opts.page_range {
form = form.text("page_range", range.0.to_string());
form = form.text("page_range", range.1.to_string());
}
// Enum fields
if let Some(ref v) = opts.image_export_mode {
form = form.text("image_export_mode", v.to_string());
}
if let Some(ref v) = opts.ocr_engine {
form = form.text("ocr_engine", v.to_string());
}
if let Some(ref v) = opts.pdf_backend {
form = form.text("pdf_backend", v.to_string());
}
if let Some(ref v) = opts.table_mode {
form = form.text("table_mode", v.to_string());
}
if let Some(ref v) = opts.pipeline {
form = form.text("pipeline", v.to_string());
}
if let Some(ref v) = opts.vlm_pipeline_model {
form = form.text("vlm_pipeline_model", v.to_string());
}
// Boolean fields
if let Some(v) = opts.do_ocr {
form = form.text("do_ocr", v.to_string());
}
if let Some(v) = opts.force_ocr {
form = form.text("force_ocr", v.to_string());
}
if let Some(v) = opts.table_cell_matching {
form = form.text("table_cell_matching", v.to_string());
}
if let Some(v) = opts.abort_on_error {
form = form.text("abort_on_error", v.to_string());
}
if let Some(v) = opts.do_table_structure {
form = form.text("do_table_structure", v.to_string());
}
if let Some(v) = opts.include_images {
form = form.text("include_images", v.to_string());
}
if let Some(v) = opts.do_code_enrichment {
form = form.text("do_code_enrichment", v.to_string());
}
if let Some(v) = opts.do_formula_enrichment {
form = form.text("do_formula_enrichment", v.to_string());
}
if let Some(v) = opts.do_picture_classification {
form = form.text("do_picture_classification", v.to_string());
}
if let Some(v) = opts.do_chart_extraction {
form = form.text("do_chart_extraction", v.to_string());
}
if let Some(v) = opts.do_picture_description {
form = form.text("do_picture_description", v.to_string());
}
// Numeric fields
if let Some(v) = opts.document_timeout {
form = form.text("document_timeout", v.to_string());
}
if let Some(v) = opts.images_scale {
form = form.text("images_scale", v.to_string());
}
if let Some(v) = opts.picture_description_area_threshold {
form = form.text("picture_description_area_threshold", v.to_string());
}
// String fields
if let Some(ref v) = opts.md_page_break_placeholder {
form = form.text("md_page_break_placeholder", v.clone());
}
// JSON-encoded object fields (sent as JSON strings in multipart)
if let Some(ref v) = opts.picture_description_local {
form = form.text("picture_description_local", v.to_string());
}
if let Some(ref v) = opts.picture_description_api {
form = form.text("picture_description_api", v.to_string());
}
if let Some(ref v) = opts.vlm_pipeline_model_local {
form = form.text("vlm_pipeline_model_local", v.to_string());
}
if let Some(ref v) = opts.vlm_pipeline_model_api {
form = form.text("vlm_pipeline_model_api", v.to_string());
}
}
Ok(form)
}
/// Convert one or more local files (synchronous).
///
/// Reads each file from disk and uploads via `multipart/form-data`.
/// The call blocks (async) until conversion is complete.
///
/// `POST /v1/convert/file`
///
/// # Arguments
/// * `file_paths` — One or more local file paths to convert.
/// * `options` — Optional conversion options. Pass `None` for server defaults.
/// * `target_type` — Optional target type. Pass `None` for default (in-body).
///
/// # Example
/// ```rust,no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = docling_rs::client::DoclingClient::new("http://127.0.0.1:5001");
/// let result = client
/// .convert_file(&["./document.pdf"], None, None)
/// .await?;
/// if let Some(md) = &result.document.md_content {
/// println!("{}", md);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn convert_file(
&self,
file_paths: &[impl AsRef<Path>],
options: Option<&ConvertDocumentsRequestOptions>,
target_type: Option<&TargetName>,
) -> Result<ConvertDocumentResponse, DoclingError> {
let form = self
.build_file_multipart(file_paths, options, target_type)
.await?;
let req = self.auth(
self.http
.post(self.url("/v1/convert/file"))
.multipart(form),
);
let resp = req.send().await?;
let resp = self.handle_response(resp).await?;
let body = resp.json::<ConvertDocumentResponse>().await?;
Ok(body)
}
/// Submit one or more local files for asynchronous conversion.
///
/// Returns a `TaskStatusResponse` containing the `task_id` which can be
/// used to poll for status and retrieve results.
///
/// `POST /v1/convert/file/async`
///
/// # Arguments
/// * `file_paths` — One or more local file paths to convert.
/// * `options` — Optional conversion options. Pass `None` for server defaults.
/// * `target_type` — Optional target type. Pass `None` for default (in-body).
pub async fn convert_file_async(
&self,
file_paths: &[impl AsRef<Path>],
options: Option<&ConvertDocumentsRequestOptions>,
target_type: Option<&TargetName>,
) -> Result<TaskStatusResponse, DoclingError> {
let form = self
.build_file_multipart(file_paths, options, target_type)
.await?;
let req = self.auth(
self.http
.post(self.url("/v1/convert/file/async"))
.multipart(form),
);
let resp = req.send().await?;
let resp = self.handle_response(resp).await?;
let body = resp.json::<TaskStatusResponse>().await?;
Ok(body)
}
// ========================================================================
// Convenience: submit file + wait
// ========================================================================
/// Submit local files for async conversion and wait for completion.
///
/// Convenience method that combines `convert_file_async`, polling via
/// `poll_task_status`, and `get_task_result` into a single call.
///
/// # Arguments
/// * `file_paths` — One or more local file paths to convert.
/// * `options` — Optional conversion options.
/// * `target_type` — Optional target type. Pass `None` for default (in-body).
/// * `timeout` — Maximum time to wait for completion.
/// * `poll_interval_secs` — Server-side long-poll wait time per request.
/// Defaults to 5 seconds if `None`.
///
/// # Example
/// ```rust,no_run
/// # use std::time::Duration;
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = docling_rs::client::DoclingClient::new("http://127.0.0.1:5001");
/// let result = client
/// .wait_for_file_conversion(
/// &["./document.pdf"],
/// None,
/// None,
/// Duration::from_secs(300),
/// None,
/// )
/// .await?;
/// println!("Status: {:?}", result.status);
/// # Ok(())
/// # }
/// ```
pub async fn wait_for_file_conversion(
&self,
file_paths: &[impl AsRef<Path>],
options: Option<&ConvertDocumentsRequestOptions>,
target_type: Option<&TargetName>,
timeout: Duration,
poll_interval_secs: Option<f64>,
) -> Result<ConvertDocumentResponse, DoclingError> {
let task = self
.convert_file_async(file_paths, options, target_type)
.await?;
self.poll_until_complete(&task.task_id, timeout, poll_interval_secs)
.await
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn url_no_trailing_slash() {
let client = DoclingClient::new("http://localhost:5001");
assert_eq!(client.url("/health"), "http://localhost:5001/health");
}
#[test]
fn url_trailing_slash_stripped() {
let client = DoclingClient::new("http://localhost:5001/");
assert_eq!(client.url("/health"), "http://localhost:5001/health");
}
#[test]
fn url_multiple_trailing_slashes_stripped() {
let client = DoclingClient::new("http://localhost:5001///");
assert_eq!(client.url("/health"), "http://localhost:5001/health");
}
#[test]
fn url_deep_path() {
let client = DoclingClient::new("http://localhost:5001");
assert_eq!(
client.url("/v1/convert/source"),
"http://localhost:5001/v1/convert/source"
);
}
#[test]
fn with_api_key_also_strips_trailing_slash() {
let client = DoclingClient::with_api_key("http://localhost:5001/", "key");
assert_eq!(client.url("/health"), "http://localhost:5001/health");
assert_eq!(client.api_key.as_deref(), Some("key"));
}
}