function api_delete_section
Flask API endpoint that deletes a specific section from a document after validating user authorization and document existence.
/tf/active/vicechatdev/vice_ai/complex_app.py
923 - 942
moderate
Purpose
This function serves as a RESTful API endpoint to remove a section from a document. It performs authorization checks to ensure only the document author can delete sections, validates the existence of both the document and section, and handles the deletion operation with appropriate error responses. It's part of a document management system with section-based content organization.
Source Code
def api_delete_section(doc_id, section_id):
"""Delete a section"""
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
success = document.remove_section(section_id)
if not success:
return jsonify({'error': 'Section not found'}), 404
save_document(document)
return jsonify({'message': 'Section deleted successfully'})
except Exception as e:
logger.error(f"Delete section error: {e}")
return jsonify({'error': 'Failed to delete 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 deleted. Extracted from the URL path parameter. Used to retrieve the target document from storage.
section_id: String identifier for the specific section to be deleted within the document. Extracted from the URL path parameter. Passed to the document's remove_section method to identify which section to remove.
Return Value
Returns a Flask JSON response tuple. On success: (jsonify({'message': 'Section deleted successfully'}), 200). On document not found: (jsonify({'error': 'Document not found'}), 404). On unauthorized access: (jsonify({'error': 'Access denied'}), 403). On section not found: (jsonify({'error': 'Section not found'}), 404). On exception: (jsonify({'error': 'Failed to delete section'}), 500). Each return is a tuple of (Response object, HTTP status code).
Dependencies
flasklogging
Required Imports
from flask import jsonify
Usage Example
# Example usage as API endpoint
# Assuming Flask app is running with proper authentication
# Client-side request (using requests library):
import requests
# User must be authenticated with valid session
session = requests.Session()
# ... perform login to get authenticated session ...
# Delete a section from a document
doc_id = 'doc_12345'
section_id = 'section_67890'
response = session.delete(
f'http://localhost:5000/api/documents/{doc_id}/sections/{section_id}'
)
if response.status_code == 200:
print(response.json()) # {'message': 'Section deleted successfully'}
elif response.status_code == 403:
print('Access denied - not the document author')
elif response.status_code == 404:
print('Document or section not found')
else:
print('Error:', response.json())
Best Practices
- Always authenticate requests using the require_auth decorator before allowing section deletion
- Verify document ownership before allowing modifications to prevent unauthorized access
- Use try-except blocks to catch and log exceptions for debugging and monitoring
- Return appropriate HTTP status codes (404 for not found, 403 for forbidden, 500 for server errors)
- Save document changes immediately after successful section removal to persist the state
- Log errors with sufficient context for troubleshooting production issues
- Validate both document and section existence before attempting deletion
- Use consistent error response format across all API endpoints for client predictability
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function delete_data_section 86.5% similar
-
function api_create_section 84.0% similar
-
function delete_text_section 82.6% similar
-
function api_update_section 81.5% similar
-
function api_delete_document 79.9% similar