FastAPI Automatic API Documentation


What is Automatic API Documentation in FastAPI?

Automatic API Documentation in FastAPI refers to the feature that generates interactive and visual documentation for your API based on the routes, models, and parameters defined in your application. FastAPI provides this documentation automatically through the OpenAPI standard and allows you to interact with your API directly from the browser using tools like Swagger UI and ReDoc.


How does FastAPI generate API documentation?

FastAPI generates API documentation using the OpenAPI (formerly known as Swagger) specification. The OpenAPI specification is automatically built from your FastAPI routes, including details such as the HTTP methods, path parameters, query parameters, request bodies, and response models. FastAPI also uses JSON Schema to define data models, ensuring comprehensive documentation of the API.

The API documentation is available in two formats:

  • Swagger UI: An interactive web-based tool for exploring and testing your API.
  • ReDoc: A more static, comprehensive documentation interface.

Where can you access the automatic API documentation in FastAPI?

You can access the automatic API documentation by visiting the following default URLs after running your FastAPI application:

  • Swagger UI: Available at /docs
  • ReDoc: Available at /redoc

Example:

http://localhost:8000/docs

This will open the Swagger UI where you can interactively explore and test the API.


How do you customize the API documentation in FastAPI?

FastAPI allows you to customize the API documentation by modifying the title, description, version, and contact information of your API. This can be done by passing the desired configuration when creating the FastAPI application instance.

Example of customizing API documentation:

from fastapi import FastAPI

app = FastAPI(
    title="Custom API",
    description="This is a custom API with modified documentation",
    version="1.0.0",
    contact={
        "name": "Support Team",
        "email": "[email protected]"
    }
)

In this example, the API documentation has been customized with a custom title, description, version, and contact information. These customizations will appear in both Swagger UI and ReDoc.


How do you disable or change the default URL for Swagger UI and ReDoc in FastAPI?

If you want to disable Swagger UI or ReDoc, or change their default URLs, FastAPI allows you to configure this during app creation. You can use the docs_url and redoc_url options to customize or disable these features.

Example of disabling Swagger UI and customizing the ReDoc URL:

app = FastAPI(
    docs_url=None,  # Disable Swagger UI
    redoc_url="/api-docs"  # Change ReDoc URL
)

In this example, Swagger UI is disabled by setting docs_url=None, and ReDoc is accessible at /api-docs instead of the default /redoc.


What is OpenAPI in FastAPI, and how is it related to API documentation?

OpenAPI is a specification that defines a standard for building and describing RESTful APIs. FastAPI uses the OpenAPI specification to generate the API documentation, which is then rendered through tools like Swagger UI and ReDoc. The OpenAPI schema provides detailed information about your API's endpoints, including the methods, parameters, and response formats, making it easier for developers to understand and interact with the API.

You can access the raw OpenAPI schema generated by FastAPI at /openapi.json.

Example:

http://localhost:8000/openapi.json

This will return the JSON representation of the OpenAPI schema for your API.


How do you add examples in API documentation with FastAPI?

FastAPI allows you to add examples to your API documentation, which can be displayed in the Swagger UI. You can include examples in your Pydantic models using the schema_extra attribute or directly in the route handlers.

Example of adding examples in a Pydantic model:

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float

    class Config:
        schema_extra = {
            "example": {
                "name": "Sample Item",
                "price": 19.99
            }
        }

@app.post("/items/")
def create_item(item: Item):
    return item

In this example, an example for the Item model is provided in the documentation, showing a sample request body. Swagger UI will automatically display the example when interacting with the API.


How do you document request and response models in FastAPI?

FastAPI automatically generates documentation for request and response models based on the Pydantic models defined in your application. You can control which model is documented for the response using the response_model parameter in the route decorator.

Example of documenting request and response models:

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float

@app.post("/items/", response_model=Item)
def create_item(item: Item):
    return item

In this example, the API documentation will automatically include both the request body and the response format, which are based on the Item model. Swagger UI will display both models when interacting with the /items/ endpoint.


How do you handle authentication in API documentation with FastAPI?

FastAPI allows you to add authentication to your API and automatically document it using security schemes. You can define authentication mechanisms like OAuth2, API keys, or HTTP basic authentication, and FastAPI will generate the corresponding documentation in Swagger UI.

Example of adding OAuth2 authentication to the documentation:

from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordBearer

app = FastAPI()

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/users/me")
def read_users_me(token: str = Depends(oauth2_scheme)):
    return {"token": token}

In this example, OAuth2 authentication is added to the /users/me route. Swagger UI will automatically display the OAuth2 authentication fields, allowing users to input their tokens when testing the endpoint.


How do you include additional metadata in FastAPI documentation?

FastAPI allows you to add additional metadata to your API documentation, such as tags, descriptions, and summaries for individual routes. This metadata helps organize and improve the readability of the generated documentation.

Example of adding metadata to routes:

@app.get("/items/", tags=["Items"], summary="Get a list of items", description="Retrieve a list of all available items.")
def read_items():
    return [{"name": "Item1"}, {"name": "Item2"}]

In this example, the route /items/ is tagged with the category "Items," and additional metadata such as a summary and description is provided. Swagger UI will display this metadata in the API documentation.


How do you document multiple responses in FastAPI?

FastAPI allows you to document multiple responses for a single endpoint, such as handling different HTTP status codes (e.g., 200, 400, 404). You can specify different response models or descriptions for each status code using the responses parameter in the route decorator.

Example of documenting multiple responses:

@app.get("/items/{item_id}", responses={
    200: {"description": "Item found"},
    404: {"description": "Item not found"}
})
def read_item(item_id: int):
    if item_id == 1:
        return {"name": "Item1"}
    else:
        return {"error": "Item not found"}, 404

In this example, the API documentation specifies different responses for status codes 200 (item found) and 404 (item not found). Swagger UI will display both possible responses when testing the /items/{item_id} endpoint.

Ads