FastAPI uses OpenAPI, a specification for building RESTful APIs, to generate documentation automatically. OpenAPI defines a standard, language-agnostic interface to RESTful APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection.
First, you need to install FastAPI and Uvicorn (a server for running FastAPI applications). You can install them using pip
:
pip install fastapi uvicorn
Here is a simple FastAPI application with auto-generated documentation:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
To run the application, save the above code in a file named main.py
and run the following command in the terminal:
uvicorn main:app --reload
Once the application is running, you can access the auto-generated documentation in two different formats:
http://127.0.0.1:8000/docs
. Swagger UI provides an interactive interface to explore and test your API endpoints.http://127.0.0.1:8000/redoc
. ReDoc is another way to view the API documentation in a more structured and readable format.You can add descriptions to your API endpoints, parameters, and responses to make the documentation more informative.
from fastapi import FastAPI
app = FastAPI()
@app.get("/", summary="Get a simple greeting", description="This endpoint returns a simple 'Hello, World' message.")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}", summary="Get an item", description="Retrieve an item by its ID.")
def read_item(item_id: int, q: str = None):
"""
- **item_id**: The ID of the item to retrieve.
- **q**: An optional query string.
"""
return {"item_id": item_id, "q": q}
You can group related endpoints together using tags.
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}", tags=["items"])
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
@app.get("/users/{user_id}", tags=["users"])
def read_user(user_id: int):
return {"user_id": user_id}
Since the documentation is generated from the code, it is essential to keep your code clean and well - structured. Use meaningful variable names, add comments, and follow a consistent coding style.
Pydantic models can be used to define the structure of request and response data. This not only helps in data validation but also makes the documentation more accurate.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
is_offer: bool = None
@app.post("/items/")
def create_item(item: Item):
return item
Even though the documentation is auto-generated, it is still a good practice to review and update it regularly, especially when there are significant changes to the API.
FastAPI’s auto-generated documentation feature is a powerful tool that simplifies the process of API documentation. By understanding the fundamental concepts, using the correct usage methods, following common practices, and adhering to best practices, developers can create high - quality, interactive, and up - to - date API documentation with minimal effort. This not only benefits the developers themselves but also makes it easier for other users to understand and interact with the API.