🔍 Code Extractor

function api_remove_document_v1

Maturity: 48

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

File:
/tf/active/vicechatdev/vice_ai/app.py
Lines:
1430 - 1443
Complexity:
simple

Purpose

This endpoint provides a RESTful DELETE API for removing documents from a user's collection. It authenticates the user via session, retrieves their email, calls a document removal function, and returns appropriate JSON responses with success/error messages and HTTP status codes.

Source Code

def api_remove_document(document_id):
    """Remove an uploaded document"""
    try:
        user_email = session['user'].get('email', 'unknown')
        
        if remove_user_document(user_email, document_id):
            logger.info(f"Document removed: {document_id} for user {user_email}")
            return jsonify({'message': 'Document removed successfully'})
        else:
            return jsonify({'error': 'Document not found'}), 404
            
    except Exception as e:
        logger.error(f"Remove document error: {e}")
        return jsonify({'error': 'Failed to remove document'}), 500

Parameters

Name Type Default Kind
document_id - - positional_or_keyword

Parameter Details

document_id: String identifier for the document to be removed. This is extracted from the URL path parameter and passed to the remove_user_document function to locate and delete the specific document associated with the authenticated user.

Return Value

Returns a Flask JSON response object. On success (200): {'message': 'Document removed successfully'}. On document not found (404): {'error': 'Document not found'}. On server error (500): {'error': 'Failed to remove document'}. Each response includes appropriate HTTP status code.

Dependencies

  • flask
  • logging

Required Imports

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

Usage Example

# Assuming Flask app setup with authentication
# Client-side usage (JavaScript fetch example):
fetch('/api/remove-document/doc123', {
  method: 'DELETE',
  credentials: 'include',
  headers: {
    'Content-Type': 'application/json'
  }
})
.then(response => response.json())
.then(data => {
  if (data.message) {
    console.log('Document removed:', data.message);
  } else {
    console.error('Error:', data.error);
  }
})
.catch(error => console.error('Request failed:', error));

Best Practices

  • Ensure the require_auth decorator is properly implemented to prevent unauthorized access
  • The remove_user_document function should validate that the document belongs to the requesting user to prevent unauthorized deletion
  • Consider adding rate limiting to prevent abuse of the deletion endpoint
  • Implement proper logging for audit trails of document deletions
  • Ensure session['user'] is properly populated by authentication middleware
  • Handle edge cases where session['user'] might not contain 'email' field
  • Consider implementing soft deletes instead of hard deletes for data recovery
  • Add CSRF protection for production environments
  • Validate document_id format to prevent injection attacks

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function api_remove_document 91.6% 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_delete_chat_uploaded_document 86.6% 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 delete_document_v1 83.9% similar

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

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function api_delete_document 83.6% 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 api_delete_section 79.0% similar

    Flask API endpoint that deletes a specific section from a document after validating user authorization and document existence.

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