function add_existing_data_section_to_document
Flask API endpoint that adds an existing data section to a document after verifying ownership and access permissions for both the document and data section.
/tf/active/vicechatdev/vice_ai/new_app.py
1486 - 1534
moderate
Purpose
This endpoint allows authenticated users to associate an existing data section with a document they own. It performs ownership verification for both resources, validates the request payload, and optionally allows specifying the position where the data section should be inserted in the document. The endpoint returns the updated document structure upon success.
Source Code
def add_existing_data_section_to_document(document_id):
"""Add a data section to a document"""
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:
data_section_id = data.get('data_section_id')
position = data.get('position') # Optional position
if not data_section_id:
return jsonify({'error': 'data_section_id is required'}), 400
# Verify data section exists and user has access
data_section = data_section_service.get_data_section(data_section_id)
if not data_section:
return jsonify({'error': 'Data section not found'}), 404
# Check ownership
if data_section.owner != user_email:
return jsonify({'error': 'Access denied to data section'}), 403
# Add data section to document using generic method
success = document_service.add_section_to_document(
document_id=document_id,
section_id=data_section_id,
section_type=SectionType.DATA,
position=position
)
if success:
# Get updated document
updated_document = document_service.get_document(document_id)
return jsonify({
'success': True,
'section_id': data_section_id,
'section_type': 'data',
'document': updated_document.to_dict() if updated_document else None
})
else:
return jsonify({'error': 'Failed to add data section to document'}), 500
except Exception as e:
logger.error(f"Error adding data section to 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 (passed as URL path parameter). Must correspond to an existing document owned by the authenticated user.
data_section_id: String identifier for the data section to add (passed in JSON request body). Required field that must reference an existing data section owned by the authenticated user.
position: Optional integer specifying where in the document's section list the data section should be inserted (passed in JSON request body). If not provided, the section is typically appended to the end.
Return Value
Returns a JSON response with different structures based on outcome: On success (200), returns {'success': True, 'section_id': str, 'section_type': 'data', 'document': dict} containing the updated document. On error, returns {'error': str} with appropriate HTTP status codes: 400 for validation errors or exceptions, 403 for access denied to data section, 404 for document not found or access denied, 500 for internal failures.
Dependencies
flasklogging
Required Imports
from flask import request, jsonify
import logging
from models import SectionType
from services import DocumentService, DataSectionService
Usage Example
# Client-side usage example (JavaScript fetch)
fetch('/api/documents/doc-123/data-sections/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer <token>'
},
body: JSON.stringify({
data_section_id: 'data-section-456',
position: 2 // Optional: insert at position 2
})
})
.then(response => response.json())
.then(data => {
if (data.success) {
console.log('Data section added:', data.section_id);
console.log('Updated document:', data.document);
} else {
console.error('Error:', data.error);
}
});
# Server-side test example (Python)
import requests
response = requests.post(
'https://api.example.com/api/documents/doc-123/data-sections/add',
json={'data_section_id': 'data-section-456', 'position': 2},
headers={'Authorization': 'Bearer <token>'}
)
result = response.json()
if result.get('success'):
print(f"Added section {result['section_id']} to document")
Best Practices
- Always verify both document and data section ownership before allowing the operation
- Include the 'data_section_id' field in the request body as it is required
- Handle all possible error responses (400, 403, 404, 500) appropriately in client code
- The 'position' parameter is optional; omit it to append the section to the end
- Ensure the user is authenticated before calling this endpoint (require_auth decorator enforces this)
- The endpoint returns the full updated document, which may be large; consider caching or partial updates for performance
- Check the 'success' field in the response to determine if the operation completed successfully
- The same data section can potentially be added to multiple documents if the business logic allows
- Error messages are logged server-side, so check logs for debugging internal failures
- The endpoint uses SectionType.DATA enum to specify the section type; ensure this enum value exists in your models
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function add_data_section_to_document 95.6% similar
-
function api_create_section 83.5% similar
-
function add_existing_section_to_document 83.5% similar
-
function create_data_section 80.3% similar
-
function update_data_section 79.2% similar