function create_text_section_for_document
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.
/tf/active/vicechatdev/vice_ai/new_app.py
1275 - 1393
moderate
Purpose
This endpoint provides a flexible interface for managing text sections within documents. It supports three distinct workflows: (1) creating a brand new text section with specified properties and adding it to a document, (2) linking an existing text section to a document, and (3) duplicating an existing section and adding the copy to a document. All operations include ownership verification to ensure users can only modify their own documents and sections.
Source Code
def create_text_section_for_document(document_id):
"""Create or add a text section to a document with multiple options"""
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:
action = data.get('action', 'create_new') # create_new, add_existing, duplicate_existing
position = data.get('position', -1)
if action == 'create_new':
# Create a new text section
title = data.get('title', 'Untitled Section')
section_type_str = data.get('type', 'text')
level = int(data.get('level', 1))
content = data.get('content', '')
# Parse section type
try:
section_type = SectionType(section_type_str)
except ValueError:
section_type = SectionType.TEXT
# Create text section
text_section = text_section_service.create_text_section(
owner=user_email,
title=title,
section_type=section_type,
level=level,
initial_content=content
)
# Add to document
document_service.add_text_section_to_document(
document_id=document_id,
text_section_id=text_section.id,
position=position
)
return jsonify({
'success': True,
'action': 'created',
'text_section': text_section.to_dict()
})
elif action == 'add_existing':
# Add existing section to document
text_section_id = data.get('text_section_id')
if not text_section_id:
return jsonify({'error': 'text_section_id is required for add_existing'}), 400
# Verify text section ownership
text_section = text_section_service.get_text_section(text_section_id)
if not text_section or text_section.owner != user_email:
return jsonify({'error': 'Text section not found or access denied'}), 404
success = document_service.add_text_section_to_document(
document_id=document_id,
text_section_id=text_section_id,
position=position
)
if success:
return jsonify({
'success': True,
'action': 'added_existing',
'text_section': text_section.to_dict()
})
else:
return jsonify({'error': 'Failed to add section to document'}), 500
elif action == 'duplicate_existing':
# Duplicate existing section and add to document
source_section_id = data.get('source_section_id')
new_title = data.get('title') # Optional custom title
if not source_section_id:
return jsonify({'error': 'source_section_id is required for duplicate_existing'}), 400
# Verify source section ownership
source_section = text_section_service.get_text_section(source_section_id)
if not source_section or source_section.owner != user_email:
return jsonify({'error': 'Source text section not found or access denied'}), 404
# Duplicate the section
duplicated_section = text_section_service.duplicate_text_section(
source_section_id,
user_email,
new_title or f"Copy of {source_section.title}"
)
if duplicated_section:
# Add to document
document_service.add_text_section_to_document(
document_id=document_id,
text_section_id=duplicated_section.id,
position=position
)
return jsonify({
'success': True,
'action': 'duplicated',
'text_section': duplicated_section.to_dict(),
'source_section_id': source_section_id
})
else:
return jsonify({'error': 'Failed to duplicate section'}), 500
else:
return jsonify({'error': f'Invalid action: {action}. Must be create_new, add_existing, or duplicate_existing'}), 400
except Exception as e:
logger.error(f"Error handling text section for 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 target document. Must be a valid document ID that exists in the system and is owned by the authenticated user. Passed as a URL path parameter.
data.action: String specifying the operation mode. Valid values: 'create_new' (default), 'add_existing', or 'duplicate_existing'. Determines which workflow to execute.
data.position: Integer specifying where to insert the section in the document's section list. Default is -1 (append to end). Zero-based index.
data.title: String title for the section. Used in 'create_new' mode (default: 'Untitled Section') and optionally in 'duplicate_existing' mode to override the duplicated title.
data.type: String representing the section type. Used in 'create_new' mode. Default is 'text'. Must match a valid SectionType enum value.
data.level: Integer or string representing the heading level. Used in 'create_new' mode. Default is 1. Converted to integer internally.
data.content: String containing the initial content for the section. Used in 'create_new' mode. Default is empty string.
data.text_section_id: String identifier for an existing text section. Required when action is 'add_existing'. Must be owned by the authenticated user.
data.source_section_id: String identifier for the section to duplicate. Required when action is 'duplicate_existing'. Must be owned by the authenticated user.
Return Value
Returns a JSON response tuple with (response_body, status_code). Success responses (200) include: {'success': True, 'action': <action_performed>, 'text_section': <section_dict>}. For 'duplicated' action, also includes 'source_section_id'. Error responses include: 404 for document/section not found or access denied, 400 for invalid parameters or action, 500 for operation failures. Error format: {'error': <error_message>}.
Dependencies
flaskloggingmodelsservices
Required Imports
from flask import request, jsonify
from models import SectionType
import logging
Usage Example
# Example 1: Create new text section
import requests
response = requests.post(
'http://localhost:5000/api/documents/doc123/text_sections',
headers={'Authorization': 'Bearer <token>'},
json={
'action': 'create_new',
'title': 'Introduction',
'type': 'text',
'level': 1,
'content': 'This is the introduction section.',
'position': 0
}
)
result = response.json()
# Returns: {'success': True, 'action': 'created', 'text_section': {...}}
# Example 2: Add existing section
response = requests.post(
'http://localhost:5000/api/documents/doc123/sections',
headers={'Authorization': 'Bearer <token>'},
json={
'action': 'add_existing',
'text_section_id': 'section456',
'position': 1
}
)
# Example 3: Duplicate section
response = requests.post(
'http://localhost:5000/api/documents/doc123/text-sections',
headers={'Authorization': 'Bearer <token>'},
json={
'action': 'duplicate_existing',
'source_section_id': 'section789',
'title': 'Copy of Methods',
'position': -1
}
)
Best Practices
- Always verify document and section ownership before performing operations to prevent unauthorized access
- Use the 'action' parameter to clearly specify the intended operation mode
- Handle all three action types appropriately in client code based on use case
- Provide meaningful error handling for 404, 400, and 500 status codes
- When using 'add_existing', ensure the text_section_id exists and is owned by the user
- When using 'duplicate_existing', provide a custom title to distinguish the copy from the original
- Position parameter of -1 appends to the end; use specific indices for precise placement
- Validate SectionType values match the enum before sending requests
- The endpoint supports three different URL patterns for backward compatibility
- Ensure authentication token is valid before making requests
- Log errors appropriately for debugging and monitoring
- Consider transaction rollback mechanisms if section creation fails after document update
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function add_existing_section_to_document 89.1% similar
-
function create_text_section 87.9% similar
-
function api_create_section 83.9% similar
-
function add_data_section_to_document 82.7% similar
-
function get_document_text_sections 78.8% similar