Skip to main content
In this guide, you’ll learn how to write clear, maintainable documentation directly inside your Python code. We’ll cover:
  • Inline comments
  • Structured docstrings (PEP 257)
  • Leveraging GitHub Copilot
  • Documenting Pydantic models
  • Generating a README.md automatically
Our running example is a simple FastAPI service that generates fake data.

Table of Contents

  1. Basic FastAPI Endpoint
  2. Adding Inline Comments
  3. Writing Comprehensive Docstrings
  4. Using GitHub Copilot to Generate Comments
  5. Documenting Your Pydantic Models
  6. Generating a README with Copilot
  7. Summary & Best Practices
  8. Links and References

1. Basic FastAPI Endpoint

Start with a minimal router in router.py:
Run the server:

2. Adding Inline Comments

Inline comments help readers follow the code flow without jumping to external docs:
Keep inline comments concise—explain why, not what. The code itself should reveal the “what.”

3. Writing Comprehensive Docstrings

Use PEP 257-style docstrings to detail arguments, return values, and examples:

4. Using GitHub Copilot to Generate Comments

Let Copilot accelerate your documentation:
  1. Open router.py in VS Code (or your editor).
  2. Place cursor above the function.
  3. Type:
Copilot will suggest a structured docstring and inline notes:
Review Copilot’s suggestions carefully—AI-generated docs may need tweaks to match your project conventions.

5. Documenting Your Pydantic Models

Enhance your request schema with docstrings for automatic API docs (Swagger UI):

6. Generating a README with Copilot

Use Copilot to scaffold a README.md:

Example README.md


7. Summary & Best Practices

  • Inline Comments: Clarify logic and intent.
  • Docstrings: Follow PEP 257 for consistency and auto-generated docs.
  • Copilot: Speeds up writing but always review AI-generated text.
  • Pydantic Models: Document attributes for better schema validation and API docs.
Documented code helps teams onboard faster and reduces maintenance overhead. Next, explore unit testing strategies to ensure your endpoints behave as expected.

Watch Video