Upload Documents to Library

Type POST

https://api.ai21.com/studio/v1/library/files

Upload a file to the designated private library in your AI21 Studio account. Currently, the size of all the files uploaded can be up to 1 GB.

Request body

  • file   string   →Required
    Full path to the file to be uploaded.

  • path   string   →Optional
    Can be used later to focus question to a specific path.

  • labels   array of strings   →Optional
    Can be used later to focus question to specific labeled documents in the library.

  • publicUrl   string   →Optional
    Public URL associated with the file, can be used as additional context in answers retrieved with the API.

import requests

url = "https://api.ai21.com/studio/v1/library/files"
headers = {"Authorization": f"Bearer API_KEY"}
files = {"file": open("/Users/user/Desktop/folder/koala.txt", "rb")}
data = {
    "path": "desktop/folder", 
    "labels": ["cuties", "furry_animals"], 
    "publicUrl": "https://en.wikipedia.org/wiki/Koala"
}

requests.post(url, headers=headers, data=data, files=files)
import fetch from 'node-fetch';
import fs from 'fs';
import FormData from 'form-data';

const url = "https://api.ai21.com/studio/v1/library/files";
const API_KEY = "your-api-key"; // replace with your API key

const file = fs.createReadStream("/Users/user/Desktop/folder/koala.txt");
const formData = new FormData();

formData.append('file', file);
formData.append('path', 'desktop/folder');
formData.append('labels', JSON.stringify(["cuties", "furry_animals"]));
formData.append('publicUrl', 'https://en.wikipedia.org/wiki/Koala');

