是的,Django 也有类似的自动生成文档的工具,但需要安装第三方库。主要有以下几个流行的解决方案:
1. Django REST Framework (DRF) 的自动文档(最常用)
安装和配置
bash
pip install djangorestframework
settings.py 配置
python
INSTALLED_APPS = [
# ...
'rest_framework',
'rest_framework_swagger', # 或者使用 drf-yasg
]
REST_FRAMEWORK = {
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}
访问地址
http://127.0.0.1:8000/swagger/
或
http://127.0.0.1:8000/docs/
2. drf-yasg(推荐,功能更强大)
安装
bash
pip install drf-yasg
配置 urls.py
python
from django.urls import path, include
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
schema_view = get_schema_view(
openapi.Info(
title="API 文档",
default_version='v1',
description="API 描述",
terms_of_service="https://www.google.com/policies/terms/",
contact=openapi.Contact(email="contact@yourapi.local"),
license=openapi.License(name="BSD License"),
),
public=True,
permission_classes=(permissions.AllowAny,),
)
urlpatterns = [
# ... 其他路由
path('swagger<format>/', schema_view.without_ui(cache_timeout=0), name='schema-json'),
path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
]
访问地址
# Swagger UI (交互式)
http://127.0.0.1:8000/swagger/
# ReDoc (静态文档)
http://127.0.0.1:8000/redoc/
# 原始 OpenAPI JSON
http://127.0.0.1:8000/swagger.json
3. Django Ninja(类似 FastAPI 的现代方案)
安装
bash
pip install django-ninja
使用示例
python
from ninja import NinjaAPI
api = NinjaAPI()
@api.get("/hello")
def hello(request):
return {"message": "Hello World"}
@api.post("/items")
def create_item(request, name: str, price: float):
return {"name": name, "price": price}
@api.put("/items/{item_id}")
def update_item(request, item_id: int, name: str):
return {"item_id": item_id, "name": name}
@api.delete("/items/{item_id}")
def delete_item(request, item_id: int):
return {"deleted": item_id}
访问地址
http://127.0.0.1:8000/api/docs
4. 核心 Django 的 Schema 生成(基础功能)
Django 3.0+ 自带基础的 schema 生成:
配置 urls.py
python
from django.urls import path, include
from rest_framework.documentation import include_docs_urls
urlpatterns = [
# ...
path('docs/', include_docs_urls(title='API 文档')),
]
访问地址
http://127.0.0.1:8000/docs/
完整示例(使用 drf-yasg)
视图示例
python
# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class UserAPI(APIView):
def get(self, request):
"""获取用户列表"""
return Response([{"id": 1, "name": "John"}])
def post(self, request):
"""创建新用户"""
data = request.data
return Response({"id": 2, "name": data.get('name')}, status=status.HTTP_201_CREATED)
def put(self, request, user_id):
"""更新用户"""
data = request.data
return Response({"id": user_id, "name": data.get('name')})
def delete(self, request, user_id):
"""删除用户"""
return Response(status=status.HTTP_204_NO_CONTENT)
序列化器
python
# serializers.py
from rest_framework import serializers
class UserSerializer(serializers.Serializer):
name = serializers.CharField(max_length=100)
email = serializers.EmailField()
推荐方案
对于新项目 :推荐使用 Django Ninja,语法类似 FastAPI,文档生成功能强大。
对于现有 DRF 项目 :推荐使用 drf-yasg,功能最完善。
访问方式:
- 启动 Django 开发服务器:
python manage.py runserver
- 访问对应的文档地址(如
http://127.0.0.1:8000/swagger/
)
这些工具都会自动包含所有的 HTTP 方法(GET、POST、PUT、DELETE、PATCH 等),并提供交互式测试功能。