🔍 Code Extractor

function api_create_section

Maturity: 50

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.

File:
/tf/active/vicechatdev/vice_ai/complex_app.py
Lines:
820 - 880
Complexity:
moderate

Purpose

This endpoint allows authenticated users to add new sections to documents they own. It validates document existence and user permissions, creates a DocumentSection object with a unique ID, inserts it at a specified position (or appends to the end), and persists the changes. It handles edge cases like undefined level values and invalid positions, providing comprehensive logging throughout the process.

Source Code

def api_create_section(doc_id):
    """Create a new section in a document"""
    try:
        logger.info(f"🔵 POST /api/documents/{doc_id}/sections - Create section request received")
        document = get_document(doc_id)
        if not document:
            logger.warning(f"🔵 Document not found: {doc_id}")
            return jsonify({'error': 'Document not found'}), 404
        
        if document.author != get_user_id():
            logger.warning(f"🔵 Access denied for user: {get_user_id()}")
            return jsonify({'error': 'Access denied'}), 403
        
        data = request.get_json()
        logger.info(f"🔵 Request data: {data}")
        
        section_id = str(uuid.uuid4())
        
        # Handle level parameter properly
        section_type = data.get('type', 'text')
        level = data.get('level', 1)  # Default to 1 if not provided
        
        # Ensure level is always an integer
        if level is None or level == 'undefined':
            level = 1
        
        section = DocumentSection(
            section_id,
            section_type,
            level,
            data.get('title', ''),
            data.get('content', '')
        )
        
        logger.info(f"🔵 Created section: {section.to_dict()}")
        
        # Insert at specified position or at the end
        position = data.get('position')
        if position is None:
            position = len(document.sections)
        
        logger.info(f"🔵 Position: {position}, Current sections count: {len(document.sections)}")
        
        if 0 <= position <= len(document.sections):
            document.sections.insert(position, section)
            logger.info(f"🔵 Inserted section at position {position}")
        else:
            document.sections.append(section)
            logger.info(f"🔵 Appended section to end")
        
        save_document(document)
        logger.info(f"🔵 Document saved with {len(document.sections)} sections")
        
        return jsonify({
            'section': section.to_dict(),
            'message': 'Section created successfully'
        })
    except Exception as e:
        logger.error(f"🔴 Create section error: {e}")
        logger.exception("🔴 Full exception:")
        return jsonify({'error': 'Failed to create section'}), 500

Parameters

Name Type Default Kind
doc_id - - positional_or_keyword

Parameter Details

doc_id: String identifier of the document to which the section will be added. Used to retrieve the document from storage and validate user access. Expected to be a valid document ID that exists in the system.

Return Value

Returns a JSON response with HTTP status code. On success (200): {'section': dict, 'message': str} containing the created section's dictionary representation and success message. On document not found (404): {'error': 'Document not found'}. On access denied (403): {'error': 'Access denied'}. On server error (500): {'error': 'Failed to create section'}. The section dictionary includes section_id, type, level, title, and content fields.

Dependencies

  • flask
  • uuid
  • logging

Required Imports

from flask import jsonify
from flask import request
import uuid
import logging

Usage Example

# Example API call using requests library
import requests

# Assuming authentication is handled via session cookies
session = requests.Session()
# ... perform authentication to get session ...

doc_id = 'abc-123-def-456'
url = f'http://localhost:5000/api/documents/{doc_id}/sections'

payload = {
    'type': 'text',
    'level': 2,
    'title': 'Introduction',
    'content': 'This is the introduction section.',
    'position': 0  # Insert at beginning
}

response = session.post(url, json=payload)

if response.status_code == 200:
    result = response.json()
    print(f"Section created: {result['section']['section_id']}")
    print(f"Message: {result['message']}")
else:
    print(f"Error: {response.json()['error']}")

Best Practices

  • Always include authentication credentials when calling this endpoint
  • Ensure the user is the document author before attempting to create sections
  • Provide a valid 'level' parameter (integer) to avoid defaulting to 1
  • Use 'position' parameter to control where the section is inserted; omit to append to end
  • Handle all possible HTTP status codes (200, 403, 404, 500) in client code
  • The 'type' parameter defaults to 'text' if not provided
  • Section IDs are automatically generated as UUIDs; do not provide custom IDs
  • The function handles edge cases like 'undefined' or None level values by defaulting to 1
  • Position validation ensures sections are inserted within valid bounds or appended
  • Check response for both 'section' data and 'message' on success

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function add_data_section_to_document 86.1% similar

    Flask API endpoint that adds a data section to a document, either by creating a new data section or linking an existing one, with ownership verification.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function create_data_section 84.8% similar

    Flask API endpoint that creates a new data section for authenticated users, accepting title and description from JSON request body.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function api_update_section 84.7% 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_delete_section 84.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
  • function create_text_section_for_document 83.9% similar

    Flask API endpoint that creates or adds text sections to a document with three action modes: creating new sections, adding existing sections, or duplicating existing sections.

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