跳转至

第10章:模式和文档

现在我们的 API 已完成,我们需要一种方法来快速准确地向他人记录其功能。毕竟,在大多数公司和团队中,使用 API 的开发人员并不是最初构建它的同一开发人员。如果 API 对公众可用,它肯定需要一个文档完善的指南才能可用。

模式是一种机器可读的文档,它概述了所有可用的 API 端点、URLs 和 HTTP 动词(GET、POST、PUT、DELETE 等)。这很好,但对人类来说不太可读。进入文档,这是添加到模式中使其更易于人类阅读和使用的内容。

提醒一下,以下是我们当前 API 端点的完整列表:

端点表格 | 端点 | HTTP 动词 | |------|----------| | / | GET | | /:pk/ | GET | | users/ | GET | | users/:pk/ | GET | | /rest-auth/registration | POST | | /rest-auth/login | POST | | /rest-auth/logout | GET | | /rest-auth/password/reset | POST | | /rest-auth/password/reset/confirm | POST |

在本章中,我们将向博客项目添加机器可读模式和人类可读文档。更好的是,我们将自动化每个的生成,以便它们始终与我们的 API 的最新版本保持同步。

模式

Open API 规范是当前记录 API 的默认方式。它描述了可用端点、输入、认证方法、联系信息等的格式通用规则。在撰写本文时,drf-spectacular 是为 Django REST Framework 生成 Open API 3 模式的推荐第三方包。

首先,像往常一样使用 Pip 安装 drf-spectacular。

Shell

(.venv) > python -m pip install drf-spectacular~=0.21.0

将其添加到 django_project/settings.py 文件中的 INSTALLED_APPS 配置中。

代码

# django_project/settings.py
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "django.contrib.sites",
    # 3rd-party apps
    "rest_framework",
    "corsheaders",
    "rest_framework.authtoken",
    "allauth",
    "allauth.account",
    "allauth.socialaccount",
    "dj_rest_auth",
    "dj_rest_auth.registration",
    "drf_spectacular", # new
    # Local
    "accounts.apps.AccountsConfig",
    "posts.apps.PostsConfig",
]

然后在 django_project/settings.py 文件的 REST_FRAMEWORK 部分注册 drf-spectacular。

代码

# django_project/settings.py
REST_FRAMEWORK = {
    "DEFAULT_PERMISSION_CLASSES": [
        "rest_framework.permissions.IsAuthenticated",
    ],
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework.authentication.SessionAuthentication",
        "rest_framework.authentication.TokenAuthentication",
    ],
    "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema", # new
}

最后一步是向默认设置添加一些元数据,如标题、描述和版本。在 django_project/settings.py 中创建一个新部分并添加以下内容:

代码

# django_project/settings.py
SPECTACULAR_SETTINGS = {
    "TITLE": "Blog API Project",
    "DESCRIPTION": "A sample blog to learn about DRF",
    "VERSION": "1.0.0",
    # OTHER SETTINGS
}

要将模式生成为独立文件,我们可以使用管理命令并指定文件名,即 schema.yml

Shell

(.venv) > python manage.py spectacular --file schema.yml

新的 schema.yml 文件已在项目根目录中创建。如果您在文本编辑器中打开该文件,它相当长且不太人类友好。但对计算机来说,它的格式完全正确。

动态模式

一种更动态的方法是从我们的 API 作为 URL 路由直接提供模式。我们将通过导入 SpectacularAPIView,然后在 api/schema/ 添加新 URL 路径来显示它。

代码

# django_project/urls.py
from django.contrib import admin
from django.urls import path, include
from drf_spectacular.views import SpectacularAPIView # new

urlpatterns = [
    path("admin/", admin.site.urls),
    path("api/v1/", include("posts.urls")),
    path("api-auth/", include("rest_framework.urls")),
    path("api/v1/dj-rest-auth/", include("dj_rest_auth.urls")),
    path("api/v1/dj-rest-auth/registration/",
         include("dj_rest_auth.registration.urls")),
    path("api/schema/", SpectacularAPIView.as_view(), name="schema"), # new
]

