function api_update_document
Flask API endpoint that updates document metadata (title and custom metadata fields) for a specific document, with authentication and authorization checks.
/tf/active/vicechatdev/vice_ai/complex_app.py
770 - 795
moderate
Purpose
This function serves as a RESTful API endpoint to modify document metadata. It validates user authentication, checks document ownership, updates allowed fields (title and metadata), and persists changes. It's designed for document management systems where users need to update their document properties without modifying content.
Source Code
def api_update_document(doc_id):
"""Update document metadata"""
try:
document = get_document(doc_id)
if not document:
return jsonify({'error': 'Document not found'}), 404
if document.author != get_user_id():
return jsonify({'error': 'Access denied'}), 403
data = request.get_json()
if 'title' in data:
document.title = data['title'].strip()
if 'metadata' in data:
document.metadata.update(data['metadata'])
save_document(document)
return jsonify({
'document': document.to_dict(),
'message': 'Document updated successfully'
})
except Exception as e:
logger.error(f"Update document error: {e}")
return jsonify({'error': 'Failed to update document'}), 500
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
doc_id |
- | - | positional_or_keyword |
Parameter Details
doc_id: String identifier for the document to be updated. Extracted from the URL path parameter. Used to retrieve the specific document from storage. Expected to be a valid document identifier (likely UUID or similar unique string).
Return Value
Returns a Flask JSON response tuple. On success (200): JSON object with 'document' key containing the updated document dictionary and 'message' key with success text. On document not found (404): JSON with 'error' key. On access denied (403): JSON with 'error' key when user doesn't own the document. On server error (500): JSON with 'error' key when update fails.
Dependencies
flasklogging
Required Imports
from flask import jsonify
from flask import request
import logging
Usage Example
# Example API call using requests library
import requests
# Assuming authentication is handled via session/token
headers = {'Authorization': 'Bearer YOUR_TOKEN', 'Content-Type': 'application/json'}
data = {
'title': 'Updated Document Title',
'metadata': {
'category': 'research',
'tags': ['important', 'review'],
'last_modified_by': 'user123'
}
}
response = requests.put(
'http://localhost:5000/api/documents/doc-uuid-123',
json=data,
headers=headers
)
if response.status_code == 200:
result = response.json()
print(f"Success: {result['message']}")
print(f"Updated document: {result['document']}")
elif response.status_code == 404:
print("Document not found")
elif response.status_code == 403:
print("Access denied - you don't own this document")
else:
print(f"Error: {response.json()['error']}")
Best Practices
- Always validate user authentication before processing the request (handled by require_auth decorator)
- Verify document ownership before allowing updates to prevent unauthorized modifications
- Use strip() on title input to remove leading/trailing whitespace
- Use update() method on metadata dictionary to merge new metadata with existing rather than replacing
- Implement proper error logging for debugging and monitoring
- Return appropriate HTTP status codes (404 for not found, 403 for forbidden, 500 for server errors)
- Validate and sanitize input data before updating document fields to prevent injection attacks
- Consider adding input validation for title length and metadata structure
- Ensure the document object is properly saved/committed to persistent storage
- The function only updates title and metadata fields, not document content - this is intentional separation of concerns
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function update_document_v2 89.5% similar
-
function api_update_section 80.8% similar
-
function api_create_document 77.8% similar
-
function update_data_section 72.6% similar
-
function api_delete_document 71.2% similar