> This page is for APIs.

> Fetch clean Markdown by appending `.md` to any page URL under https://signalwire.com/docs or requesting it with the HTTP header `Accept: text/markdown`. The root index at https://signalwire.com/docs/llms.txt lists the available documentation indexes.

# Create document

POST https://%7BYour_Space_Name%7D.signalwire.com/api/datasphere/documents
Content-Type: application/json

Ingests a document from the supplied URL, applies the selected chunking strategy, and creates its Datasphere record. Use it when adding source material for later semantic retrieval; use [Search documents](/docs/apis/rest/documents/search-documents) after ingestion, or [List documents](/docs/apis/rest/documents/list-documents) to monitor processing status.

#### Permissions

The API token used to authenticate must have the following scope(s) enabled to make a successful request: _DataSphere_.

[Learn more about API scopes](/docs/platform/your-signalwire-api-space).

Reference: https://signalwire.com/docs/apis/rest/documents/create-document

## Authentication

- `Authorization` header (basic auth, required) — SignalWire Basic Authentication using Project ID and API Token. The client sends HTTP requests with the Authorization header containing the word Basic followed by a space and a base64-encoded string of project_id:token. The project ID will be used as the username and the API token as the password. Example: ``` Authorization: Basic base64(project_id:token) ```

## Request

### Body (application/json)

This endpoint expects a Datasphere.DocumentCreateRequest.

- `Datasphere.DocumentCreateRequest`

## Response

### 201

The request has succeeded and a new resource has been created as a result.

- `id` (string, required) — Unique ID of the Document.
- `filename` (string, required) — Name of the Document.
- `status` (enum, required) — Status of the Document.
  - Allowed values: `submitted`, `in_progress`, `completed`, `failed`
- `tags` (list of string, required) — Document tags.
- `chunking_strategy` (enum, required) — Strategy used to chunk the document.
  - Allowed values: `sentence`, `paragraph`, `page`, `sliding`
- `max_sentences_per_chunk` (integer, required, nullable) — Max Sentences per Chunk. Only present when chunking strategy is 'sentence', null otherwise.
- `split_newlines` (boolean, required, nullable) — Split on Newlines. Only present when chunking strategy is 'sentence', null otherwise.
- `overlap_size` (integer, required, nullable) — Overlap Size. Only present when chunking strategy is 'sliding', null otherwise.
- `chunk_size` (integer, required, nullable) — Chunk Size. Only present when chunking strategy is 'sliding', null otherwise.
- `number_of_chunks` (integer, required) — Number of Chunks in the Document.
- `chunks_uri` (string, required) — URI path to the chunks for this document.
- `created_at` (datetime, required) — Document Creation Date.
- `updated_at` (datetime, required) — Document Update Date.

## Errors

### 400 Bad Request Error

The request is invalid.

- `error` (enum, required)
  - Allowed values: `Bad Request`

### 401 Unauthorized Error

Access is unauthorized.

- `error` (enum, required)
  - Allowed values: `Unauthorized`

### 422 Unprocessable Entity Error

The request contains invalid parameters. See errors for details.

- `errors` (list of Types.StatusCodes.RestApiErrorItem, required) — List of validation errors.

### 500 Internal Server Error

An internal server error occurred.

- `error` (enum, required)
  - Allowed values: `Internal Server Error`

## Types

### Datasphere.DocumentCreateSentenceRequest

- `url` (string, required) — URL of the document.
- `chunking_strategy` (enum, optional) — Strategy for chunking the document
  - Allowed values: `sentence`
- `max_sentences_per_chunk` (integer, optional, default: 50) — Maximum number of sentences per chunk.
- `split_newlines` (boolean, optional, default: false) — Whether to split chunks on new lines. **Default value:** `false`
- `tags` (list of string, optional) — Document tags.

### Datasphere.DocumentCreateSlidingRequest

- `url` (string, required) — URL of the document.
- `chunk_size` (integer, optional, default: 50) — Number of words per chunk.
- `chunking_strategy` (enum, optional) — Strategy for chunking the document
  - Allowed values: `sliding`
