function api_list_documents_v2
Flask API endpoint that retrieves and returns a list of all documents uploaded by the currently authenticated user from their session storage.
/tf/active/vicechatdev/vice_ai/new_app.py
2452 - 2475
simple
Purpose
This endpoint provides a RESTful API for fetching document metadata for the current user's session. It retrieves documents stored in the Flask session, transforms them into a frontend-friendly format with essential metadata (ID, filename, size, text length, upload timestamp), and returns them as JSON. Used for displaying user's uploaded documents in the UI and managing document listings.
Source Code
def api_list_documents():
"""List all uploaded documents for the current user"""
try:
documents = session.get('uploaded_documents', {})
# Convert to list format expected by frontend
doc_list = []
for doc_id, doc_info in documents.items():
doc_list.append({
'id': doc_id,
'filename': doc_info['filename'],
'size': doc_info['size'],
'text_length': len(doc_info['text_content']),
'uploaded_at': doc_info['uploaded_at']
})
return jsonify({
'documents': doc_list,
'count': len(doc_list)
})
except Exception as e:
logger.error(f"List documents error: {e}")
return jsonify({'error': 'Failed to list documents'}), 500
Return Value
Returns a Flask JSON response. On success (HTTP 200): a dictionary with 'documents' (list of document objects containing id, filename, size, text_length, uploaded_at) and 'count' (integer total number of documents). On error (HTTP 500): a dictionary with 'error' key containing error message string.
Dependencies
flasklogging
Required Imports
from flask import jsonify
from flask import session
import logging
Usage Example
# Client-side usage (JavaScript fetch example):
// GET request to the endpoint
fetch('/api/list-documents', {
method: 'GET',
credentials: 'include', // Include session cookie
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
console.log(`Found ${data.count} documents`);
data.documents.forEach(doc => {
console.log(`${doc.filename} (${doc.size} bytes, uploaded: ${doc.uploaded_at})`);
});
})
.catch(error => console.error('Error:', error));
# Server-side testing (Python):
import requests
with requests.Session() as s:
# Assume authentication is handled
response = s.get('http://localhost:5000/api/list-documents')
if response.status_code == 200:
data = response.json()
print(f"Documents: {data['count']}")
for doc in data['documents']:
print(f" - {doc['filename']}")
Best Practices
- This endpoint requires authentication via the @require_auth decorator - ensure users are authenticated before calling
- Documents are stored in Flask session which has size limitations - consider moving to database storage for production
- The endpoint returns text_length by calculating len(doc_info['text_content']) which could be memory-intensive for large documents
- Error handling catches all exceptions generically - consider more specific exception handling for production
- Session-based storage means documents are lost when session expires - implement persistent storage for production use
- The endpoint does not support pagination - may need to add pagination for users with many documents
- Consider adding query parameters for filtering/sorting documents by filename, date, or size
- Ensure proper CORS configuration if calling from a different domain
- The uploaded_at field format should be consistent (ISO 8601 recommended) for frontend parsing
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function api_list_documents_v1 94.5% similar
-
function api_list_documents 86.2% similar
-
function api_get_chat_uploaded_documents 83.5% similar
-
function get_documents_v1 81.5% similar
-
function api_remove_document_v1 73.3% similar