DRF项目中如果想要自动生成API文档我们可以借助drf-spectacular
这个库,drf-spectacular
非常强大,它可以自动从DRF中提取信息,自动生成API文档,配置简单开箱即用,并且它对很多常用的第三方如:SimpleJWT
、django-filter
等做了适配。
下面的示例中我们将创建一个一些接口,由django-filter
实现过滤功能,并且使用drf-spectacular
创建接口文档。
1. 下载依赖
shell
pip install drf-spectacular[sidecar]
pip install django-filter
2. 配置settings.py
python
# APP配置
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"api.apps.BlogConfig",# 你的app
'rest_framework',
'drf_spectacular',
'drf_spectacular_sidecar',
]
# DRF配置
REST_FRAMEWORK = {
...
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
...
}
# SPECTACULAR配置
SPECTACULAR_SETTINGS = {
'TITLE': 'Your Project API',
'DESCRIPTION': 'Your project description',
'VERSION': '1.0.0',
'SERVE_INCLUDE_SCHEMA': False,
}
3. 创建模型
python
from django.db import models
from django_filters import rest_framework as filters
from rest_framework import serializers
class Order(models.Model):
name = models.CharField(max_length=100)
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
create_at = models.DateTimeField(auto_now_add=True)
order = models.ForeignKey(Order, on_delete=models.CASCADE)
4. 创建过滤器
python
class ProductFilter(filters.FilterSet):
class Meta:
model = Product
fields = {
'price': ['lt', 'gt'],
'create_at': ['lt', 'gt'],
'order__name': ['exact'],
}
5. 创建序列化器
python
class OrderSer(serializers.ModelSerializer):
class Meta:
model = Order
fields = '__all__'
def create(self, validated_data):
return Order.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.name = validated_data.get('name', instance.name)
instance.save()
return instance
class ProductReadSer(serializers.ModelSerializer):
order = OrderSer(read_only=True)
class Meta:
model = Product
fields = '__all__'
class ProductCreateSer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ['price', 'order']
def create(self, validated_data):
return Product.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.price = validated_data.get('price', instance.price)
instance.order = validated_data.get('order', instance.order)
instance.save()
return instance
6. 创建路由
python
from django.contrib import admin
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView
from api.views import OrderViewSet, ProductReadViewSet, ProductCreateViewSet
router = DefaultRouter()
router.register(r'orders', OrderViewSet)
router.register(r'products/read', ProductReadViewSet, basename='product-read')
router.register(r'products/create', ProductCreateViewSet, basename='product-create')
# 后台管理
urlpatterns = [
path('admin/', admin.site.urls),
]
# API接口
urlpatterns += [
path('api/', include(router.urls)),
]
# API文档
urlpatterns += [
path('api/schema/', SpectacularAPIView.as_view(), name='schema'),
path('api/schema/swagger-ui/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'),
path('api/schema/redoc/', SpectacularRedocView.as_view(url_name='schema'), name='redoc'),
]
7. 数据库迁移
shell
python manage.py makemigrations XXX
python manage.py migrate
8. 使用示例
启动项目打开我们配置的文档地址可以看到注册到路由中的接口其文档已经被自动创建好了。
配置了过滤器的接口也在文档中有所反映: