> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Creating In code documentation

> Guide to writing concise in-code documentation, using inline comments, docstrings, examples, and AI assistants like Copilot, plus README generation and practical verification tips.

In this lesson we cover practical, code-first techniques for writing clear in-code documentation. We'll demonstrate inline comments, simple docstrings, common styles (PEP 257, Google, NumPy), and how to accelerate the process with tools like GitHub Copilot. The aim is to help you generate useful, accurate documentation quickly — while emphasizing the essential verification and editing steps.

Key topics:

* Inline comments and compact docstrings for endpoints
* Using AI assistants (e.g., GitHub Copilot) to generate or improve comments
* Before/after examples to illustrate improvements
* Generating README.md skeletons with AI
* Console/runtime troubleshooting and practical tips

## 1. Inline comments and simple docstrings

For small endpoints, a concise docstring plus a couple of inline comments is often sufficient. Keep the docstring focused on purpose, inputs, outputs, and example request/response shapes.

Example (FastAPI):

```python theme={null}
from fastapi import APIRouter
from api.models.fake_data_request import FakeDataRequest
from data.fake_data_repository import get_fake_data

router = APIRouter()

@router.post("/getfakedata")
async def generate_fake_data(request: FakeDataRequest) -> dict:
    """
    Generate fake data based on the incoming request model.

    Args:
        request (FakeDataRequest): Request model that contains a `count`
            parameter indicating how many fake items to generate.

    Returns:
        dict: JSON response containing generated fake data under the
            `data` key.

    Example:
        Request:
        {
            "count": 5
        }

        Response:
        {
            "data": [...generated items...]
        }
    """
    # Fetch fake data using the repository function
    data = get_fake_data(request.count)

    # Return data wrapped in a dictionary for JSON response
    return {"data": data}
```

Best practices:

* Keep the docstring short and focused on the function's role, inputs, and output format.
* Use inline comments sparingly for non-obvious logic, edge cases, or performance implications.
* Use typing annotations to make the signature self-documenting.

<Callout icon="lightbulb" color="#1CB2FE">
  AI-generated comments are a great starting point, but always review them for accuracy and to remove stale or incorrect details.
</Callout>

## 2. Asking GitHub Copilot (or other assistants) to comment code

If you prefer automated assistance, you can ask Copilot to annotate code. Typical workflow:

* Open the file you want documented in your editor.
* Prompt the assistant, for example: "Please comment this code to explain it clearly."
* Review the generated docstrings and inline comments; edit them to ensure correctness.

Example prompt:

```text theme={null}
Please comment this code to explain it clearly.
```

Checklist after generation:

* Verify that parameter names match the current model and code (AI may refer to removed fields).
* Confirm examples reflect actual requests/responses.
* Remove any speculative or hallucinated details (e.g., fields that no longer exist).

<Callout icon="warning" color="#FF6B6B">
  AI assistants can hallucinate parameters or behavior. Always validate generated comments against the current code and tests before committing.
</Callout>

## 3. Example — before and after

Before (minimal comments):

```python theme={null}
from fastapi import APIRouter
from api.models.fake_data_request import FakeDataRequest
from data.fake_data_repository import get_fake_data

router = APIRouter()

@router.post("/getfakedata")
async def generate_fake_data(request: FakeDataRequest) -> dict:
    data = get_fake_data(request.count)
    return {"data": data}
```

After (annotated and documented):

```python theme={null}
from fastapi import APIRouter
from api.models.fake_data_request import FakeDataRequest
from data.fake_data_repository import get_fake_data

# Initialize FastAPI router instance
router = APIRouter()

@router.post("/getfakedata")
async def generate_fake_data(request: FakeDataRequest) -> dict:
    """
    Generate fake data based on the provided request parameters.

    Args:
        request (FakeDataRequest): Request model containing the `count`
            parameter specifying the number of fake data items to generate.

    Returns:
        dict: JSON response containing:
            - data: list of generated fake data items

    Example:
        Request: POST /getfakedata
        {
            "count": 5
        }
        Response:
        {
            "data": [...generated items...]
        }
    """
    # Retrieve fake data using repository function
    data = get_fake_data(request.count)

    # Return data wrapped in response dictionary
    return {"data": data}
```