fetch(url, {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${API_KEY}`,
  },
  body: formData
}).then(res => res.json())
  .then(json => console.log(json))
  .catch(err => console.error('error:' + err));

Response 200

A unique identifier for the uploaded file. Type: UUID

da13301a-14e4-4487-aa2f-cc6048e73cdc // file-uuid

Error: Unsupported document type 422

Error message:

{
    "detail": "Invalid file type: {fileType}. Supported file types are: text/plain"
}

Error: Same file name, same path 422

Error message:

{
  "detail": "File: {fileName} already exists",
  "suggestion": "To override the file content, delete it first using the DELETE endpoint"
}

Retrieve Document List

Type GET

https://api.ai21.com/studio/v1/library/files

Retrieves a list of all uploaded documents in the user's library.

Pagination:
By default, the endpoint returns up to 1000 files. Pagination can be controlled using the following parameters:

  • offset (optional): The number of files to skip.
  • limit (optional): The number of files to retrieve (maximum 1000).
import requests

url = "https://api.ai21.com/studio/v1/library/files"
params = {
    "offset": 0,  # Optional: Adjust as needed
    "limit": 100  # Optional: Adjust as needed
}
headers = {"Authorization": f"Bearer API_KEY"}

response = requests.get(url, headers=headers, params=params)
import fetch from 'node-fetch';

const url = "https://api.ai21.com/studio/v1/library/files";
const API_KEY = "your-api-key"; // replace with your API key

fetch(url, {
  method: 'GET',
  headers: {
    'Authorization': `Bearer ${API_KEY}`,
  }
}).then(res => res.json())
  .then(json => console.log(json))
  .catch(err => console.error('error:' + err));

Response 200

Success response contains a list of documents. Each document includes the following parameters:

fileId  uuid   The unique identifier of the file.
name string   The name of the file.
path string   The path where the file is located.
fileType string   The type of the file.
sizeBytes int   The size of the file in bytes.
labels list of strings   The labels associated with the file.
publicUrl string   The public URL of the file.
createdBy  uuid   The identifier of the user who created the file.
creationDate  date   The date when the file was created.
lastUpdated  date   The last update date of the file.
status string   The status of the file.
errorCode int   The error code, if any.
errorMessage string   The error message, if any.

Error Response 422 occurs when no id is found.


Retrieve Document by ID

Type GET

https://api.ai21.com/studio/v1/library/files/fileId

Retrieves a specific document from the user's library using its unique identifier.

import requests

url = "https://api.ai21.com/studio/v1/library/files/{fileId}"
headers = {"Authorization": f"Bearer API_KEY"}

requests.get(url, headers=headers)
import fetch from 'node-fetch';

const DOCUMENT_ID = "your-document-id"; // replace with your document id
const API_KEY = "your-api-key"; // replace with your API key
const url = `https://api.ai21.com/studio/v1/library/files/${DOCUMENT_ID}`;

fetch(url, {
  method: 'GET',
  headers: {
    'Authorization': `Bearer ${API_KEY}`,
  }
}).then(res => res.json())
  .then(json => console.log(json))
  .catch(err => console.error('error:' + err));

Response 200

Success response returns the specific document details including:

fileId  uuid   The unique identifier of the file.
name string   The name of the file.
path string   The path where the file is located.
fileType string   The type of the file.
sizeBytes int   The size of the file in bytes.
labels list of strings   The labels associated with the file.
publicUrl string   The public URL of the file.
createdBy  uuid   The identifier of the user who created the file.
creationDate  date   The date when the file was created.
lastUpdated  date   The last update date of the file.
status string   The status of the file.
errorCode int   The error code, if any.
errorMessage string   The error message, if any.

Error Response 422 occurs when no id is found.


Update Document Parameters

Type PUT

https://api.ai21.com/studio/v1/library/files/fileId

Updates the specified parameters of a specific document in the user's library. This operation currently supports updating the publicUrl and labels parameters.

This operation will overwrite the existing values of the parameters. If you wish to add new labels without removing the existing ones, you must include the existing labels along with the new labels in the labels parameter.

For instance, if the existing labels are "Label A" and "Label B", and you wish to add "New Label C" and "New Label D", you must set "labels": ["Label A", "Label B", "New Label C", "New Label D"]. If you set "labels": ["New Label C", "New Label D"], the labels "Label A" and "Label B" will be removed.

Request body

  • publicUrl   string   →Optional
    The updated public URL of the document.

  • labels   array of strings   →Optional
    The updated labels associated with the file. Separate multiple labels with commas.

import requests

url = "https://api.ai21.com/studio/v1/library/files/{fileId}"
headers = {"Authorization": f"Bearer API_KEY"}
data = {
    "labels": ["Label A", "Label B", "New Label C", "New Label D"], 
    "publicUrl": "www.updated-url.com"
}

requests.put(url, headers=headers, json=data)
import fetch from 'node-fetch';

const DOCUMENT_ID = "your-document-id"; // replace with your document id
const API_KEY = "your-api-key"; // replace with your API key
const url = `https://api.ai21.com/studio/v1/library/files/${DOCUMENT_ID}`;

let data = {
  "labels": ["Label A", "Label B", "New Label C", "New Label D"],
  "public_url": "www.updated-url.com"
};

fetch(url, {
  method: 'PUT',
  headers: {
    'Authorization': `Bearer ${API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data)
}).then(res => res.json())
  .then(json => console.log(json))
  .catch(err => console.error('error:' + err));

Response

If the update is successful, the server will return an HTTP status code 200 with no body content. If the document ID does not exist, a 422 error message will be returned.


Delete Document

Type DELETE

https://api.ai21.com/studio/v1/library/files/fileId

Deletes a specific document from the user's library.

import requests

url = "https://api.ai21.com/studio/v1/library/files/{fileId}"
headers = {"Authorization": "Bearer API_KEY"}

requests.delete(url, headers=headers)
import fetch from 'node-fetch';

const url = "https://api.ai21.com/studio/v1/library/files/DOCUMENT_ID";
const headers = {"Authorization": "Bearer API_KEY"};

fetch(url, {
  method: 'DELETE',
  headers: headers
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

If the deletion is successful, the server will return an HTTP status code 200 with no body content. If the document ID does not exist, a 422 error message will be returned.

Restrictions:
Files in PROCESSING status cannot be deleted. Attempts to delete such files will result in a 422 error.