🔍 Code Extractor

function update_document_v2

Maturity: 50

Flask API endpoint that updates a document's title and/or description after verifying user ownership and authentication.

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
1078 - 1113
Complexity:
moderate

Purpose

This function serves as a RESTful API endpoint for updating document metadata (title and description). It enforces ownership verification to ensure only the document owner can make modifications, updates the timestamp, and persists changes to the database. It's part of a document management system with authentication and authorization controls.

Source Code

def update_document(document_id):
    """Update document title or description"""
    user_email = get_current_user()
    data = request.get_json()
    
    # Verify document ownership
    document = document_service.get_document(document_id)
    if not document or document.owner != user_email:
        return jsonify({'error': 'Document not found or access denied'}), 404
    
    try:
        title = data.get('title')
        description = data.get('description')
        
        if title is not None:
            document.title = title.strip()
        
        if description is not None:
            document.description = description.strip()
        
        document.updated_at = datetime.now()
        
        # Save the updated document
        success = document_service.db.save_document(document)
        
        if success:
            return jsonify({
                'success': True,
                'document': document.to_dict()
            })
        else:
            return jsonify({'error': 'Failed to update document'}), 500
            
    except Exception as e:
        logger.error(f"Error updating document: {e}")
        return jsonify({'error': str(e)}), 400

Parameters

Name Type Default Kind
document_id - - positional_or_keyword

Parameter Details

document_id: String identifier for the document to be updated. Passed as a URL path parameter in the route '/api/documents/<document_id>'. Used to retrieve and verify the specific document from the database.

Return Value

Returns a Flask JSON response tuple. On success (200): {'success': True, 'document': <document_dict>} containing the updated document data. On not found/unauthorized (404): {'error': 'Document not found or access denied'}. On update failure (500): {'error': 'Failed to update document'}. On exception (400): {'error': <error_message>}.

Dependencies

  • flask
  • datetime
  • logging

Required Imports

from flask import request, jsonify
from datetime import datetime
import logging

Usage Example

# Client-side usage example (JavaScript fetch)
fetch('/api/documents/doc123', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer <token>'
  },
  body: JSON.stringify({
    title: 'Updated Document Title',
    description: 'Updated description text'
  })
})
.then(response => response.json())
.then(data => {
  if (data.success) {
    console.log('Document updated:', data.document);
  } else {
    console.error('Error:', data.error);
  }
});

# Server-side context (Flask app setup)
# app = Flask(__name__)
# document_service = DocumentService()
# logger = logging.getLogger(__name__)
# The function is automatically called when PUT request is made to the route

Best Practices

  • Always verify document ownership before allowing updates to prevent unauthorized access
  • Strip whitespace from title and description inputs to maintain data consistency
  • Update the updated_at timestamp whenever document metadata changes for audit trails
  • Use try-except blocks to handle potential errors gracefully and return appropriate HTTP status codes
  • Return detailed error messages in the response body while logging full exception details server-side
  • Validate that the document exists before attempting updates to avoid null reference errors
  • Use the require_auth decorator to ensure only authenticated users can access this endpoint
  • Consider adding input validation for title/description length limits and content sanitization
  • The function allows partial updates (only title, only description, or both) by checking if fields are not None
  • HTTP status codes follow REST conventions: 200 for success, 404 for not found, 400 for bad request, 500 for server errors

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function api_update_document 89.5% similar

    Flask API endpoint that updates document metadata (title and custom metadata fields) for a specific document, with authentication and authorization checks.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function api_update_section 78.8% similar

    REST API endpoint that updates an existing section within a document, allowing modification of title, content, type, and level properties with authentication and authorization checks.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function api_create_document 77.9% similar

    Flask API endpoint that creates a new document with a title and author, returning the created document's details as JSON.

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

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

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function update_text_section 76.7% similar

    Flask API endpoint that updates either the title or content of a text section, with ownership verification and version tracking.

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