This before/after demonstrates how small docstrings and targeted comments improve clarity for maintainers and API consumers.

## 4. Generate or improve README.md with GitHub Copilot

Copilot and similar assistants can quickly scaffold a README. Use a clear prompt and then verify every section (dependencies, setup steps, env vars, example calls).

Typical steps:

1. Create `README.md`.
2. Prompt: "Generate a README for a FastAPI-based fake data generator repository."
3. Edit the generated content to match your repo (e.g., exact dependencies, environment variables, and example commands).

Example README snippet (cleaned and reviewed):

````markdown theme={null}
A FastAPI-based service that generates and serves realistic fake data for development and testing purposes.

## Features

- Generate fake personal data (names, emails, ages, cities, occupations)
- REST API endpoints for programmatic access
- SQLite database storage (optional)
- Customizable data generation parameters

## Requirements

- Python 3.8+
- Dependencies listed in `requirements.txt`

## Installation

1. Clone the repository:
```sh
git clone https://github.com/yourusername/fake-data-generator.git
cd fake-data-generator
```text

2. Create and activate a virtual environment:
```sh
python3 -m venv venv
source venv/bin/activate
```text

3. Install dependencies:
```sh
pip install -r requirements.txt
```text

## Usage

1. Start the FastAPI server:
```sh
uvicorn main:app --reload
```text

2. Call the endpoint:
```sh
curl -X POST "http://0.0.0.0:8000/getfakedata" \
  -H "Content-Type: application/json" \
  -d '{"count": 5}'
```text
````

Always verify and adapt the generated README content — don’t publish without confirming accuracy.

## 5. Console and runtime notes

When running a FastAPI app with uvicorn you typically see logs like:

```Python theme={null}
INFO:     Started server process [12345]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO:     127.0.0.1:56608 - "POST /getfakedata HTTP/1.1" 200 OK
```

Common runtime issues:

* 422 Unprocessable Entity: request JSON does not match the expected Pydantic model.
  * Inspect the Pydantic model (e.g., `FakeDataRequest`) for required fields.
  * Confirm request keys and types match the model.
  * Update docstrings and README examples to reflect the actual schema.

## 6. Practical tips

* Use consistent import styles (absolute or relative) across the codebase to avoid confusion in docs and examples.
* Document public modules, exported functions, and class methods — not just endpoints.
* Prefer short, testable docstrings that are easy to keep up-to-date.
* When using AI to generate docs or READMEs:
  * Provide a precise prompt and example inputs/outputs.
  * Review outputs for factual accuracy and completeness.
* Include exact setup steps, environment variables, and curl/postman examples in README for better onboarding.

Table — Common docstring styles at-a-glance:

| Style                      | Typical Use                             | Example notes                                   |
| -------------------------- | --------------------------------------- | ----------------------------------------------- |
| PEP 257 (reStructuredText) | Python stdlib, formal docs              | Emphasizes short summary + extended description |
| Google                     | Readable, widely used in many teams     | Clear Args/Returns/Examples sections            |
| NumPy                      | Scientific code, arrays & return shapes | Includes Parameters/Returns/Examples with types |

## Links and References

* [FastAPI documentation](https://learn.kodekloud.com/user/courses/python-api-development-with-fastapi)
* [GitHub Copilot guide](https://learn.kodekloud.com/user/courses/github-copilot-in-action)
* [Uvicorn — ASGI server](https://www.uvicorn.org/)
* [Pydantic documentation](https://docs.pydantic.dev/)

## Conclusion

Automated tools like GitHub Copilot can speed up writing in-code documentation and README scaffolding. They provide useful stubs and suggestions, but the final verification and refinement step is essential to ensure accuracy. With short, consistent docstrings, selective inline comments, and validated AI outputs, you can maintain a codebase that’s easier for current and future maintainers to understand.

Thank you for reading this lesson.

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/github-copilot-in-action/module/5c3827f4-b200-4c22-90bb-e7c6540d96d8/lesson/c0d28a3e-a97f-4387-b3cd-6e237ca6e097" />
</CardGroup>
