🔍 Code Extractor

function api_get_chat_uploaded_documents

Maturity: 50

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

File:
/tf/active/vicechatdev/vice_ai/complex_app.py
Lines:
2335 - 2358
Complexity:
simple

Purpose

This endpoint serves as a REST API to fetch metadata about documents that a user has uploaded for use in chat sessions. It authenticates the user, retrieves their uploaded documents from storage, and returns a sanitized list containing document IDs, names, file types, upload timestamps, and content lengths. This is typically used to display available documents in a chat interface or document management UI.

Source Code

def api_get_chat_uploaded_documents():
    """Get user's uploaded documents for chat"""
    try:
        user_email = get_user_email()
        if not user_email:
            return jsonify({'error': 'User not authenticated'}), 401
        
        documents = get_user_uploaded_documents(user_email)
        doc_list = []
        
        for doc_id, doc_info in documents.items():
            doc_list.append({
                'id': doc_id,
                'name': doc_info['name'],
                'file_type': doc_info['file_type'],
                'upload_time': doc_info['upload_time'],
                'content_length': len(doc_info['content'])
            })
        
        return jsonify({'documents': doc_list})
        
    except Exception as e:
        logger.error(f"Get uploaded documents error: {e}")
        return jsonify({'error': 'Failed to retrieve documents'}), 500

Return Value

Returns a Flask JSON response. On success (200): {'documents': [{'id': str, 'name': str, 'file_type': str, 'upload_time': str, 'content_length': int}, ...]}. On authentication failure (401): {'error': 'User not authenticated'}. On server error (500): {'error': 'Failed to retrieve documents'}.

Dependencies

  • flask
  • logging

Required Imports

from flask import jsonify
import logging

Usage Example

# Client-side usage example (JavaScript fetch)
fetch('/api/chat-uploaded-documents', {
  method: 'GET',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer <token>'  // If using token auth
  },
  credentials: 'include'  // If using session cookies
})
.then(response => response.json())
.then(data => {
  if (data.documents) {
    data.documents.forEach(doc => {
      console.log(`Document: ${doc.name}, Type: ${doc.file_type}, Size: ${doc.content_length}`);
    });
  }
})
.catch(error => console.error('Error:', error));

# Server-side test example (Python)
import requests
response = requests.get(
  'http://localhost:5000/api/chat-uploaded-documents',
  cookies={'session': 'your_session_cookie'}
)
if response.status_code == 200:
  documents = response.json()['documents']
  for doc in documents:
    print(f"ID: {doc['id']}, Name: {doc['name']}")

Best Practices

  • Always ensure the require_auth decorator is properly implemented to prevent unauthorized access
  • The function returns content_length instead of full document content to optimize response size and performance
  • Error logging is implemented for debugging failed document retrieval attempts
  • The function uses try-except to gracefully handle errors and return appropriate HTTP status codes
  • User email is validated before attempting to retrieve documents
  • Document IDs should be treated as sensitive data and validated before use in subsequent operations
  • Consider implementing pagination if users can have large numbers of documents
  • The get_user_uploaded_documents function should implement proper access control to ensure users only see their own documents
  • Consider adding rate limiting to prevent abuse of this endpoint
  • Document metadata should be cached if this endpoint is called frequently

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function api_list_documents_v1 84.2% 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_chat_upload_document 84.1% similar

    Flask API endpoint that handles document upload for chat context, processes the document to extract text content, and stores it for later retrieval in chat sessions.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function api_list_documents_v2 83.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_delete_chat_uploaded_document 81.5% similar

    Flask API endpoint that deletes a user's uploaded document by document ID, requiring authentication and returning success/error responses.

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