function api_get_document
Flask API endpoint that retrieves a specific document by ID, validates user access permissions, and returns the document data as JSON.
/tf/active/vicechatdev/vice_ai/complex_app.py
752 - 766
moderate
Purpose
This function serves as a REST API endpoint to fetch a single document from the system. It enforces authentication via the @require_auth decorator, verifies that the requesting user is the document's author, and returns the document in JSON format. It handles error cases including document not found, access denied, and server errors with appropriate HTTP status codes.
Source Code
def api_get_document(doc_id):
"""Get a specific document"""
try:
document = get_document(doc_id)
if not document:
return jsonify({'error': 'Document not found'}), 404
# Check access permission
if document.author != get_user_id():
return jsonify({'error': 'Access denied'}), 403
return jsonify({'document': document.to_dict()})
except Exception as e:
logger.error(f"Get document error: {e}")
return jsonify({'error': 'Failed to retrieve document'}), 500
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
doc_id |
- | - | positional_or_keyword |
Parameter Details
doc_id: String identifier for the document to retrieve. This is extracted from the URL path parameter and used to query the document from the database or storage system.
Return Value
Returns a Flask JSON response tuple. On success (200): {'document': <document_dict>} containing the document's dictionary representation. On document not found (404): {'error': 'Document not found'}. On access denied (403): {'error': 'Access denied'}. On server error (500): {'error': 'Failed to retrieve document'}. Each error response includes an appropriate HTTP status code.
Dependencies
flasklogging
Required Imports
from flask import jsonify
Usage Example
# Assuming Flask app setup and dependencies are configured
# GET request to: /api/documents/abc123
# With valid authentication token/session
import requests
# Example API call
response = requests.get(
'http://localhost:5000/api/documents/abc123',
headers={'Authorization': 'Bearer <token>'},
cookies={'session': '<session_id>'}
)
if response.status_code == 200:
document = response.json()['document']
print(f"Document title: {document['title']}")
elif response.status_code == 404:
print("Document not found")
elif response.status_code == 403:
print("Access denied - not the document author")
else:
print("Server error occurred")
Best Practices
- Always use the @require_auth decorator to ensure only authenticated users can access this endpoint
- The function implements proper authorization by checking if the requesting user is the document author
- Returns appropriate HTTP status codes (404, 403, 500) for different error scenarios
- Uses try-except block to catch and log unexpected errors without exposing internal details
- Logs errors with context for debugging while returning generic error messages to clients
- Ensure get_document() returns None for non-existent documents rather than raising exceptions
- The document model should implement a to_dict() method that sanitizes sensitive data before serialization
- Consider implementing rate limiting on this endpoint to prevent abuse
- For production use, consider adding request validation and sanitization for doc_id parameter
- Consider implementing caching mechanisms for frequently accessed documents
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function get_document_v4 78.7% similar
-
function api_list_documents 78.6% similar
-
function get_documents_v1 78.6% similar
-
function api_create_document 75.8% similar
-
function api_remove_document_v1 75.7% similar