Django集成Swagger的兩種實(shí)現(xiàn)方案全指南
一、前言
概述
在前后端分離開(kāi)發(fā)中,API 文檔的重要性不言而喻。Swagger(現(xiàn)更名為 OpenAPI)作為主流的 API 文檔生成工具,能自動(dòng)生成交互式文檔,極大提升開(kāi)發(fā)效率。本文將介紹兩種在 Django 項(xiàng)目中集成 Swagger 的實(shí)用方案,幫助開(kāi)發(fā)者快速搭建完善的 API 文檔系統(tǒng)。
什么是 Swagger/OpenAPI
Swagger 是一套用于描述、生成、消費(fèi)和可視化 RESTful API 的規(guī)范和工具集,目前已演進(jìn)為 OpenAPI 規(guī)范:
- Swagger 2.0:支持 WebSockets、OAuth2、文件上傳等功能,提升了 API 描述的精確度
- OpenAPI 3.0:下一代規(guī)范,提供更嚴(yán)格的模式驗(yàn)證、更多數(shù)據(jù)類型支持和更好的擴(kuò)展性
通過(guò)集成 Swagger,開(kāi)發(fā)者可以獲得:
- 自動(dòng)生成的交互式 API 文檔
- 在線接口調(diào)試功能
- 標(biāo)準(zhǔn)化的 API 描述格式(JSON/YAML)
- 便于前后端協(xié)作和 API 版本管理
兩種方案對(duì)比
| 特性 | drf-yasg | drf-spectacular |
|---|---|---|
| 規(guī)范支持 | Swagger 2.0 | OpenAPI 3.0 |
| 功能豐富度 | 基礎(chǔ)功能完善 | 高級(jí)功能更豐富 |
| 可定制性 | 中等 | 高 |
| 學(xué)習(xí)曲線 | 平緩 | 稍陡 |
| 推薦場(chǎng)景 | 簡(jiǎn)單項(xiàng)目快速集成 | 復(fù)雜項(xiàng)目、需要高級(jí)定制 |
二、方案一:使用 drf-yasg(支持 Swagger 2.0)
工具介紹
drf-yasg 是基于 Django REST Framework (DRF) 的 API 文檔生成工具,專注于 Swagger 2.0 規(guī)范,具有以下特點(diǎn):
- 動(dòng)態(tài)生成 Swagger UI,支持多種主題
- 可自定義文檔樣式和內(nèi)容
- 支持隱藏指定字段、添加額外參數(shù)等高級(jí)功能
安裝步驟
安裝
pip install -U drf-yasg
配置settings.py:在 INSTALLED_APPS 中添加相關(guān)應(yīng)用
INSTALLED_APPS = [ # ... 'django.contrib.staticfiles', # 用于提供 Swagger UI 的靜態(tài)文件 'drf_yasg', # ... ]
配置urls.py:添加 Swagger 相關(guān)路由
from django.urls import re_path
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
# 配置 API 文檔基本信息
schema_view = get_schema_view(
openapi.Info(
title="項(xiàng)目 API",
default_version='v1',
description="API 接口文檔描述",
terms_of_service="https://www.example.com/terms/",
contact=openapi.Contact(email="contact@example.com"),
license=openapi.License(name="MIT License"),
),
public=True,
permission_classes=(permissions.AllowAny,), # 允許任何人訪問(wèn)文檔
)
# 添加 URL 路由
urlpatterns = [
# ...
# 文檔 JSON/YAML 下載
path('swagger<format>/', schema_view.without_ui(cache_timeout=0), name='schema-json'),
# Swagger UI 頁(yè)面
path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
# ReDoc 頁(yè)面
path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
# ...
]
查看效果
啟動(dòng) Django 項(xiàng)目后,通過(guò)以下地址訪問(wèn)文檔:
Swagger UI 界面:http://localhost:8000/swagger/

ReDoc 界面:http://localhost:8000/redoc/
下載 JSON 格式文檔:http://localhost:8000/swagger.json
下載 YAML 格式文檔:http://localhost:8000/swagger.yaml
三、方案二:使用 drf-spectacular(支持 OpenAPI 3.0)
工具介紹
drf-spectacular 是新一代 API 文檔生成工具,支持 OpenAPI 3.0 規(guī)范,具有以下優(yōu)勢(shì):
- 更強(qiáng)的可擴(kuò)展性和可定制性
- 支持客戶端代碼生成
- 兼容多種 DRF 插件
- 提供更豐富的文檔裝飾器
參考資料: drf-spectacular 官方文檔
安裝步驟
安裝
pip install drf-spectacular pip install drf-spectacular[sidecar] # 安裝內(nèi)置 UI 資源(推薦)
配置 settings.py:點(diǎn)擊查看完整代碼
INSTALLED_APPS = [
# ...
'drf_spectacular',
'drf_spectacular_sidecar', # 內(nèi)置 UI 資源
# ...
]
# 配置 DRF
REST_FRAMEWORK = {
# OpenAPI 文檔
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
}
### drf-spectacular OpenAPI 文檔配置
SPECTACULAR_SETTINGS = {
"SWAGGER_UI_DIST": "SIDECAR", # 使用內(nèi)置 UI
"SWAGGER_UI_FAVICON_HREF": "SIDECAR",
"TITLE": "MarsMgn API",
"DESCRIPTION": "火星信息平臺(tái)接口文檔",
"VERSION": "1.0.0",
"SERVE_INCLUDE_SCHEMA": False, # 不在文檔中包含 schema 本身
}
配置 urls.py:點(diǎn)擊查看完整代碼
from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView
urlpatterns = [
#...
# API schema 生成端點(diǎn)
path('api/schema/', SpectacularAPIView.as_view(), name='schema'),
# Swagger UI 界面
path('api/schema/swagger-ui/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'),
# ReDoc 界面
path('api/schema/redoc/', SpectacularRedocView.as_view(url_name='schema'), name='redoc'),
#...
]
查看效果
啟動(dòng) Django 項(xiàng)目后,通過(guò)以下地址訪問(wèn) Swagger UI 界面:http://127.0.0.1:8000/api/schema/swagger-ui

四、drf-spectacular 高級(jí)使用技巧
字段注釋
文檔描述優(yōu)先從序列化器 / 模型的 help_text 提取:
class SystemPost(models.Model):
id = models.BigAutoField(primary_key=True, help_text="崗位ID")
code = models.CharField(
max_length=64,
help_text="崗位編碼", # 會(huì)顯示在文檔中
)
接口說(shuō)明
使用 @extend_schema 裝飾器自定義接口描述:
from drf_spectacular.utils import extend_schema
@extend_schema(summary="創(chuàng)建崗位", description="自定義接口詳細(xì)說(shuō)明")
@action(methods=["post"], detail=False, url_path="create")
def create_post(self, request, *args, **kwargs):
return self.custom_create(request, *args, **kwargs)
接口分組
通過(guò) tags 參數(shù)對(duì)接口進(jìn)行分組:
@extend_schema(tags=["管理后臺(tái)-system-崗位"])
class PostViewSet(CustomViewSet):
queryset = SystemPost.objects.all()
filterset_class = SystemPostFilter
請(qǐng)求與響應(yīng)參數(shù)定義
定義響應(yīng)參數(shù)示例
from drf_spectacular.utils import extend_schema, OpenApiResponse
from drf_spectacular.types import OpenApiTypes
@extend_schema(
responses={
200: OpenApiResponse(
description="操作成功",
response={
"type": "object",
"properties": {
"code": {"type": "integer", "example": 0},
"data": {"type": "boolean", "example": True},
"msg": {"type": "string", "example": ""}
}
}
)
}
)
def delete_post(self, request, *args, ?**kwargs):
"""刪除崗位"""
return Response({"code": 0, "data": True, "msg": ""}, status=200)
到此這篇關(guān)于Django集成Swagger的兩種實(shí)現(xiàn)方案全指南的文章就介紹到這了,更多相關(guān)Django集成Swagger內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
selenium動(dòng)態(tài)數(shù)據(jù)獲取的方法實(shí)現(xiàn)
本文主要介紹了selenium動(dòng)態(tài)數(shù)據(jù)獲取的方法實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
python時(shí)間日期函數(shù)與利用pandas進(jìn)行時(shí)間序列處理詳解
python標(biāo)準(zhǔn)庫(kù)包含于日期(date)和時(shí)間(time)數(shù)據(jù)的數(shù)據(jù)類型,datetime、time以及calendar模塊會(huì)被經(jīng)常用到,而pandas則可以對(duì)時(shí)間進(jìn)行序列化排序2018-03-03
詳解Python如何實(shí)現(xiàn)查看WiFi密碼
這篇文章主要為大家詳細(xì)介紹了如何使用python來(lái)試試看看能不能讀取到已連接過(guò)WIFI的密碼,文中的示例代碼講解詳細(xì),?感興趣的小伙伴可以了解下2023-11-11
opencv銀行卡號(hào)識(shí)別的項(xiàng)目實(shí)踐
本文主要介紹了opencv銀行卡號(hào)識(shí)別的項(xiàng)目實(shí)踐,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2025-04-04
Python?print函數(shù):如何將對(duì)象打印輸出
這篇文章主要介紹了Python?print函數(shù):如何將對(duì)象打印輸出,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05

