### POST /api/documents/ Source: https://github.com/tb1337/paperless-api/blob/main/docs/4_permissions.md Creates a new document with specified permissions. ```APIDOC ## POST /api/documents/ ### Description Creates a new document resource. You can optionally set object-level permissions during creation by providing a `PermissionTableType` object to the `set_permissions` field. ### Method POST ### Endpoint `/api/documents/` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **set_permissions** (object) - Optional - An object of type `PermissionTableType` to define initial permissions for the new document. This object contains `view` and `edit` fields, each being a `PermissionSetType` specifying lists of users and groups. ### Request Example ```python from pypaperless.models.common import PermissionSetType, PermissionTableType # Assuming 'paperless' is an initialized PaperlessAPI client draft = paperless.correspondents.draft() # Example for a correspondent, similar structure for documents draft.name = "Correspondent with perms" draft.set_permissions = PermissionTableType( view=PermissionSetType( users=[23], # User ID 23 can view ), edit=PermissionSetType( groups=[1] # Group ID 1 can edit ) ) # ... other fields for the document/correspondent # await paperless.documents.create(draft) # or similar create method ``` ### Response #### Success Response (201 Created) Returns the newly created document object, including its assigned permissions. #### Response Example ```json { "id": 123, "name": "Correspondent with perms", "permissions": { "view": { "users": [23], "groups": [] }, "edit": { "users": [], "groups": [1] } } // ... other document fields } ``` --- ``` -------------------------------- ### Get Document Metadata using Paperless API Source: https://context7.com/tb1337/paperless-api/llms.txt Provides examples for retrieving document metadata, such as checksums, sizes, MIME types, and language, using the Paperless API. It also shows how to access original metadata embedded within the document. The pypaperless library is used, and the code demonstrates both direct API calls and using document instances. ```python from pypaperless import Paperless import asyncio async def main(): async with Paperless("localhost:8000", "your-token") as paperless: # Get metadata metadata = await paperless.documents.metadata(23) print(f"Original checksum: {metadata.original_checksum}") print(f"Original size: {metadata.original_size}") print(f"Original mime type: {metadata.original_mime_type}") print(f"Has archive version: {metadata.has_archive_version}") print(f"Language: {metadata.lang}") if metadata.original_metadata: for item in metadata.original_metadata: print(f" {item['namespace']}:{item['prefix']}:{item['key']} = {item['value']}") # Using document instance document = await paperless.documents(23) metadata = await document.get_metadata() asyncio.run(main()) ``` -------------------------------- ### Create New Item Draft and Save Source: https://github.com/tb1337/paperless-api/blob/main/docs/1_basic_usage.md Demonstrates creating a new resource item. It involves getting a draft instance, applying data (via kwargs or attribute assignment), and then calling `save()` to persist the item. The primary key of the newly created item is returned. ```python from pypaperless.models.common import MatchingAlgorithmType draft = paperless.correspondents.draft( name="New correspondent", is_insensitive=True, # this works ) draft.matching_algorithm = MatchingAlgorithmType.ANY draft.match = 'any word "or small strings" match' draft.is_insensitive = False # and this, too! new_pk = await draft.save() #-> 42 ``` -------------------------------- ### Create New Item with Permissions using pypaperless Source: https://github.com/tb1337/paperless-api/blob/main/docs/4_permissions.md Demonstrates how to create a new resource item (e.g., a correspondent) with specific permissions using `pypaperless`. It involves initializing a draft of the resource and setting the `set_permissions` field with a `PermissionTableType` object, which can define users with view permissions. ```python from pypaperless.models.common import PermissionSetType, PermissionTableType draft = paperless.correspondents.draft() draft.name = "Correspondent with perms" draft.set_permissions = PermissionTableType( view=PermissionSetType( users=[23], ), ) # ... ``` -------------------------------- ### Create New Paperless Resource Items (Python) Source: https://context7.com/tb1337/paperless-api/llms.txt Provides examples for creating new resource items like correspondents, tags, and document types using the Paperless Python client. It demonstrates using the `draft()` method to prepare a new resource and `save()` to persist it. Includes setting specific properties like `matching_algorithm` and `match` for correspondents. Requires `pypaperless` and `asyncio`. ```python from pypaperless import Paperless from pypaperless.models.common import MatchingAlgorithmType import asyncio async def main(): async with Paperless("localhost:8000", "your-token") as paperless: # Create correspondent draft = paperless.correspondents.draft( name="ACME Corporation", is_insensitive=True ) draft.matching_algorithm = MatchingAlgorithmType.ANY draft.match = 'ACME "Corporation" invoice' new_id = await draft.save() print(f"Created correspondent with ID: {new_id}") # Create tag tag_draft = paperless.tags.draft( name="Important", color="#ff0000" ) tag_id = await tag_draft.save() print(f"Created tag with ID: {tag_id}") # Create document type dtype_draft = paperless.document_types.draft( name="Invoice" ) dtype_id = await dtype_draft.save() print(f"Created document type with ID: {dtype_id}") asyncio.run(main()) ``` -------------------------------- ### Update Payload Examples (JSON) Source: https://github.com/tb1337/paperless-api/blob/main/docs/1_basic_usage.md Illustrates the JSON payloads for updating items. The PATCH payload includes only changed fields, while the PUT payload includes all fields, requiring a complete representation of the item. ```json { "title": "New document title" } ``` ```json { "title": "New document title", "content": "...", "correspondents": ["..."], "document_types": ["..."], "storage_paths": ["..."], "...": "..." // and every other field } ``` -------------------------------- ### GET /api/documents/ Source: https://github.com/tb1337/paperless-api/blob/main/docs/1_basic_usage.md Retrieves a list of primary keys for all available documents. This is useful for knowing which items exist before fetching them individually. ```APIDOC ## GET /api/documents/ ### Description Retrieves a list of primary keys for all available documents. This is useful for knowing which items exist before fetching them individually. ### Method GET ### Endpoint /api/documents/ ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number to retrieve. Defaults to 1. ### Request Example ```python item_keys = await paperless.documents.all() ``` ### Response #### Success Response (200) - **list[integer]** - A list of document primary keys. #### Response Example ```json [ 1, 2, 3 ] ``` ``` -------------------------------- ### GET /api/documents/{id}/?full_perms=true Source: https://github.com/tb1337/paperless-api/blob/main/docs/4_permissions.md Retrieves a specific document, including its detailed permission information when `full_perms=true` is set. ```APIDOC ## GET /api/documents/{id}/?full_perms=true ### Description Retrieves a specific document by its ID. When the `full_perms` query parameter is set to `true`, the response will include detailed object-level permissions for the document. ### Method GET ### Endpoint `/api/documents/{id}/?full_perms=true` ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the document. #### Query Parameters - **full_perms** (boolean) - Optional - If set to `true`, includes detailed permission fields in the response. #### Request Body None ### Request Example ```bash GET https://localhost:8000/api/documents/23/?full_perms=true ``` ### Response #### Success Response (200) - **id** (integer) - The document's ID. - **owner** (object) - Information about the owner of the document. - **user_can_change** (boolean) - Indicates if the current user can modify the document. - **permissions** (object) - Contains detailed permission settings (view, edit, etc.). #### Response Example ```json { "id": 23, "owner": { "id": 1, "username": "admin" }, "user_can_change": true, "permissions": { "view": { "users": [1], "groups": [] }, "edit": { "users": [], "groups": [] } } } ``` --- ``` -------------------------------- ### Fetch Document and List Notes Source: https://github.com/tb1337/paperless-api/blob/main/docs/2_documents.md Fetches a document by its primary key and then retrieves all associated notes. This involves two HTTP GET requests to the Paperless-ngx API. ```python document = await paperless.documents(23) list_of_notes = await document.notes() ``` -------------------------------- ### PATCH /api/documents/{id}/?full_perms=true Source: https://github.com/tb1337/paperless-api/blob/main/docs/4_permissions.md Updates the permissions of an existing document. ```APIDOC ## PATCH /api/documents/{id}/?full_perms=true ### Description Updates an existing document's permissions. To modify permissions, you must first enable permission requesting for the document type, fetch the document, modify its `permissions` field, and then call the update method. ### Method PATCH ### Endpoint `/api/documents/{id}/?full_perms=true` ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the document to update. #### Query Parameters - **full_perms** (boolean) - Required - Must be set to `true` to enable modification of permission fields. #### Request Body This endpoint updates permissions by modifying the `document.permissions` object fetched previously and then calling `document.update()`. ### Request Example ```python # Ensure permissions are requested paperless.documents.request_permissions = True document = await paperless.documents(23) # Fetch document with permissions if document.has_permissions: # Modify permissions (e.g., add user 5 to the view list) document.permissions.view.users.append(5) await document.update() # Save the changes ``` ### Response #### Success Response (200 OK) Returns the updated document object. #### Response Example ```json { "id": 23, "owner": { "id": 1, "username": "admin" }, "user_can_change": true, "permissions": { "view": { "users": [1, 5], "groups": [] }, "edit": { "users": [], "groups": [] } } // ... other document fields } ``` --- ``` -------------------------------- ### Work with Custom Fields and Caching in Paperless API Source: https://context7.com/tb1337/paperless-api/llms.txt Demonstrates advanced usage of the `pypaperless` library, including initializing a cache for custom fields and safely retrieving custom field values from a document. It shows how to iterate through fields, check for existence, get values with type safety, and use fallback mechanisms. Requires API access and documents with custom fields. ```python from pypaperless import Paperless from pypaperless.models.common import CustomFieldIntegerValue import asyncio async def main(): async with Paperless("localhost:8000", "your-token") as paperless: # Initialize custom fields cache paperless.cache.custom_fields = await paperless.custom_fields.as_dict() # Fetch document with custom fields document = await paperless.documents(1337) # Iterate over custom fields for field in document.custom_fields: print(f"Field {field.field}: {field.value}") if hasattr(field, 'name'): print(f" Name: {field.name}") print(f" Type: {field.data_type}") # Check if field exists if 1 in document.custom_fields: print("Field 1 is present") # Get field value with type safety field = document.custom_fields.get(1, expected_type=CustomFieldIntegerValue) print(f"Integer value: {field.value}") # Get field with fallback if field := document.custom_fields.default(999): print(f"Optional field: {field.value}") else: print("Field 999 not found") asyncio.run(main()) ``` -------------------------------- ### Get Document Suggestions by Primary Key Source: https://github.com/tb1337/paperless-api/blob/main/docs/2_documents.md Retrieves classification suggestions (correspondents, tags, document types, etc.) for a document using its primary key. This makes a single HTTP GET request to the Paperless-ngx API. ```python suggestions = await paperless.documents.suggestions(23) ``` -------------------------------- ### List All Resource Primary Keys in Paperless Source: https://context7.com/tb1337/paperless-api/llms.txt Demonstrates how to retrieve lists of primary keys (IDs) for all resources of a specific type (e.g., documents, tags, correspondents) from Paperless-ngx. This is useful for getting an overview of available items. Requires `pypaperless` and `asyncio`, using the async context manager. ```python from pypaperless import Paperless import asyncio async def main(): async with Paperless("localhost:8000", "your-token") as paperless: # Get all document IDs document_ids = await paperless.documents.all() print(f"Document IDs: {document_ids}") # Get all tag IDs tag_ids = await paperless.tags.all() print(f"Tag IDs: {tag_ids}") # Get all correspondent IDs correspondent_ids = await paperless.correspondents.all() print(f"Correspondent IDs: {correspondent_ids}") asyncio.run(main()) ``` -------------------------------- ### Upload New Document using Paperless API Source: https://context7.com/tb1337/paperless-api/llms.txt Provides a Python code example for uploading a new document to paperless-ng using the `pypaperless` library. It covers reading a file, creating a document draft, setting various metadata fields (filename, title, created date, correspondent, document type, tags, ASN), and finally saving the document. Requires API access and a file to upload. ```python from pypaperless import Paperless import asyncio from datetime import datetime async def main(): async with Paperless("localhost:8000", "your-token") as paperless: # Read file with open("/path/to/invoice.pdf", "rb") as f: file_content = f.read() # Create document draft draft = paperless.documents.draft() draft.document = file_content draft.filename = "invoice.pdf" draft.title = "Invoice from ACME" draft.created = datetime.now() draft.correspondent = 1 draft.document_type = 5 draft.tags = [1, 2, 3] draft.archive_serial_number = 1337 # Upload document_id = await draft.save() print(f"Uploaded document with ID: {document_id}") asyncio.run(main()) ``` -------------------------------- ### Get Document Suggestions for Fetched Document Source: https://github.com/tb1337/paperless-api/blob/main/docs/2_documents.md Retrieves classification suggestions for an already fetched document object. This process involves fetching the document first (if not already) and then requesting suggestions via an HTTP GET request. ```python document = await paperless.documents(23) suggestions = await document.get_suggestions() ``` -------------------------------- ### Get One Item by Primary Key Source: https://github.com/tb1337/paperless-api/blob/main/docs/1_basic_usage.md Retrieves a single resource item using its primary key. Dependencies include the paperless API client. It returns a PaperlessModel object which can be used to fetch related resources. ```python document = await paperless.documents(1337) doc_type = await paperless.document_types(document.document_type) # 23 print(f"Document '{document.title}' is an {doc_type.name}.") #-> Document 'Order #23: Desktop Table' is an Invoice. ``` -------------------------------- ### Get Document Suggestions using Paperless API Source: https://context7.com/tb1337/paperless-api/llms.txt Demonstrates how to retrieve AI-powered suggestions for correspondents, tags, document types, storage paths, and dates for a given document using the Paperless API. It also shows how to apply these suggestions to a document and update it. The pypaperless library is required for this functionality. ```python from pypaperless import Paperless import asyncio async def main(): async with Paperless("localhost:8000", "your-token") as paperless: # Get AI suggestions suggestions = await paperless.documents.suggestions(23) print(f"Suggested correspondents: {suggestions.correspondents}") print(f"Suggested tags: {suggestions.tags}") print(f"Suggested document types: {suggestions.document_types}") print(f"Suggested storage paths: {suggestions.storage_paths}") print(f"Suggested dates: {suggestions.dates}") # Apply suggestions to document document = await paperless.documents(23) if suggestions.correspondents: document.correspondent = suggestions.correspondents[0] if suggestions.tags: document.tags = suggestions.tags await document.update() asyncio.run(main()) ``` -------------------------------- ### Iterate Over All Resource Items in Paperless Source: https://context7.com/tb1337/paperless-api/llms.txt Provides examples of iterating asynchronously over all items of a resource type (documents, tags) in Paperless-ngx. This allows processing each item individually, such as filtering documents or displaying tag usage. Requires `pypaperless` and `asyncio`, utilizing the async context manager. ```python from pypaperless import Paperless import asyncio async def main(): async with Paperless("localhost:8000", "your-token") as paperless: # Iterate over all documents count = 0 async for document in paperless.documents: if document.correspondent == 1: count += 1 print(f"Document {document.id}: {document.title}") print(f"Total documents for correspondent 1: {count}") # Iterate over all tags async for tag in paperless.tags: print(f"Tag: {tag.name} (used {tag.document_count} times)") asyncio.run(main()) ``` -------------------------------- ### Manage Permissions for Documents in Paperless API Source: https://context7.com/tb1337/paperless-api/llms.txt Provides examples of managing document permissions within the Paperless API using the pypaperless library. It covers enabling permission requests, fetching documents with their permissions, modifying user/group permissions for viewing and changing, and setting permissions when creating new entities. ```python from pypaperless import Paperless from pypaperless.models.common import PermissionSetType, PermissionTableType import asyncio async def main(): async with Paperless("localhost:8000", "your-token") as paperless: # Enable permission requests paperless.documents.request_permissions = True # Fetch document with permissions document = await paperless.documents(23) if document.has_permissions: print(f"Owner: {document.owner}") print(f"Can change: {document.user_can_change}") print(f"View users: {document.permissions.view.users}") print(f"View groups: {document.permissions.view.groups}") print(f"Change users: {document.permissions.change.users}") # Update permissions document.permissions.view.users.append(5) document.permissions.change.groups.append(2) await document.update() # Create with permissions draft = paperless.correspondents.draft() draft.name = "Restricted Correspondent" draft.set_permissions = PermissionTableType( view=PermissionSetType(users=[23], groups=[1]), change=PermissionSetType(users=[23]) ) new_id = await draft.save() asyncio.run(main()) ``` -------------------------------- ### GET /api/documents/{id}/ Source: https://github.com/tb1337/paperless-api/blob/main/docs/1_basic_usage.md Retrieves a single document by its primary key. The returned object is a PaperlessModel which may contain references to other resources that need to be resolved separately. ```APIDOC ## GET /api/documents/{id}/ ### Description Retrieves a single document by its primary key. The returned object is a PaperlessModel which may contain references to other resources that need to be resolved separately. ### Method GET ### Endpoint /api/documents/{id}/ ### Parameters #### Path Parameters - **id** (integer) - Required - The primary key of the document to retrieve. ### Request Example ```python document = await paperless.documents(1337) ``` ### Response #### Success Response (200) - **PaperlessModel** - The document object. #### Response Example ```json { "id": 1337, "title": "Order #23: Desktop Table", "document_type": 23 } ``` ``` -------------------------------- ### API Response Example: Custom Field Metadata Source: https://github.com/tb1337/paperless-api/blob/main/docs/3_custom_fields.md Demonstrates the detailed metadata structure for a single custom field as returned by the Paperless-ngx API. This includes the field's ID, name, data type, extra configuration, and document count. ```json { "id": 1, "name": "Very Important Document (VID)", "data_type": "boolean", "extra_data": { "select_options": [ null ], "default_currency": null }, "document_count": 23 } ``` -------------------------------- ### API Response Example: Custom Fields Source: https://github.com/tb1337/paperless-api/blob/main/docs/3_custom_fields.md Illustrates the raw JSON structure returned by the Paperless-ngx API for custom fields associated with a document. It shows the basic format containing field IDs and their corresponding values. ```json { "custom_fields": [ { "value": 42, "field": 11 } ] } ``` -------------------------------- ### Enable/Disable Permission Requesting in pypaperless Source: https://github.com/tb1337/paperless-api/blob/main/docs/4_permissions.md This snippet shows how to toggle the retrieval of permission fields (`owner` and `user_can_change`) when requesting data from Paperless-ngx. By setting `paperless.documents.request_permissions` to `True`, subsequent document requests will include permission details. Setting it to `False` disables this feature. ```python paperless.documents.request_permissions = True document = await paperless.documents(23) print(document.has_permissions) #-> True ``` ```python paperless.documents.request_permissions = False document = await paperless.documents(23) print(document.has_permissions) #-> False ``` -------------------------------- ### Update Permissions of an Existing Item in pypaperless Source: https://github.com/tb1337/paperless-api/blob/main/docs/4_permissions.md This code shows how to update the permissions of an existing resource item in Paperless-ngx using `pypaperless`. It requires enabling permission requests, fetching the item, modifying the `permissions` field (e.g., adding a user to the view permissions), and then saving the changes with an `update()` call. ```python paperless.documents.request_permissions = True document = await paperless.documents(23) if document.has_permissions: document.permissions.view.users.append(5) await document.update() ``` -------------------------------- ### Toggle Permission Requesting Source: https://github.com/tb1337/paperless-api/blob/main/docs/4_permissions.md Control whether permission fields ('owner', 'user_can_change') are included in API responses. By default, these fields are not returned. Enabling this feature adds them to subsequent requests for the specified resource type until explicitly disabled. ```APIDOC ## Toggle Permission Requesting ### Description Enables or disables the inclusion of permission-related fields (`owner`, `user_can_change`) in API responses for a given resource type. When enabled, subsequent requests for that resource will include these fields. The setting persists until explicitly disabled. ### Method This is controlled via a client-side setting, not a direct API endpoint. ### Endpoint N/A (Client-side setting) ### Parameters #### Query Parameters N/A #### Request Body N/A ### Request Example ```python # Enable requesting permissions for documents paperless.documents.request_permissions = True # Disable requesting permissions for documents paperless.documents.request_permissions = False ``` ### Response This action does not produce a direct API response. It modifies the client's behavior for subsequent API calls. #### Success Response (N/A) N/A #### Response Example N/A --- ``` -------------------------------- ### Initialize Paperless Connection with Token Source: https://context7.com/tb1337/paperless-api/llms.txt Demonstrates how to initialize an asynchronous connection to Paperless-ngx using a URL and an API token. It includes manual initialization and cleanup, and prints connection details. Requires the `pypaperless` library and `asyncio`. ```python import asyncio from pypaperless import Paperless async def main(): # Initialize with URL and token paperless = Paperless("localhost:8000", "your-secret-token") # Method 1: Manual initialization and cleanup await paperless.initialize() try: # Check connection details print(f"API Version: {paperless.host_api_version}") print(f"Host Version: {paperless.host_version}") print(f"Base URL: {paperless.base_url}") finally: await paperless.close() asyncio.run(main()) ``` -------------------------------- ### Initialize Paperless API Session (Python) Source: https://github.com/tb1337/paperless-api/blob/main/docs/1_basic_usage.md Demonstrates the basic initialization of the Paperless API client. It requires the host address, an API token, and uses asyncio for asynchronous operations. The session can be managed explicitly or using an async context manager. ```python import asyncio from pypaperless import Paperless paperless = Paperless("localhost:8000", "your-secret-token") # see main() examples async def main(): await paperless.initialize() # do something await paperless.close() asyncio.run(main()) ``` ```python import asyncio from pypaperless import Paperless paperless = Paperless("localhost:8000", "your-secret-token") async def main(): async with paperless: # do something asyncio.run(main()) ``` -------------------------------- ### Get Custom Field Value with Fallback (Python) Source: https://github.com/tb1337/paperless-api/blob/main/docs/3_custom_fields.md Retrieves a custom field value from a document, returning None if the field does not exist. This is safer than `get()` when the field's existence is uncertain, preventing potential errors. ```python specific_custom_field = await paperless.custom_fields(1) if field := document.custom_fields.default(specific_custom_field): print(field.value) #-> 42 ``` ```python custom_field_id = 1 if field := document.custom_fields.default(custom_field_id): print(field.value) #-> 42 ``` ```python from pypaperless.models.common import CustomFieldIntegerValue field = document.custom_fields.default(custom_field_id, expected_type=CustomFieldIntegerValue) ``` -------------------------------- ### Download, Preview, and Thumbnail Document Data (Python) Source: https://github.com/tb1337/paperless-api/blob/main/docs/2_documents.md Demonstrates how to download the binary data, preview, and thumbnail of a document using its primary key or an already fetched document object. It returns a DownloadedDocument instance containing the binary data and associated attributes. ```python download = await paperless.documents.download(23) preview = await paperless.documents.preview(23) thumbnail = await paperless.documents.thumbnail(23) ``` ```python document = await paperless.documents(23) download = await document.get_download() preview = await document.get_preview() thumbnail = await document.get_thumbnail() ``` -------------------------------- ### Use Paperless Context Manager for Connection Source: https://context7.com/tb1337/paperless-api/llms.txt Illustrates using an asynchronous context manager (`async with`) for managing the Paperless-ngx connection. This ensures automatic initialization and cleanup of the connection. It demonstrates fetching all documents and a specific document. Requires `pypaperless` and `asyncio`. ```python from pypaperless import Paperless import asyncio async def main(): # Use async context manager for automatic cleanup async with Paperless("localhost:8000", "your-token") as paperless: # Connection is automatically initialized documents = await paperless.documents.all() print(f"Total document IDs: {len(documents)}") # Fetch specific document document = await paperless.documents(1337) print(f"Title: {document.title}") print(f"Content: {document.content[:100]}...") # Connection is automatically closed asyncio.run(main()) ``` -------------------------------- ### Search Documents by Query using Paperless API Source: https://context7.com/tb1337/paperless-api/llms.txt Demonstrates how to search for documents using query syntax with the Paperless API. It shows basic keyword searches and more complex queries involving dates and correspondent. Requires the pypaperless library and an active Paperless API connection. ```python from pypaperless import Paperless import asyncio async def main(): async with Paperless("localhost:8000", "your-token") as paperless: # Search with query syntax async for document in paperless.documents.search("type:invoice"): print(f"Found: {document.title}") # Access search hit data if document.has_search_hit: print(f" Score: {document.search_hit.score}") print(f" Rank: {document.search_hit.rank}") # Complex search query = "correspondent:ACME created:[2024-01-01 to 2024-12-31]" async for document in paperless.documents.search(query): print(f"Match: {document.id} - {document.title}") asyncio.run(main()) ``` -------------------------------- ### Access System Status and Configuration with PyPaperless Source: https://context7.com/tb1337/paperless-api/llms.txt This snippet shows how to retrieve system status, configuration details, and statistics from a Paperless-ngx instance using the PyPaperless library. It requires the 'pypaperless' library and uses asynchronous programming. ```python from pypaperless import Paperless import asyncio async def main(): async with Paperless("localhost:8000", "your-token") as paperless: # Get system status status = await paperless.status() print(f"Installed version: {status.installed_version}") print(f"Storage type: {status.storage_type}") print(f"Database type: {status.database_type}") print(f"OCR mode: {status.ocr_mode}") # Get configuration config = await paperless.config() print(f"App title: {config.app_title}") print(f"App logo: {config.app_logo}") print(f"User args: {config.user_args}") # Get statistics stats = await paperless.statistics() print(f"Total documents: {stats.documents_total}") print(f"Inbox documents: {stats.documents_inbox}") asyncio.run(main()) ``` -------------------------------- ### Use Custom aiohttp Session with Paperless (Python) Source: https://github.com/tb1337/paperless-api/blob/main/docs/1_basic_usage.md Shows how to integrate an existing `aiohttp.ClientSession` with the Paperless API client. This is useful for managing network connections across multiple library instances or for custom request configurations. ```python import aiohttp from pypaperless import Paperless my_session = aiohttp.ClientSession() # ... paperless = Paperless("localhost:8000", "your-secret-token", session=my_session) ``` -------------------------------- ### Get Custom Field Value (Python) Source: https://github.com/tb1337/paperless-api/blob/main/docs/3_custom_fields.md Retrieves a specific custom field value from a document. Raises ItemNotFoundError if the field does not exist. This method is useful when you are certain the custom field exists. ```python specific_custom_field = await paperless.custom_fields(1) field = document.custom_fields.get(specific_custom_field) print(field.value) #-> 42 ``` ```python custom_field_id = 1 field = document.custom_fields.get(custom_field_id) print(field.value) #-> 42 ``` ```python from pypaperless.models.common import CustomFieldIntegerValue field = document.custom_fields.get(custom_field_id, expected_type=CustomFieldIntegerValue) ``` -------------------------------- ### Remove Integer Custom Field (JavaScript) Source: https://github.com/tb1337/paperless-api/blob/main/docs/3_custom_fields.md This example demonstrates how to remove an integer custom field from a document using JavaScript. It shows the syntax for accessing and modifying the custom fields object directly. ```javascript document.custom_fields -= my_int_field ``` -------------------------------- ### Get Next Available Archive Serial Number Source: https://github.com/tb1337/paperless-api/blob/main/docs/2_documents.md Fetches the next available archive serial number (ASN) from Paperless-ngx as an integer. This is useful for ensuring unique numbering when archiving new documents. ```python next_asn = await paperless.documents.get_next_asn() #-> 1337 ``` -------------------------------- ### Work with Document Notes using Paperless API Source: https://context7.com/tb1337/paperless-api/llms.txt Demonstrates how to retrieve, create, and delete notes associated with a document using the `pypaperless` library. It shows two methods for creating notes and how to handle note deletion. Requires a running paperless-ng instance and an API token. ```python from pypaperless import Paperless import asyncio async def main(): async with Paperless("localhost:8000", "your-token") as paperless: # Get all notes for a document notes = await paperless.documents.notes(23) for note in notes: print(f"Note {note.id}: {note.note}") print(f" Created: {note.created}") print(f" User: {note.user}") # Create new note (method 1) draft = paperless.documents.notes.draft(23) draft.note = "This document needs review" note_id, doc_id = await draft.save() print(f"Created note {note_id} on document {doc_id}") # Create new note (method 2) document = await paperless.documents(23) note_draft = document.notes.draft() note_draft.note = "Follow up with customer" note_id, doc_id = await note_draft.save() # Delete a note notes = await document.notes() if notes: success = await notes[0].delete() print(f"Note deleted: {success}") asyncio.run(main()) ``` -------------------------------- ### Filter Paperless Resources with Reduce (Python) Source: https://context7.com/tb1337/paperless-api/llms.txt Demonstrates how to filter documents using the `reduce` method in the Paperless Python client. Supports filtering by single or multiple criteria and retrieving specific fields like document IDs. Requires the `pypaperless` library and `asyncio`. ```python from pypaperless import Paperless import asyncio async def main(): async with Paperless("localhost:8000", "your-token") as paperless: # Filter documents by correspondent filters = {"correspondent__id": 1} async with paperless.documents.reduce(**filters) as filtered: async for document in filtered: print(f"Document: {document.title}") # Filter documents by date range filters = { "created__date__gt": "2024-01-01", "created__date__lt": "2024-12-31" } async with paperless.documents.reduce(**filters) as filtered: count = 0 async for document in filtered: count += 1 print(f"Documents in 2024: {count}") # Get filtered list of IDs only async with paperless.documents.reduce(correspondent__id=5) as filtered: ids = await filtered.all() print(f"Document IDs for correspondent 5: {ids}") asyncio.run(main()) ``` -------------------------------- ### Check for Custom Field Existence (by ID) Source: https://github.com/tb1337/paperless-api/blob/main/docs/3_custom_fields.md Shows how to check for the presence of a custom field on a document using its ID. The `get` method on `document.custom_fields` returns the field if found, allowing access to its value. ```python import paperless # ... assuming document and paperless are initialized ... custom_field_id = 1 field = document.custom_fields.get(custom_field_id) if field: # do something with: field.value ``` -------------------------------- ### Iterate Over Paginated Paperless Resources (Python) Source: https://context7.com/tb1337/paperless-api/llms.txt Shows how to iterate through paginated results of resources, such as documents, using the `pages()` method. It demonstrates fetching individual pages, accessing page details (current page, total pages, count, items), and checking for the existence of subsequent pages. Requires `pypaperless` and `asyncio`. ```python from pypaperless import Paperless import asyncio async def main(): async with Paperless("localhost:8000", "your-token") as paperless: # Iterate page by page page_iter = aiter(paperless.documents.pages()) # Get first page page = await anext(page_iter) print(f"Page {page.current_page} of {page.total_pages}") print(f"Total items: {page.count}") print(f"Items on this page: {len(page.items)}") print(f"Has next: {page.has_next}") # Process documents on this page for document in page.items: print(f" - {document.title}") # Get second page if page.has_next: page = await anext(page_iter) print(f"\nPage {page.current_page}") for document in page.items: print(f" - {document.title}") asyncio.run(main()) ``` -------------------------------- ### Download Document Files using Paperless API Source: https://context7.com/tb1337/paperless-api/llms.txt Illustrates how to download document files, including archived and original versions, as well as previews and thumbnails, using the Paperless API. The code utilizes the pypaperless library and demonstrates saving downloaded content to a file. It also shows how to use document instances for these operations. ```python from pypaperless import Paperless import asyncio async def main(): async with Paperless("localhost:8000", "your-token") as paperless: # Download archived version download = await paperless.documents.download(23) print(f"Content type: {download.content_type}") print(f"Filename: {download.disposition_filename}") print(f"Size: {len(download.content)} bytes") # Save to file with open(f"/tmp/{download.disposition_filename}", "wb") as f: f.write(download.content) # Download original version original = await paperless.documents.download(23, original=True) # Get preview preview = await paperless.documents.preview(23) # Get thumbnail thumbnail = await paperless.documents.thumbnail(23) # Using document instance document = await paperless.documents(23) download = await document.get_download() preview = await document.get_preview() thumbnail = await document.get_thumbnail() asyncio.run(main()) ``` -------------------------------- ### Retrieve List of Primary Keys Source: https://github.com/tb1337/paperless-api/blob/main/docs/1_basic_usage.md Fetches a list of all available primary keys for a given resource. This is useful for bulk operations or when needing to reference multiple items. The function `all()` on the resource client is used. ```python item_keys = await paperless.documents.all() #-> [1, 2, 3, ...] ``` -------------------------------- ### Generate Paperless API Token from Credentials Source: https://context7.com/tb1337/paperless-api/llms.txt Shows how to generate an API token for Paperless-ngx using username and password credentials. The generated token can then be used to establish a connection. This requires `pypaperless` and `asyncio`. Error handling for the generation process is included. ```python from pypaperless import Paperless import asyncio async def main(): # Generate token from username/password try: token = await Paperless.generate_api_token( url="localhost:8000", username="api_user", password="secret_password" ) print(f"Generated token: {token}") # Use the token to initialize connection paperless = Paperless("localhost:8000", token) async with paperless: config = await paperless.config() print(f"App title: {config.app_title}") except Exception as e: print(f"Error: {e}") asyncio.run(main()) ``` -------------------------------- ### Update Existing Paperless Resource Items (Python) Source: https://context7.com/tb1337/paperless-api/llms.txt Illustrates how to update existing resources, such as documents, using the Paperless Python client. It covers fetching a resource, modifying its attributes, and saving changes using either a PATCH request (default, `update()`) or a PUT request (with `only_changed=False`). Requires `pypaperless` and `asyncio`. ```python from pypaperless import Paperless import asyncio async def main(): async with Paperless("localhost:8000", "your-token") as paperless: # Fetch document document = await paperless.documents(23) # Update fields document.title = "Updated Invoice Title" document.tags = [1, 2, 3] document.correspondent = 5 # Save changes (PATCH - only changed fields) success = await document.update() print(f"Update successful: {success}") # Alternative: PUT all fields document.archive_serial_number = 42 success = await document.update(only_changed=False) print(f"Full update successful: {success}") asyncio.run(main()) ``` -------------------------------- ### Generate Paperless API Token (Python) Source: https://github.com/tb1337/paperless-api/blob/main/docs/1_basic_usage.md Provides a utility function to generate an API token for Paperless-ngx. It requires the host, username, and password. Optionally, a custom `aiohttp.ClientSession` can be provided. Caution: Avoid hardcoding credentials. ```python from pypaperless import Paperless token = Paperless.generate_api_token( "localhost:8000", "test_user", "your-password-here", ) ``` ```python import aiohttp from pypaperless import Paperless url = "localhost:8000" my_session = aiohttp.ClientSession() token = Paperless.generate_api_token( "localhost:8000", "test_user", "not-so-secret-password-anymore", session=my_session, ) ``` -------------------------------- ### Get Next Available Archive Serial Number with Paperless API Source: https://context7.com/tb1337/paperless-api/llms.txt Shows how to retrieve the next available archive serial number (ASN) from the paperless-ng system using the `pypaperless` library. This is useful when creating new documents to ensure unique serial numbers. Requires a connection to the paperless-ng API. ```python from pypaperless import Paperless import asyncio async def main(): async with Paperless("localhost:8000", "your-token") as paperless: # Get next ASN next_asn = await paperless.documents.get_next_asn() print(f"Next available ASN: {next_asn}") # Use it when creating a document draft = paperless.documents.draft() draft.archive_serial_number = next_asn # ... set other fields and save asyncio.run(main()) ``` -------------------------------- ### Iterating Over Document Custom Fields Source: https://github.com/tb1337/paperless-api/blob/main/docs/3_custom_fields.md Demonstrates the straightforward way to iterate through all custom fields attached to a document using a simple for loop. ```python import paperless # ... assuming document and paperless are initialized ... for field in document.custom_fields: # do something with each field ``` -------------------------------- ### POST /api/correspondents/ Source: https://github.com/tb1337/paperless-api/blob/main/docs/1_basic_usage.md Creates a new correspondent. This involves first retrieving a draft instance, applying data to it, and then saving the draft to create the actual resource. ```APIDOC ## POST /api/correspondents/ ### Description Creates a new correspondent. This involves first retrieving a draft instance, applying data to it, and then saving the draft to create the actual resource. ### Method POST ### Endpoint /api/correspondents/ ### Parameters #### Request Body - **name** (string) - Required - The name of the correspondent. - **is_insensitive** (boolean) - Optional - Whether the matching algorithm is case-insensitive. - **matching_algorithm** (string) - Optional - The matching algorithm to use (e.g., ANY, ALL). - **match** (string) - Optional - The matching pattern. ### Request Example ```python from pypaperless.models.common import MatchingAlgorithmType draft = paperless.correspondents.draft( name="New correspondent", is_insensitive=True, ) draft.matching_algorithm = MatchingAlgorithmType.ANY draft.match = 'any word "or small strings" match' draft.is_insensitive = False new_pk = await draft.save() ``` ### Response #### Success Response (201) - **integer** - The primary key of the newly created correspondent. #### Response Example ```json 42 ``` ``` -------------------------------- ### Retrieve Document Metadata (Python) Source: https://github.com/tb1337/paperless-api/blob/main/docs/2_documents.md Shows how to fetch metadata associated with a document. This can be done either by providing the document's primary key or by using an already retrieved document object. ```python metadata = await paperless.documents.metadata(23) ``` ```python document = await paperless.documents(23) metadata = await document.get_metadata() ``` -------------------------------- ### Iterating over Documents Source: https://github.com/tb1337/paperless-api/blob/main/docs/1_basic_usage.md Iterate over all documents in the system. Each item returned is a PaperlessModel, allowing for mass operations or individual processing. ```APIDOC ## Iterating over Documents ### Description Iterate over all documents in the system. Each item returned is a PaperlessModel, allowing for mass operations or individual processing. ### Method GET ### Endpoint /api/documents/ ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number to retrieve. Used internally for pagination. ### Request Example ```python count = 0 async for item in paperless.documents: if item.correspondent == 1: count += 1 ``` ### Response #### Success Response (200) - **PaperlessModel** - A document object. #### Response Example ```json { "id": 1, "title": "Sample Document", "correspondent": 1 } ``` ``` -------------------------------- ### Iterate Over Resource Items Source: https://github.com/tb1337/paperless-api/blob/main/docs/1_basic_usage.md Enables iterating through all resource items. Each item yielded is a PaperlessModel. This is suitable for mass operations but can lead to numerous HTTP requests. ```python count = 0 async for item in paperless.documents: if item.correspondent == 1: count += 1 print(f"{count} documents are currently stored for correspondent 1.") #-> 5 documents are currently stored for correspondent 1. ``` -------------------------------- ### Manage Tags and Correspondents with PyPaperless Source: https://context7.com/tb1337/paperless-api/llms.txt This snippet demonstrates how to list, create, and manage tags and correspondents using the PyPaperless library. It utilizes asynchronous operations for network requests and relies on the 'pypaperless' library. ```python from pypaperless import Paperless import asyncio async def main(): async with Paperless("localhost:8000", "your-token") as paperless: # List all tags async for tag in paperless.tags: print(f"Tag: {tag.name} (color: {tag.color})") print(f" Used in {tag.document_count} documents") # Create tag tag_draft = paperless.tags.draft( name="Urgent", color="#ff0000", is_inbox_tag=True ) tag_id = await tag_draft.save() # List correspondents async for corr in paperless.correspondents: print(f"Correspondent: {corr.name}") if corr.match: print(f" Match: {corr.match}") print(f" Algorithm: {corr.matching_algorithm}") # Create correspondent corr_draft = paperless.correspondents.draft(name="New Vendor") corr_id = await corr_draft.save() asyncio.run(main()) ```