🔍 Code Extractor

function api_list_documents

Maturity: 50

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.

File:
/tf/active/vicechatdev/vice_ai/complex_app.py
Lines:
694 - 715
Complexity:
moderate

Purpose

This endpoint serves as a REST API route to fetch all documents created by the currently authenticated user. It filters documents from the application state by matching the document author with the authenticated user's ID, then returns a JSON response containing document metadata. The function uses thread-safe locking to prevent race conditions when accessing shared document storage.

Source Code

def api_list_documents():
    """List all documents for the user"""
    try:
        user_id = get_user_id()
        with app_state['locks']['documents']:
            user_docs = [
                {
                    'id': doc.id,
                    'title': doc.title,
                    'author': doc.author,
                    'sections_count': len(doc.sections),
                    'created_at': doc.created_at.isoformat(),
                    'updated_at': doc.updated_at.isoformat()
                }
                for doc in app_state['documents'].values()
                if doc.author == user_id
            ]
        
        return jsonify({'documents': user_docs})
    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 {'documents': [list of document objects]}, where each document object contains: 'id' (document identifier), 'title' (document title), 'author' (user ID of creator), 'sections_count' (number of sections in document), 'created_at' (ISO format timestamp), 'updated_at' (ISO format timestamp). On error (HTTP 500), returns {'error': 'Failed to list documents'}.

Dependencies

  • flask
  • logging
  • threading

Required Imports

from flask import Flask
from flask import jsonify
from flask import session
import logging
from threading import Lock

Usage Example

# This is a Flask route endpoint, called via HTTP GET request
# Example using requests library:
import requests

# Assuming Flask app is running on localhost:5000
# and user is authenticated with valid session cookie
response = requests.get(
    'http://localhost:5000/api/documents',
    cookies={'session': 'valid_session_cookie'}
)

if response.status_code == 200:
    data = response.json()
    for doc in data['documents']:
        print(f"Document: {doc['title']}")
        print(f"  ID: {doc['id']}")
        print(f"  Sections: {doc['sections_count']}")
        print(f"  Created: {doc['created_at']}")
else:
    print(f"Error: {response.json()['error']}")

# Example response:
# {
#   'documents': [
#     {
#       'id': 'doc-123',
#       'title': 'My Document',
#       'author': 'user-456',
#       'sections_count': 5,
#       'created_at': '2024-01-15T10:30:00',
#       'updated_at': '2024-01-16T14:20:00'
#     }
#   ]
# }

Best Practices

  • This function must be called through HTTP GET request to '/api/documents' endpoint, not directly
  • User must be authenticated before calling this endpoint (enforced by require_auth decorator)
  • The function uses thread-safe locking when accessing shared app_state['documents'], ensuring data consistency in multi-threaded environments
  • Error handling catches all exceptions and returns user-friendly error messages while logging detailed errors
  • Document timestamps are converted to ISO format for consistent JSON serialization
  • Only documents where doc.author matches the authenticated user_id are returned, ensuring data isolation between users
  • The function filters documents in-memory, which may not scale well for large document collections - consider database pagination for production
  • Session management and authentication state should be properly configured before using this endpoint
  • Consider adding pagination parameters (limit, offset) for better performance with large document sets
  • The lock acquisition should be brief to avoid blocking other requests - current implementation is appropriate

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function api_list_documents_v1 87.8% similar

    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.

    From: /tf/active/vicechatdev/vice_ai/app.py
  • function api_list_documents_v2 86.2% 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 get_documents_v1 84.7% 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_get_document 78.6% similar

    Flask API endpoint that retrieves a specific document by ID, validates user access permissions, and returns the document data as JSON.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function api_get_chat_uploaded_documents 76.8% 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
← Back to Browse