- `overlap_size` (integer, optional, default: 10) — Amount of overlap between chunks, in number of words.
- `tags` (list of string, optional) — Document tags.

### Datasphere.DocumentCreatePageRequest

- `url` (string, required) — URL of the document.
- `chunking_strategy` (enum, optional) — Strategy for chunking the document
  - Allowed values: `page`
- `tags` (list of string, optional) — Document tags.

### Datasphere.DocumentCreateParagraphRequest

- `url` (string, required) — URL of the document.
- `chunking_strategy` (enum, optional) — Strategy for chunking the document
  - Allowed values: `paragraph`
- `tags` (list of string, optional) — Document tags.

### Types.StatusCodes.RestApiErrorItem

Details about a specific error.

- `type` (string, required) — The category of error.
- `code` (string, required) — A specific error code.
- `message` (string, required) — A description of what caused the error.
- `url` (string, required) — A link to documentation about this error.
- `attribute` (string, optional, nullable) — The request parameter that caused the error, if applicable.

## Examples

**Request**

```json
{
  "url": "https://example.com/document.pdf"
}
```

**Response**

```json
{
  "id": "acaa5c49-be5e-4477-bce0-48f4b23b7720",
  "filename": "player_list.pdf",
  "status": "in_progress",
  "tags": [
    "sports",
    "football",
    "game"
  ],
  "chunking_strategy": "sentence",
  "max_sentences_per_chunk": 80,
  "split_newlines": true,
  "overlap_size": 10,
  "chunk_size": 50,
  "number_of_chunks": 2345,
  "chunks_uri": "/api/rest/datasphere/documents/acaa5c49-be5e-4477-bce0-48f4b23b7720/chunks",
  "created_at": "2024-05-06T12:20-12Z",
  "updated_at": "2024-05-06T12:20-12Z"
}
```

**SDK Code**

```python
import requests

url = "https://{your_space_name}.signalwire.com/api/datasphere/documents"

payload = { "url": "https://example.com/document.pdf" }
headers = {
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers, auth=("<project_id>", "<api_token>"))

print(response.json())
```

```javascript
const url = 'https://{your_space_name}.signalwire.com/api/datasphere/documents';
const credentials = btoa("<project_id>:<api_token>");

const options = {
  method: 'POST',
  headers: {
    Authorization: `Basic ${credentials}`,
    'Content-Type': 'application/json'
  },
  body: '{"url":"https://example.com/document.pdf"}'
};

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

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://{your_space_name}.signalwire.com/api/datasphere/documents"

	payload := strings.NewReader("{\n  \"url\": \"https://example.com/document.pdf\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.SetBasicAuth("<project_id>", "<api_token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

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

url = URI("https://{your_space_name}.signalwire.com/api/datasphere/documents")

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

request = Net::HTTP::Post.new(url)
request.basic_auth("<project_id>", "<api_token>")
request["Content-Type"] = 'application/json'
request.body = "{\n  \"url\": \"https://example.com/document.pdf\"\n}"

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

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

HttpResponse<String> response = Unirest.post("https://{your_space_name}.signalwire.com/api/datasphere/documents")
  .basicAuth("<project_id>", "<api_token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"url\": \"https://example.com/document.pdf\"\n}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://{your_space_name}.signalwire.com/api/datasphere/documents', [
  'body' => '{
  "url": "https://example.com/document.pdf"
}',
  'headers' => [
    'Content-Type' => 'application/json',
  ],
    'auth' => ['<project_id>', '<api_token>'],
]);

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

```csharp
using RestSharp;
using RestSharp.Authenticators;

var client = new RestClient("https://{your_space_name}.signalwire.com/api/datasphere/documents");
client.Authenticator = new HttpBasicAuthenticator("<project_id>", "<api_token>");
var request = new RestRequest(Method.POST);

request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"url\": \"https://example.com/document.pdf\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let credentials = Data("<project_id>:<api_token>".utf8).base64EncodedString()

let headers = [
  "Authorization": "Basic \(credentials)",
  "Content-Type": "application/json"
]
let parameters = ["url": "https://example.com/document.pdf"] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://{your_space_name}.signalwire.com/api/datasphere/documents")! 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()
```