Skip to content

Chapter 6.4: Documenting the API

Study Time: 30 minutes


1. Why is API Documentation Necessary?

Imagine being given the control panel of a complex spaceship with not a single label on the buttons. You would press them at random, risking launching the catapult instead of turning on the lights. API documentation is those very labels and instructions.

Good documentation:

  • Saves time: Developers don't have to guess what endpoints exist, what parameters they accept, and what they return.
  • Reduces errors: A clear description of data formats and error codes helps to avoid incorrect use of the API.
  • Simplifies integration: The frontend team can work in parallel with the backend team, relying on the documentation as a contract.
  • Is your legacy: Six months from now, you will thank yourself when you return to the project.

💡 Space Analogy:

  • API = A complex control system for a space station.
  • API Documentation = A manual for astronauts. It describes:
  • What command (endpoint) to send to open the airlock.
  • What parameters (request body) to pass to configure the life support system.
  • What signals (API responses) to expect in return.

2. Documentation in FastAPI: Automatic Magic

FastAPI makes documentation incredibly simple. It automatically generates interactive documentation based on your code, using the OpenAPI and Swagger UI standards.

Step 1: Add Metadata to Your Application

In main.py, you can add descriptions that will appear in the documentation.

# main.py
from fastapi import FastAPI
from pydantic import BaseModel, Field

# ... (FastAPI code)

app = FastAPI(
    title="SpaceAPI",
    description="""
API for exploring the galaxy. 🚀

You will be able to:
* **View planets**.
* **Add new worlds** (requires authentication).
    """,
    version="1.0.0",
    contact={
        "name": "Chief Engineer of Mission Control",
        "url": "https://example.com/contact",
        "email": "engineer@example.com",
    },
)

Step 2: Describe Your Models and Endpoints

The more detail you describe your Pydantic models and endpoint parameters, the better the documentation will be.

# In the file with Pydantic models or in main.py

class PlanetBase(BaseModel):
    name: str = Field(..., example="Earth", description="The name of the planet")
    description: str = Field(..., example="A blue planet with diverse life", description="A brief description")
    # ...

class Planet(PlanetBase):
    id: int
    is_habitable: bool

    class Config:
        orm_mode = True # or from_attributes = True in Pydantic v2

# In the routes file
@router.get(
    "/planets",
    response_model=list[Planet],
    summary="Get a list of all planets",
    description="Returns a list of all known planets with pagination (in the future)."
)
def get_planets():
    # ...

@router.post(
    "/planets",
    # ...
    summary="Create a new planet",
    responses={
        401: {"description": "User is not authorized"},
        422: {"description": "Data validation error"}
    }
)
def create_planet(planet: PlanetCreate, ...):
    # ...
  • Field(..., example="..."): Adds examples to the documentation.
  • summary: A brief description of the endpoint.
  • description: A detailed description.
  • responses: A description of possible response codes, other than successful ones.

Step 3: Open the Documentation in Your Browser

Start your FastAPI server and open two magic URLs:

  1. http://127.0.0.1:8000/docs — will open the interactive Swagger UI documentation. Here you can not only read, but also test your endpoints directly from the browser!
  2. http://127.0.0.1:8000/redoc — will open an alternative view of the ReDoc documentation. It is less interactive, but often more readable.

3. Documentation in Laravel: Using Third-Party Packages

Unlike FastAPI, Laravel does not generate documentation "out of the box". However, there are excellent packages that do this by analyzing your code. The most popular is Scribe.

Step 1: Install Scribe

composer require --dev "knuckleswtf/scribe"
php artisan vendor:publish --tag=scribe-config
php artisan scribe:generate

Step 2: Describe Endpoints with DocBlocks

Scribe reads PHP DocBlocks (comments of the form /** ... */) above your controller methods.

Open app/Http/Controllers/PlanetController.php:

// app/Http/Controllers/PlanetController.php

/**
 * @group Planets
 * API for managing planets
 */
class PlanetController extends Controller
{
    /**
     * Get a list of planets
     *
     * Returns a paginated list of all planets in the galaxy.
     *
     * @unauthenticated
     */
    public function index()
    {
        // ...
    }

    /**
     * Create a new planet
     *
     * @authenticated
     *
     * @bodyParam name string required The name of the planet. Example: Kepler-186f
     * @bodyParam description string required A description of the planet.
     * @bodyParam size_km integer required The diameter in kilometers. Example: 14000
     * @bodyParam is_habitable boolean Whether the planet is habitable. Example: true
     *
     * @response 201 {
     *  "id": 4,
     *  "name": "Kepler-186f",
     *  "description": "The first confirmed Earth-sized planet in the habitable zone of another star.",
     *  "size_km": 14000,
     *  "is_habitable": true,
     *  "created_at": "2023-10-27T12:00:00.000000Z",
     *  "updated_at": "2023-10-27T12:00:00.000000Z"
     * }
     */
    public function store(Request $request)
    {
        // ...
    }
    // ... and so on for other methods
}

Key Scribe tags:

  • @group: Groups endpoints.
  • @unauthenticated / @authenticated: Indicates whether a token is required.
  • @bodyParam: Describes a parameter in the request body.
  • @response: An example of a successful response.

Step 3: Generate and View the Documentation

Each time you make changes to the DocBlocks, run the command:

php artisan scribe:generate
Scribe will create a static HTML page with your documentation. Open it at: http://your-app-url/docs.


Reinforcement Quiz

1. FastAPI generates documentation based on the standard:

2. Which URL opens Swagger UI in FastAPI by default?

3. A popular package for generating documentation in Laravel is:

4. In Scribe, the tag used to describe request body parameters is:


🚀 Chapter Summary:

You have created professional documentation, turning your APIs from "black boxes" into understandable and convenient tools.

  • ✅ Understood the critical importance of API documentation.
  • 🪄 Learned to use automatic documentation generation in FastAPI.
  • ⚙️ Mastered the basics of the Scribe package for documenting APIs in Laravel.
  • 🛰️ Became convinced that good documentation is the best assistant for any developer.

Your APIs are now not only working and secure, but also fully ready for use by other team members. The last, but most important step remains — the final security check.

📌 Check:

  • For FastAPI: open /docs in your browser and try to execute a GET request to the list of planets directly from the Swagger UI interface.
  • For Laravel: execute php artisan scribe:generate and open /docs. Make sure the endpoints are grouped and that the store method has a description of the parameters.