🔍 Code Extractor

function api_delete_chat_uploaded_document

Maturity: 50

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

File:
/tf/active/vicechatdev/vice_ai/complex_app.py
Lines:
2362 - 2374
Complexity:
simple

Purpose

This endpoint provides a RESTful API interface for authenticated users to delete their uploaded documents from the system. It validates user authentication, calls the document removal function, and returns appropriate HTTP responses. It's part of a document management system within a chat or RAG (Retrieval-Augmented Generation) application.

Source Code

def api_delete_chat_uploaded_document(doc_id):
    """Delete uploaded document"""
    try:
        user_email = get_user_email()
        if not user_email:
            return jsonify({'error': 'User not authenticated'}), 401
        
        remove_uploaded_document(user_email, doc_id)
        return jsonify({'message': 'Document deleted successfully'})
        
    except Exception as e:
        logger.error(f"Delete uploaded document error: {e}")
        return jsonify({'error': 'Failed to delete document'}), 500

Parameters

Name Type Default Kind
doc_id - - positional_or_keyword

Parameter Details

doc_id: String identifier for the document to be deleted. This is extracted from the URL path parameter and uniquely identifies the uploaded document in the system. Expected to be a valid document ID that exists for the authenticated user.

Return Value

Returns a Flask JSON response tuple. On success: (jsonify({'message': 'Document deleted successfully'}), 200). On authentication failure: (jsonify({'error': 'User not authenticated'}), 401). On server error: (jsonify({'error': 'Failed to delete document'}), 500). The response includes both a JSON object and an HTTP status code.

Dependencies

  • flask
  • logging

Required Imports

from flask import jsonify
import logging

Usage Example

# Client-side usage example (JavaScript fetch):
# DELETE request to remove a document
fetch('/api/chat-uploaded-documents/doc_12345', {
  method: 'DELETE',
  headers: {
    'Content-Type': 'application/json'
  },
  credentials: 'include'  // Include session cookies
})
.then(response => response.json())
.then(data => {
  if (data.message) {
    console.log('Document deleted:', data.message);
  } else if (data.error) {
    console.error('Error:', data.error);
  }
})
.catch(error => console.error('Request failed:', error));

# Server-side context (Flask app setup):
# from flask import Flask
# app = Flask(__name__)
# 
# @app.route('/api/chat-uploaded-documents/<doc_id>', methods=['DELETE'])
# @require_auth
# def api_delete_chat_uploaded_document(doc_id):
#     # Function implementation as shown

Best Practices

  • Always verify user authentication before performing delete operations
  • Use proper HTTP status codes (401 for unauthorized, 500 for server errors)
  • Log errors with sufficient detail for debugging while avoiding sensitive data exposure
  • Implement proper error handling with try-except blocks
  • Ensure the remove_uploaded_document function validates that the document belongs to the authenticated user to prevent unauthorized deletions
  • Consider implementing soft deletes instead of hard deletes for data recovery purposes
  • Add rate limiting to prevent abuse of the delete endpoint
  • Consider returning 404 if the document doesn't exist rather than 500
  • Implement CSRF protection for state-changing operations
  • Add audit logging for document deletion operations for compliance

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function api_remove_document_v1 86.6% similar

    Flask API endpoint that removes a user's uploaded document by document ID, with authentication required.

    From: /tf/active/vicechatdev/vice_ai/app.py
  • function api_remove_document 83.0% similar

    Flask API endpoint that removes an uploaded document from the session and deletes its associated file from the filesystem.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function api_get_chat_uploaded_documents 81.5% 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 api_delete_document 80.9% similar

    REST API endpoint that deletes a document from the application state after verifying the user's ownership and authentication.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function delete_document_v1 80.3% similar

    Flask API endpoint that deletes a document after verifying ownership and authentication.

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