> ## Documentation Index
> Fetch the complete documentation index at: https://developers.circularo.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 2. Advanced Document Creation

> [!WARNING]
>
> You are viewing the documentation of release 26.1, which is no longer the current one. [Go to the documentation of the current release 26.2](https://developers.circularo.com/).

## Advanced Document Creation

This scenario demonstrates how to create a document in Circularo with additional metadata fields and optional properties. It shows how to first retrieve available metadata definitions and workflow definitions, then use them to create a more customized document.

**Key features:**

* Discover available metadata definitions and workflow definitions
* Create documents with custom metadata fields
* Apply optional document properties during creation
* Upload and use external PDF files as document content

### Prerequisites

Before creating a document, you need:

* A valid authentication token (see the "Authentication & Security" section for details)
* A PDF file to upload as the document content

> [!NOTE]
>
> This scenario builds on the basic document creation process by adding more customization options.

## Step 1 - Retrieve available metadata definitions

Before creating a document, it's useful to retrieve the list of available metadata definitions in your Circularo instance. This helps you understand what document types you can create and what fields they support.

* Metadata definitions specify the structure and fields for different document types
* Each definition includes information about available fields
* The response includes all metadata definitions the authenticated user has access to

> [!NOTE]
>
> Metadata definitions are configured by administrator and may vary between different Circularo instances.

**Endpoint**

```http theme={null}
GET /definitions/documents
```

**Request**

```http theme={null}
GET /definitions/documents?token=mJnDRPWRaWr5mgk0Nj62YiaR6KTWTKvXhAxmfXfHFvdSYhfuaa4EHbtqPLcCOXEO
```

**Response**

```json theme={null}
{
  "results": [
    {
      "name": "d_my_definition",  //Metadata definition name
      "definitionType": [  //Types of documents the definition is for
        "ext"
      ],
      "workflow": "wf_archive",  //Workflow definition available for this metadata definition
      "fields": [
        {
          "name": "documentTitle",
          "required": true,
          "type": "text",
          ...
        },
        {
          "name": "D_MY_DEFINITION_TEXTAREA",
          "required": true,
          "type": "richtext",
          ...
        },
        ...
      ]
    },
    {
      "name": "d_default",
      "definitionType": [
        "ext"
      ],
      "workflow": "wf_archive",
      "fields": [
        {
          "name": "documentTitle",
          "required": true,
          "type": "text",
          ...
        },
        ...
      ],
      ...
    },
    ...
  ]
}
```

The response includes all available metadata definitions that you can use when creating documents.

* Each definition has a unique **name** that serves as its identifier
* The **fields** property lists all available fields for each definition
* The **definitionType** indicates the types of document the definition is for

## Step 2 - Retrieve available workflow definitions

Next, retrieve the list of available workflow definitions in your Circularo instance. Workflows define the lifecycle and processing steps for documents.

* Workflow definitions specify the states a document can go through
* Each workflow includes information about available actions
* The response includes all workflow definitions the authenticated user has access to

> [!NOTE]
>
> Workflow definitions are configured by administrator and determine how documents are processed in your organization.

**Endpoint**

```http theme={null}
GET /definitions/workflows
```

**Request**

```http theme={null}
GET /definitions/workflows?token=mJnDRPWRaWr5mgk0Nj62YiaR6KTWTKvXhAxmfXfHFvdSYhfuaa4EHbtqPLcCOXEO
```

**Response**

```json theme={null}
{
  "results": [
    {
      "name": "wf_archive",  //Workflow definition name
      "states": [
        {
          "stateName": "initialized",
          "stateId": 0,
          ...
        },
        {
          "stateName": "created",
          "stateId": 1,
          ...
        },
        ...
      ],
      "actions": [
        {
          "name": "create",
          "id": 0,
          "stateId": 0,
          "nextState": 1,
          ...
        },
        ...
      ],
      "requests": [],
      ...
    },
    ...
  ]
}
```

The response includes all available workflow definitions that you can apply to documents.

* Each workflow has a unique **name** that serves as its identifier
* The **states** property lists all possible states in the workflow

## Step 3 - Retrieve available document categories

Before creating a document, it's useful to retrieve the list of available document categories in your Circularo instance. Document categories are predefined by organization administrators and help organize documents by type or purpose.

* Document categories are predefined by organization administrators in system settings
* Categories are returned during initial login or can be obtained via the settings endpoint
* This endpoint provides a convenient way to check available categories before document creation

> [!NOTE]
>
> Document categories are also returned during the initial login process when you obtain your session token. This step demonstrates how to retrieve them separately if needed.

**Endpoint**

```http theme={null}
GET /login
```

**Request**

```http theme={null}
GET /login?token=mJnDRPWRaWr5mgk0Nj62YiaR6KTWTKvXhAxmfXfHFvdSYhfuaa4EHbtqPLcCOXEO
```

**Response**

```json theme={null}
{
  "logged": true,
  "isUnlocked": true,
  "settings": {
    "data": {
      "documentCategories": [
        "General",
        ...
      ],
      ...
    },
    ...
  },
  ...
}
```

The response includes user session information and system settings, including available document categories.

* The **settings.data.documentCategories** array contains all available document categories
* These categories can be used when creating documents to properly classify them
* Using predefined categories ensures consistency across your document management system

## Step 4 - Upload a PDF file

Before creating a document, you need to upload the PDF file that will serve as the document content. This step uploads and stores a PDF file in the Circularo system.

* The file is uploaded as a multipart/form-data request
* The response includes the file ID that will be used in the document creation step
* The response also includes storage quota information to help manage available space

> [!NOTE]
>
> The file upload is a separate step from document creation.

**Endpoint**

```http theme={null}
POST /files/saveFile
```

**Request**

```http theme={null}
POST /files/saveFile?token=mJnDRPWRaWr5mgk0Nj62YiaR6KTWTKvXhAxmfXfHFvdSYhfuaa4EHbtqPLcCOXEO

Content-Type: multipart/form-data

{
  "file": "blob",
  "fileName": "My PDF file"
}
```

**Response**

```json theme={null}
{
  "file": {
    "id": "vn9rgTQNvfDGIgueHquHNdbc948F5xBluMJQGted72wMZ77D7dvoMeK4CxffNWzL",
    "documentname": "My PDF file",
    "mimetype": "application/pdf",
    "size": 125840,
    ...
  },
  "storage": {
    "used": 2458732,
    "limit": 10737418240,
    ...
  },
  ...
}
```

The response contains the following important properties:

* **fileId** - Located at `file.id` in the response.
  * Example value: `vn9rgTQNvfDGIgueHquHNdbc948F5xBluMJQGted72wMZ77D7dvoMeK4CxffNWzL`

The PDF file has been successfully uploaded and stored in the system. The response includes the file ID that will be used in the next step to create a document based on this file.

* The **file.id** is the unique identifier for the uploaded file (also referred as "file hash")
* This ID will be used in the document creation step to reference this file
* The storage information shows your current usage and available quota

> [!NOTE]
>
> Store the file ID for use in the next step. This ID is required to create a document based on this file.

## Step 5 - Upload an attachment file

In addition to the main document content, you can upload attachment files that will be associated with the document during creation. This step uploads and stores a file that will be used as an attachment.

* The file is uploaded as a multipart/form-data request
* The attachment can be any file type (PDF, Word, Excel, images, etc.)
* The response includes the file ID that will be used to reference this attachment in the document creation step
* Multiple attachments can be added to a single document

> [!NOTE]
>
> Attachments provide a way to include supporting files with your main document.

**Endpoint**

```http theme={null}
POST /files/saveFile
```

**Request**

```http theme={null}
POST /files/saveFile?token=mJnDRPWRaWr5mgk0Nj62YiaR6KTWTKvXhAxmfXfHFvdSYhfuaa4EHbtqPLcCOXEO

Content-Type: multipart/form-data

{
  "file": "blob",
  "fileName": "Supporting Document"
}
```

**Response**

```json theme={null}
{
  "file": {
    "id": "UCMnLOjqtpmq1xAVaFYisughRcJJF1iyLAlpaL9cp9lw9aODLUWw6xClo0VbbbTE",
    "documentname": "Supporting Document",
    "mimetype": "application/pdf",
    "size": 98765,
    ...
  },
  "storage": {
    "used": 2557497,
    "limit": 10737418240,
    ...
  },
  ...
}
```

The response contains the following important properties:

* **attachmentFileId** - Located at `file.id` in the response.
  * The unique identifier for the uploaded attachment file. Use this ID to reference the attachment when creating the document.
  * Example value: `UCMnLOjqtpmq1xAVaFYisughRcJJF1iyLAlpaL9cp9lw9aODLUWw6xClo0VbbbTE`

The attachment file has been successfully uploaded and stored in the system. The response includes the file ID that will be used in the document creation step to reference this attachment.

* The **file.id** is the unique identifier for the uploaded attachment file
* This ID will be used in the document creation step to reference this attachment
* You can upload multiple attachment files before creating the document

> [!NOTE]
>
> Store the attachment file ID for use in the document creation step. During document creation, you'll include this ID in the attachments array to associate it with the document.

## Step 6 - Create a document with custom metadata field

This endpoint creates a new document in the Circularo system using the previously uploaded PDF file and the metadata definition and workflow definition you selected.

* The **documentType** parameter specifies which metadata definition to use
* The **workflow** parameter defines the workflow that will be applied to the document
* The **definitionType** parameter is set to "ext" to indicate an external file-based document
* The **pdfFile.content** parameter references the file ID from the previous step
* Custom metadata fields are included based on the selected metadata definition
* The **file** array contains attachments to be associated with the document

> [!WARNING]
>
> You must have the appropriate permissions to create documents with the specified metadata definition and workflow.

**Endpoint**

```http theme={null}
POST /documents
```

**Request**

```http theme={null}
POST /documents?token=mJnDRPWRaWr5mgk0Nj62YiaR6KTWTKvXhAxmfXfHFvdSYhfuaa4EHbtqPLcCOXEO

Content-Type: application/json

{
  "body": {
    "documentType": "d_my_definition",
    "documentTitle": "Advanced Document Example",
    "documentCategory": "General",
    "pdfFile": {  //Document main file is always specified in \"pdfFile\" property, no matter the real content type
      "content": "vn9rgTQNvfDGIgueHquHNdbc948F5xBluMJQGted72wMZ77D7dvoMeK4CxffNWzL"
    },
    "file": [  //List of attachments
      {
        "content": "UCMnLOjqtpmq1xAVaFYisughRcJJF1iyLAlpaL9cp9lw9aODLUWw6xClo0VbbbTE"
      }
    ],
    "D_MY_DEFINITION_TEXTAREA": "Custom metadata field value"  //Metadata template specific value
  },
  "definitionType": "ext",
  "workflow": "wf_archive"
}
```

**Response**

```json theme={null}
{
  "results": [
    {
      "documentId": "05565225-504b-43e6-a051-37a389bfa65d",
      "documentTitle": "Advanced Document Example",
      "documentType": "d_my_definition",
      "documentCategory": "General",
      "D_MY_DEFINITION_TEXTAREA": "Custom metadata field value",
      "pdfFile": {
        "content": "vn9rgTQNvfDGIgueHquHNdbc948F5xBluMJQGted72wMZ77D7dvoMeK4CxffNWzL",
        ...
      },
      "attachments": [
        {
          "content": "UCMnLOjqtpmq1xAVaFYisughRcJJF1iyLAlpaL9cp9lw9aODLUWw6xClo0VbbbTE",
          ...
        }
      ],
      "workflow": {
        "workflowType": "wf_archive",
        ...
      },
      ...
    }
  ],
  ...
}
```

The response contains the following important properties:

* **documentId** - Located at `results[0].documentId` in the response.
  * The unique identifier for the newly created document. Use this ID for all subsequent operations on this document.
  * Example value: `05565225-504b-43e6-a051-37a389bfa65d`

The document has been successfully created with custom metadata fields and attachments.

* The response includes the document ID which can be used for subsequent operations
* The document is created with the specified metadata definition and workflow
* The document includes all the custom metadata fields you provided
* The document includes the attachment you uploaded

> [!NOTE]
>
> Store the document ID for future operations such as updating, signing, or downloading the document.

***

## Advanced Document Creation Summary

You have successfully created a document in the Circularo system with custom metadata fields and attachments.

### Key Concepts

* **Metadata Definitions**: Templates that define the structure and fields of a document
* **Workflow Definitions**: Processes that define the lifecycle and states of a document
* **Document Categories**: Predefined classifications to organize documents
* **Attachments**: Supporting files associated with the main document

### Next Steps

With your document created, you can now:

* Add more attachments to the document
* Sign or seal the document
* Share the document with other users
* Move the document through its workflow states
* Search for documents using metadata fields

### Example Implementation

> [!NOTE]
>
> See our OpenAPI documentation to learn about the full set of API endpoints and parameters.

> [!NOTE]
>
> Please use proper exception handling and function decomposition in your own code. The code is provided for illustrative purposes only and is not intended for production use.

```javascript theme={null}
// Advanced document creation with metadata
const URL = "https://sandbox.circularo.com";
const API_PATH = "/api/v1";
const TOKEN = "YOUR_AUTH_TOKEN"; // Obtained from login or API key

try {
    // Step 1: Get available metadata definitions
    const metadataResponse = await fetch(`${URL}${API_PATH}/definitions/documents?token=${TOKEN}`);
    if (!metadataResponse.ok) {
        throw new Error(`Failed to retrieve metadata definitions: ${metadataResponse.status} ${metadataResponse.statusText}`);
    }
    const metadataData = await metadataResponse.json();
    console.log(`Available metadata definitions: ${metadataData.results.map(def => def.name).join(', ')}`);

    // Step 2: Get available workflow definitions
    const workflowResponse = await fetch(`${URL}${API_PATH}/definitions/workflows?token=${TOKEN}`);
    if (!workflowResponse.ok) {
        throw new Error(`Failed to retrieve workflow definitions: ${workflowResponse.status} ${workflowResponse.statusText}`);
    }
    const workflowData = await workflowResponse.json();
    console.log(`Available workflow definitions: ${workflowData.results.map(wf => wf.name).join(', ')}`);

    // Step 3: Get document categories
    const categoriesResponse = await fetch(`${URL}${API_PATH}/login?token=${TOKEN}`);
    if (!categoriesResponse.ok) {
        throw new Error(`Failed to retrieve document categories: ${categoriesResponse.status} ${categoriesResponse.statusText}`);
    }
    const categoriesData = await categoriesResponse.json();
    const documentCategories = categoriesData.settings.data.documentCategories;
    const selectedCategory = documentCategories[0]; // Select the first available category

    // Step 4: Upload the main PDF file
    const mainFormData = new FormData();
    mainFormData.append('fileName', 'Main Document');
    mainFormData.append('file', fs.createReadStream('path/to/main-document.pdf'));  // This example uses Node.js 'fs' module to read the file

    const mainUploadResponse = await fetch(`${URL}${API_PATH}/files/saveFile?token=${TOKEN}`, {
        method: 'POST',
        body: mainFormData
    });
    if (!mainUploadResponse.ok) {
        throw new Error(`Main file upload failed: ${mainUploadResponse.status} ${mainUploadResponse.statusText}`);
    }
    const mainUploadData = await mainUploadResponse.json();
    const mainFileId = mainUploadData.file.id;

    // Step 5: Upload an attachment file
    const attachmentFormData = new FormData();
    attachmentFormData.append('fileName', 'Supporting Document');
    attachmentFormData.append('file', fs.createReadStream('path/to/attachment.pdf'));  // This example uses Node.js 'fs' module to read the file

    const attachmentUploadResponse = await fetch(`${URL}${API_PATH}/files/saveFile?token=${TOKEN}`, {
        method: 'POST',
        body: attachmentFormData
    });
    if (!attachmentUploadResponse.ok) {
        throw new Error(`Attachment upload failed: ${attachmentUploadResponse.status} ${attachmentUploadResponse.statusText}`);
    }
    const attachmentUploadData = await attachmentUploadResponse.json();
    const attachmentFileId = attachmentUploadData.file.id;

    // Step 6: Create a document with custom metadata and attachment
    const createResponse = await fetch(`${URL}${API_PATH}/documents?token=${TOKEN}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            body: {
                documentType: "d_my_definition",
                documentTitle: "Advanced Document Example",
                documentCategory: selectedCategory,
                pdfFile: {
                    content: mainFileId
                },
                file: [{
                    content: attachmentFileId
                }],
                D_MY_DEFINITION_TEXTAREA: "Custom metadata field value"
            },
            definitionType: "ext",
            workflow: "wf_archive"
        })
    });
    if (!createResponse.ok) {
        throw new Error(`Document creation failed: ${createResponse.status} ${createResponse.statusText}`);
    }

    const createData = await createResponse.json();
    const documentId = createData.results[0].documentId;

    console.log(`Document created successfully with ID: ${documentId}`);
} catch (error) {
    console.error('Error creating document:', error.message);
}
```

> [!WARNING]
>
> The metadata definition and workflow must exist in your Circularo instance. The example uses "d\_my\_definition" and "wf\_archive" which are examples, your system may use different values.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.