再次使用 python manage.py runserver 启动本地服务器,并导航到新的模式 URL 端点 [[http://127.0.0.1:8000/api/schema/。我们整个](http://127.0.0.1:8000/api/schema/。我们整个](http://127.0.0.1:8000/api/schema/。我们整个](http://127.0.0.1:8000/api/schema/`。我们整个)) API 的自动生成模式文件可用,并将作为文件下载。

就个人而言,我更喜欢项目中的动态方法,而不必在每次 API 更改时重新生成 schema.yml 文件。

文档

模式对于计算机使用来说很好,但人类通常需要文档来使用 API。drf-spectacular 支持两种 API 文档工具:Redoc 和 Swagger UI。幸运的是,将我们的模式转换为其中任何一种都是相对轻松的过程。

让我们从 Redoc 开始。要添加它,在 django_project/urls.py 顶部导入 SpectacularRedocView,然后在 api/schema/redoc/ 添加 URL 路径。

代码

# django_project/urls.py
from django.contrib import admin
from django.urls import path, include
from drf_spectacular.views import (
    SpectacularAPIView,
    SpectacularRedocView, # new
)

urlpatterns = [
    path("admin/", admin.site.urls),
    path("api/v1/", include("posts.urls")),
    path("api-auth/", include("rest_framework.urls")),
    path("api/v1/dj-rest-auth/", include("dj_rest_auth.urls")),
    path("api/v1/dj-rest-auth/registration/",
         include("dj_rest_auth.registration.urls")),
    path("api/schema/", SpectacularAPIView.as_view(), name="schema"),
    path("api/schema/redoc/",
         SpectacularRedocView.as_view(url_name="schema"),
         name="redoc",), # new
]

如果本地服务器仍在运行,您可以直接前往 [[http://127.0.0.1:8000/api/schema/redoc/](http://127.0.0.1:8000/api/schema/redoc/](http://127.0.0.1:8000/api/schema/redoc/](http://127.0.0.1:8000/api/schema/redoc/`)) 查看我们的新文档。

添加 Swagger UI 的过程非常相似。在文件顶部导入 SpectacularSwaggerView,然后在 api/schema/swagger-ui/ 为其添加 URL 路径。

代码

# django_project/urls.py
from django.contrib import admin
from django.urls import path, include
from drf_spectacular.views import (
    SpectacularAPIView,
    SpectacularRedocView,
    SpectacularSwaggerView, # new
)

urlpatterns = [
    path("admin/", admin.site.urls),
    path("api/v1/", include("posts.urls")),
    path("api-auth/", include("rest_framework.urls")),
    path("api/v1/dj-rest-auth/", include("dj_rest_auth.urls")),
    path("api/v1/dj-rest-auth/registration/",
         include("dj_rest_auth.registration.urls")),
    path("api/schema/", SpectacularAPIView.as_view(), name="schema"),
    path("api/schema/redoc/",
         SpectacularRedocView.as_view(url_name="schema"),
         name="redoc",),
    path("api/schema/swagger-ui/",
         SpectacularSwaggerView.as_view(url_name="schema"),
         name="swagger-ui"), # new
]

然后前往 Web 浏览器查看输出: [[http://127.0.0.1:8000/api/schema/swagger-ui/](http://127.0.0.1:8000/api/schema/swagger-ui/](http://127.0.0.1:8000/api/schema/swagger-ui/](http://127.0.0.1:8000/api/schema/swagger-ui/`))

结论

添加模式和文档是任何 API 的重要组成部分。这通常是 fellow 开发人员首先查看的内容,无论是在团队内还是开源项目中。得益于本章介绍的自动化工具,确保您的 API 具有准确、最新的文档只需要少量配置。最后一步是正确部署博客 API,我们将在下一章中介绍。