🔍 Code Extractor

function api_move_section

Maturity: 52

Flask API endpoint that moves a document section up or down in the section order, with authentication and authorization checks.

File:
/tf/active/vicechatdev/vice_ai/complex_app.py
Lines:
946 - 974
Complexity:
moderate

Purpose

This endpoint allows authenticated users to reorder sections within their documents by moving a specific section either up or down in the sequence. It validates document ownership, checks the move direction, performs the move operation, persists the changes, and returns the updated document structure.

Source Code

def api_move_section(doc_id, section_id):
    """Move a section up or down"""
    try:
        document = get_document(doc_id)
        if not document:
            return jsonify({'error': 'Document not found'}), 404
        
        if document.author != get_user_id():
            return jsonify({'error': 'Access denied'}), 403
        
        data = request.get_json()
        direction = data.get('direction', 'down')
        
        if direction not in ['up', 'down']:
            return jsonify({'error': 'Invalid direction'}), 400
        
        success = document.move_section(section_id, direction)
        if not success:
            return jsonify({'error': 'Cannot move section'}), 400
        
        save_document(document)
        
        return jsonify({
            'document': document.to_dict(),
            'message': f'Section moved {direction} successfully'
        })
    except Exception as e:
        logger.error(f"Move section error: {e}")
        return jsonify({'error': 'Failed to move section'}), 500

Parameters

Name Type Default Kind
doc_id - - positional_or_keyword
section_id - - positional_or_keyword

Parameter Details

doc_id: String identifier for the document containing the section to be moved. Extracted from the URL path. Used to retrieve the document from storage.

section_id: String identifier for the specific section within the document that should be moved. Extracted from the URL path. Used to identify which section to reorder.

Return Value

Returns a Flask JSON response tuple. On success (200): JSON object with 'document' key containing the full updated document dictionary and 'message' key with success message. On error: JSON object with 'error' key and appropriate HTTP status code (404 for document not found, 403 for access denied, 400 for invalid direction or unmovable section, 500 for server errors).

Dependencies

  • flask
  • logging

Required Imports

from flask import request
from flask import jsonify
import logging

Usage Example

# Client-side usage example (JavaScript fetch)
fetch('/api/documents/doc123/sections/section456/move', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer <token>'
  },
  body: JSON.stringify({
    direction: 'up'
  })
})
.then(response => response.json())
.then(data => {
  if (data.document) {
    console.log('Section moved successfully:', data.message);
    console.log('Updated document:', data.document);
  } else {
    console.error('Error:', data.error);
  }
});

# Python requests example
import requests

response = requests.post(
  'http://localhost:5000/api/documents/doc123/sections/section456/move',
  json={'direction': 'down'},
  headers={'Authorization': 'Bearer <token>'}
)
result = response.json()
if response.status_code == 200:
  print(f"Success: {result['message']}")
  updated_doc = result['document']
else:
  print(f"Error: {result['error']}")

Best Practices

  • Always validate document ownership before allowing modifications to prevent unauthorized access
  • Use try-except blocks to catch and log exceptions for debugging and error tracking
  • Validate input direction parameter against allowed values to prevent invalid operations
  • Return appropriate HTTP status codes (404, 403, 400, 500) to clearly communicate error types to clients
  • Persist document changes immediately after successful operations to prevent data loss
  • Include descriptive error messages in responses to help clients understand what went wrong
  • Log errors with sufficient context for troubleshooting production issues
  • The endpoint expects JSON request body with 'direction' field set to either 'up' or 'down'
  • Ensure the Document class's move_section method handles edge cases (first/last section) and returns False when move is not possible
  • Consider adding rate limiting to prevent abuse of the endpoint
  • The require_auth decorator must be properly implemented to ensure only authenticated users can access this endpoint

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function move_section 93.7% similar

    Flask API endpoint that moves a section (text or data) up or down within a document's section order, with authentication and ownership verification.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function api_update_section 80.1% 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_section 79.6% similar

    Flask API endpoint that creates a new section within a specified document, handling section positioning, type, level, title, and content with proper authentication and authorization checks.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function api_delete_section 76.8% 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
  • function api_replace_section_content 72.8% similar

    API endpoint that replaces the content of a specific section within a document, storing the old content for potential undo operations and updating the section's timestamp.

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