🔍 Code Extractor

function get_document_v3

Maturity: 48

Flask API endpoint that retrieves all versions of a specific document, verifying user ownership before returning the version history.

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
1176 - 1194
Complexity:
moderate

Purpose

This endpoint provides version control functionality for documents in a document management system. It authenticates the user, verifies they own the requested document, and returns all historical versions of that document. This is useful for tracking document changes, implementing rollback functionality, and maintaining audit trails.

Source Code

def get_document_versions(document_id):
    """Get all versions of a document"""
    user_email = get_current_user()
    
    # 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:
        versions = document_service.get_document_versions(document_id)
        return jsonify({
            'versions': versions,
            'count': len(versions)
        })
        
    except Exception as e:
        logger.error(f"Error getting document versions: {e}")
        return jsonify({'error': str(e)}), 500

Parameters

Name Type Default Kind
document_id - - positional_or_keyword

Parameter Details

document_id: String identifier for the document whose versions are being requested. This is extracted from the URL path parameter. Must correspond to an existing document in the system that the authenticated user owns.

Return Value

Returns a Flask JSON response. On success (200): {'versions': list of version objects, 'count': integer number of versions}. On document not found or access denied (404): {'error': 'Document not found or access denied'}. On server error (500): {'error': error message string}. The versions list structure depends on the document_service.get_document_versions implementation.

Dependencies

  • flask
  • logging

Required Imports

from flask import jsonify
import logging

Usage Example

# Assuming Flask app setup with authentication
# GET request to: /api/documents/doc-123-abc/versions
# Headers: Authorization token (handled by require_auth decorator)

# Example response on success:
# {
#   "versions": [
#     {"version_id": "v1", "created_at": "2024-01-01T10:00:00", "author": "user@example.com"},
#     {"version_id": "v2", "created_at": "2024-01-02T15:30:00", "author": "user@example.com"}
#   ],
#   "count": 2
# }

# Example client-side usage:
import requests

response = requests.get(
    'https://api.example.com/api/documents/doc-123-abc/versions',
    headers={'Authorization': 'Bearer <token>'}
)

if response.status_code == 200:
    data = response.json()
    print(f"Found {data['count']} versions")
    for version in data['versions']:
        print(version)
else:
    print(f"Error: {response.json()['error']}")

Best Practices

  • Always verify document ownership before returning sensitive data to prevent unauthorized access
  • Use proper HTTP status codes (404 for not found, 500 for server errors)
  • Log errors with sufficient context for debugging while avoiding sensitive data in logs
  • The function combines authorization check (ownership verification) with the main operation, which is appropriate for security
  • Consider adding pagination for documents with many versions to improve performance
  • The error message 'Document not found or access denied' intentionally doesn't distinguish between non-existent documents and access denial to prevent information leakage
  • Ensure the document_service methods handle database connections properly and use transactions where appropriate
  • Consider adding rate limiting to prevent abuse of the API endpoint
  • The require_auth decorator should validate and refresh tokens as needed

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_document_v4 82.8% similar

    Flask API endpoint that retrieves a specific document with its text and data sections, including optional sharing information, for authenticated users.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function revert_document_to_version 79.8% similar

    Flask API endpoint that reverts a document to a specific previous version after verifying user ownership and authentication.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function create_document_v7 79.1% similar

    Flask API endpoint that creates a new version of an existing document with an optional change summary, verifying document ownership before creation.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function get_text_section_versions 78.0% similar

    Flask API endpoint that retrieves all historical versions of a specific text section, with ownership verification and authentication required.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function api_get_document 71.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
← Back to Browse