Skip to content

docs: Enhance FastAPI auto-generated documentation with better annotations #19

@doughayden

Description

@doughayden

Documentation Enhancement

Enhance FastAPI's automatic Swagger documentation by adding proper annotations, descriptions, and examples to improve the auto-generated /docs endpoint.

Level of Effort: 🟢 Small (1-2 days)

  • Model annotations: 0.5 day for enhancing Pydantic model documentation
  • Endpoint descriptions: 0.5 day for adding comprehensive endpoint documentation
  • Examples and responses: 0.5 day for adding request/response examples
  • Testing: 0.5 day for validating generated documentation

Current State

What we have:

  • FastAPI automatically generates Swagger UI at /docs
  • Basic Pydantic models with minimal documentation
  • Auto-generated OpenAPI schema

What's missing:

  • Detailed descriptions for endpoints and models
  • Request/response examples
  • Comprehensive error response documentation
  • Better organization with tags and summaries

Proposed Enhancements

1. Enhanced Endpoint Documentation

Add comprehensive annotations to existing endpoints:

# src/answer_app/main.py
@app.post(
    "/answer",
    response_model=AnswerResponse,
    summary="Get AI-powered answer to user query",
    description="""
    Submit a question and receive an AI-generated answer with citations.
    
    The system uses Vertex AI Discovery Engine to provide grounded responses
    based on your document corpus. Responses include source citations and
    session tracking for conversation context.
    """,
    responses={
        400: {"description": "Invalid request format or missing required fields"},
        401: {"description": "Authentication required - invalid or missing credentials"},
        500: {"description": "Internal server error - check logs for details"}
    },
    tags=["Query Processing"]
)
async def answer_query(request: AnswerRequest):
    """Process user query and return AI-generated answer with citations."""

2. Enhanced Pydantic Model Documentation

Add detailed field descriptions and examples:

# src/answer_app/model.py
class AnswerRequest(BaseModel):
    """Request model for submitting questions to the AI assistant."""
    
    query: str = Field(
        ...,
        description="The user's question or query to be answered",
        example="What is the company policy on remote work?",
        min_length=1,
        max_length=10000
    )
    
    session_id: Optional[str] = Field(
        None,
        description="Optional session ID to maintain conversation context",
        example="session_abc123"
    )

class AnswerResponse(BaseModel):
    """Response containing the AI-generated answer and metadata."""
    
    answer: str = Field(
        ...,
        description="The AI-generated answer to the user's query",
        example="The company allows remote work up to 3 days per week..."
    )
    
    citations: List[str] = Field(
        default_factory=list,
        description="Source documents used to generate the answer",
        example=["HR_Policy.pdf", "Remote_Work_Guidelines.docx"]
    )
    
    session_id: str = Field(
        ...,
        description="Session ID for tracking conversation context",
        example="session_abc123"
    )

3. FastAPI App Metadata

Enhance app-level documentation:

# src/answer_app/main.py
app = FastAPI(
    title="Answer App API",
    description="""
    Vertex AI Search Answer App API for conversational search and document-based Q&A.
    
    This API provides AI-powered answers to user questions based on your document corpus,
    with conversation tracking and source citations.
    """,
    version="0.2.0",
    contact={
        "name": "Answer App",
        "url": "https://github.com/doughayden/answer-app",
    },
    license_info={
        "name": "MIT",
        "url": "https://opensource.org/licenses/MIT",
    },
    tags_metadata=[
        {
            "name": "Query Processing",
            "description": "Submit questions and receive AI-generated answers",
        },
        {
            "name": "Session Management", 
            "description": "Manage user sessions and conversation context",
        },
        {
            "name": "Feedback",
            "description": "Submit feedback on answer quality",
        },
        {
            "name": "Health",
            "description": "API health and status endpoints",
        },
    ]
)

Implementation Areas

Files to Enhance:

  • src/answer_app/main.py: Add endpoint descriptions, tags, and response documentation
  • src/answer_app/model.py: Enhance Pydantic models with Field descriptions and examples
  • Existing endpoints: /answer, /feedback, /healthz - add comprehensive documentation

Documentation Improvements:

  • Detailed field descriptions for all request/response models
  • Example requests and responses for each endpoint
  • Error response documentation with status codes
  • Proper tagging and organization of endpoints

Current Endpoints to Document

1. /answer (POST)

  • Add detailed description of query processing
  • Document expected request format
  • Provide example queries and responses
  • Document error scenarios

2. /feedback (POST)

  • Document feedback submission process
  • Explain feedback scoring system
  • Provide example feedback requests

3. /healthz (GET)

  • Document health check response format
  • Explain what health checks are performed

Testing Validation

Documentation Quality Checks:

  • Visit /docs and verify comprehensive documentation
  • Ensure all endpoints have descriptions and examples
  • Validate that request/response schemas are clear
  • Test example requests work correctly

User Experience Testing:

  • Documentation clarity for new developers
  • Completeness of information for API integration
  • Accuracy of examples and descriptions

Acceptance Criteria

  • All endpoints have comprehensive descriptions and summaries
  • Request/response models include detailed field descriptions
  • Example requests and responses provided for all endpoints
  • Error responses documented with appropriate status codes
  • Endpoints properly organized with tags
  • FastAPI app metadata complete with contact/license info
  • Generated Swagger UI at /docs is comprehensive and user-friendly

Priority

Low - Improves developer experience but FastAPI already provides functional auto-documentation.

When to Implement

This becomes more valuable when:

  • External developers need to integrate with the API
  • API complexity increases with more endpoints
  • Documentation clarity becomes important for team productivity
  • Support requests involve API usage questions

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions