🔍 Code Extractor

function api_create_document

Maturity: 48

Flask API endpoint that creates a new document with a title and author, returning the created document's details as JSON.

File:
/tf/active/vicechatdev/vice_ai/complex_app.py
Lines:
719 - 748
Complexity:
moderate

Purpose

This is a REST API endpoint that handles POST requests to create new documents in the system. It extracts the title from the request JSON payload, retrieves the authenticated user ID as the author, validates the input, creates the document using a helper function, and returns the created document's details. It includes comprehensive logging for debugging and error handling for robustness.

Source Code

def api_create_document():
    """Create a new document"""
    try:
        logger.info("🔵 POST /api/documents - Create document request received")
        data = request.get_json()
        logger.info(f"🔵 Request data: {data}")
        
        title = data.get('title', 'Untitled Document').strip()
        author = get_user_id()
        
        logger.info(f"🔵 Creating document with title: '{title}', author: '{author}'")
        
        if not title:
            logger.warning("🔵 Title is empty, returning error")
            return jsonify({'error': 'Title cannot be empty'}), 400
        
        document = create_document(title, author)
        logger.info(f"🔵 Document created successfully: {document.id}")
        
        result = {
            'document': document.to_dict(),
            'message': 'Document created successfully'
        }
        logger.info(f"🔵 Returning result: {result}")
        
        return jsonify(result)
    except Exception as e:
        logger.error(f"🔴 Create document error: {e}")
        logger.exception("🔴 Full exception:")
        return jsonify({'error': 'Failed to create document'}), 500

Return Value

Returns a JSON response with two possible outcomes: (1) Success (200): {'document': <document_dict>, 'message': 'Document created successfully'} where document_dict contains the serialized document object with fields like id, title, author, etc. (2) Error (400): {'error': 'Title cannot be empty'} if validation fails. (3) Error (500): {'error': 'Failed to create document'} if an exception occurs during creation.

Dependencies

  • flask
  • logging
  • uuid
  • datetime
  • threading
  • os
  • json
  • time
  • re
  • html
  • werkzeug
  • tempfile
  • zipfile
  • io
  • markdown
  • python-docx
  • reportlab

Required Imports

from flask import Flask
from flask import request
from flask import jsonify
from flask import session
import logging

Usage Example

# Example client-side usage (JavaScript fetch):
fetch('/api/documents', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer <token>'  // if using token auth
  },
  body: JSON.stringify({
    title: 'My New Document'
  })
})
.then(response => response.json())
.then(data => {
  console.log('Created document:', data.document);
  console.log('Document ID:', data.document.id);
})
.catch(error => console.error('Error:', error));

# Example using Python requests:
import requests

response = requests.post(
  'http://localhost:5000/api/documents',
  json={'title': 'My New Document'},
  cookies={'session': '<session_cookie>'}  # or headers for auth
)

if response.status_code == 200:
  document = response.json()['document']
  print(f"Created document with ID: {document['id']}")
else:
  print(f"Error: {response.json()['error']}")

Best Practices

  • Always send a valid JSON payload with Content-Type: application/json header
  • Ensure user is authenticated before calling this endpoint (require_auth decorator enforces this)
  • Handle both success and error responses appropriately in client code
  • The title field is optional but will be validated - empty strings after stripping will be rejected
  • Check HTTP status codes: 200 for success, 400 for validation errors, 500 for server errors
  • The function uses extensive logging with emoji prefixes (🔵 for info, 🔴 for errors) for debugging
  • The created document object must implement a to_dict() method for serialization
  • Consider implementing rate limiting for this endpoint to prevent abuse
  • The get_user_id() function must be properly configured to extract user identity from the authenticated session

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function api_create_section 78.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 update_document_v2 77.9% similar

    Flask API endpoint that updates a document's title and/or description after verifying user ownership and authentication.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function api_update_document 77.8% similar

    Flask API endpoint that updates document metadata (title and custom metadata fields) for a specific document, with authentication and authorization checks.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function create_document_v5 77.6% similar

    Flask API endpoint that creates a new document or duplicates an existing document with options to copy or reference sections.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function api_get_document 75.8% similar

    Flask API endpoint that retrieves a specific document by ID, validates user access permissions, and returns the document data as JSON.

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