🔍 Code Extractor

function api_list_documents_v1

Maturity: 50

Flask API endpoint that retrieves and returns a list of all documents uploaded by the currently authenticated user, including metadata such as filename, size, and creation date.

File:
/tf/active/vicechatdev/vice_ai/app.py
Lines:
1447 - 1469
Complexity:
simple

Purpose

This endpoint serves as a document management API that allows authenticated users to view their uploaded documents. It fetches user-specific documents from storage, formats the metadata into a standardized response structure, and returns it as JSON. This is typically used in document management interfaces, dashboards, or file browsers where users need to see their uploaded content.

Source Code

def api_list_documents():
    """List all uploaded documents for the current user"""
    try:
        user_email = session['user'].get('email', 'unknown')
        documents = get_user_documents(user_email)
        
        # Format response
        doc_list = []
        for doc_id, doc_info in documents.items():
            doc_list.append({
                'id': doc_id,
                'filename': doc_info['metadata'].get('original_filename', 'Unknown'),
                'size': doc_info['metadata'].get('size', 0),
                'text_length': len(doc_info['text_content']),
                'created_at': doc_info['created_at'].isoformat(),
                'file_type': doc_info['metadata'].get('file_type', 'unknown')
            })
        
        return jsonify({'documents': 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 object. On success (HTTP 200), returns a dictionary with key 'documents' containing a list of document objects. Each document object includes: 'id' (document identifier), 'filename' (original filename), 'size' (file size in bytes), 'text_length' (length of extracted text content), 'created_at' (ISO format timestamp), and 'file_type' (document type). On error (HTTP 500), returns a dictionary with key 'error' containing an error message string.

Dependencies

  • flask
  • logging
  • datetime

Required Imports

from flask import Flask
from flask import jsonify
from flask import session
import logging

Usage Example

# Client-side usage example (JavaScript fetch)
fetch('/api/list-documents', {
  method: 'GET',
  credentials: 'include',
  headers: {
    'Content-Type': 'application/json'
  }
})
.then(response => response.json())
.then(data => {
  console.log('User documents:', data.documents);
  data.documents.forEach(doc => {
    console.log(`${doc.filename} (${doc.size} bytes) - ${doc.file_type}`);
  });
})
.catch(error => console.error('Error:', error));

# Python client usage example
import requests

session = requests.Session()
# Assume user is already authenticated and session cookies are set
response = session.get('http://localhost:5000/api/list-documents')

if response.status_code == 200:
    documents = response.json()['documents']
    for doc in documents:
        print(f"ID: {doc['id']}, Name: {doc['filename']}, Size: {doc['size']}")
else:
    print(f"Error: {response.json()['error']}")

Best Practices

  • Ensure the @require_auth decorator is properly implemented to prevent unauthorized access
  • The function assumes session['user']['email'] exists; ensure authentication middleware properly populates this
  • Consider implementing pagination for users with large numbers of documents to avoid performance issues
  • The function catches all exceptions broadly; consider more specific exception handling for better error diagnostics
  • Ensure get_user_documents() function properly isolates user data to prevent data leakage between users
  • Consider adding query parameters for filtering, sorting, or pagination in future enhancements
  • The text_length field exposes the length of document content; ensure this doesn't leak sensitive information
  • Implement rate limiting on this endpoint to prevent abuse
  • Consider caching document lists for frequently accessed user data to improve performance
  • Ensure proper logging configuration to capture errors without exposing sensitive user information

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function api_list_documents_v2 94.5% similar

    Flask API endpoint that retrieves and returns a list of all documents uploaded by the currently authenticated user from their session storage.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function api_list_documents 87.8% similar

    Flask API endpoint that retrieves and returns a list of all documents belonging to the authenticated user, including metadata like title, author, section count, and timestamps.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function api_get_chat_uploaded_documents 84.2% similar

    Flask API endpoint that retrieves a list of documents uploaded by the authenticated user for chat functionality, returning document metadata without full content.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function get_documents_v1 81.2% similar

    Flask API endpoint that retrieves all documents belonging to the currently authenticated user and returns them as JSON.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function api_upload_document_v1 74.7% similar

    Flask API endpoint that handles document file uploads, validates file type and size, stores the file temporarily, and extracts basic text content for processing.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
← Back to Browse