接口文档


一、接口文档

在前后端分离的web应用模式下,我们编写后端只需要编写接口,前端根据我们的接口编写各式各样的前端界面。

作为后端,我们十分清除自己编写的各种接口的作用,以及接口的要求,但是前端人员并不知道,因此我们需要编写接口文档,让前端可以明白需要往什么接口发送请求,请求需要符合的要求。

举例:登陆接口的要求

-作为后端来讲,我们很清楚,比如登录接口  /api/v1/login/---->post---->变量名称username,password 编码方式json----》返回的格式  {code:100,msg:登录成功}

在公司里面写API接口文档的方式有三种:

# 接口文档如何编写
	-1 使用word,md 编写接口文档
    -2 使用第三方平台(比如showdoc),编写我们的接口文档(非常多)---》收费
    	-https://www.showdoc.com.cn/item/index
    -3 公司自己使用第三方开源的搭建的---》Yapi ---》你如果想自己搭建(去看教程)
    	-https://zhuanlan.zhihu.com/p/366025001 
            
    -4 使用drf编写的接口,可以自动生成接口文档
    	-swagger---》drf-yasg---》官方推荐使用
        -coreapi----》咱们讲的是这个

接口文档,需要有的东西

-描述
-地址
-请求方式
-请求编码格式
-请求数据详解(必填,类型)
-返回格式案例
-返回数据字段解释
-错误码

使用coreapi自动生成接口文档步骤

  • 步骤一:安装coreapi模块

pycharm下载或是

pip install coreapi
  • 步骤二:配置路由

在总路由中添加接口文档路径。

文档路由对应的视图配置为rest_framework.documentation.include_docs_urls

参数title为接口文档网站的标题。

from rest_framework.documentation import include_docs_urls

urlpatterns = [
    ...
    path('docs/', include_docs_urls(title='站点页面标题'))
]
  • 步骤三:在视图类或视图集的内部写上注释

我们可以视图类或是视图类中的类方法内加注释,让他接口文档中进行显示,写在类中的注释会出现在接口文档的每一个方法内,写在类方法内的注释会出现在接口文档中该方法所在的位置

如果我们想要修改接口文档中的序列化类或是模型表中的字段的名称或限制条件,可以在字段中进行修改,接口文档中也会显示出来(help_text:给字段配置注释,required:不能为空约束)。

  • 步骤四:配置文件中添加配置信息
    	REST_FRAMEWORK = {
     		'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',

    	}
  • 步骤五:访问地址,查看接口文档
http://127.0.0.1:8000/docs

代码

urls.py

from django.contrib import admin
from django.urls import path, include
from rest_framework.documentation import include_docs_urls
from rest_framework.routers import SimpleRouter
from app01 import views

router = SimpleRouter()
router.register('books', views.BookView, 'books')


urlpatterns = [
    path('admin/', admin.site.urls),
    # 这是接口文档的路由
    path('docs/', include_docs_urls(title='zzh的项目接口文件')),
    # 这是视图类自动匹配的路由
    path('api/v1/', include(router.urls)),
]

models.py

两个def方法在数据库迁移的时候要先注释掉

from django.db import models


# 图书跟作者:多对多,需要建立中间表,但是我们可以通过ManyToManyField自动生成,写在哪里都行
# 图书跟出版社:一对多,一个出版社,出版多本书,关联字段写在多的一方,写在Book
class Book(models.Model):
    name = models.CharField(max_length=32, default='xx', help_text='图书名字')
    price = models.IntegerField()

    publish = models.ForeignKey(to='Publish', on_delete=models.CASCADE)  # 留住,还有很多
    authors = models.ManyToManyField(to='Author')

    def publish_detail(self):
        return {'name': self.publish.name, 'addr': self.publish.addr}

    def author_list(self):
        l = []
        for author in self.authors.all():
            l.append({'name': author.name, 'phone': author.phone})
        return l


class Publish(models.Model):
    name = models.CharField(max_length=32)
    addr = models.CharField(max_length=32)


class Author(models.Model):
    name = models.CharField(max_length=32)
    phone = models.CharField(max_length=11)


class User(models.Model):
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)
    user_type = models.IntegerField(choices=((1, '超级管理员'), (2, '普通用户'), (3, '2B用户')), default=2)


class UserToken(models.Model):  # 跟User是一对一
    token = models.CharField(max_length=32)
    user = models.OneToOneField(to='User', on_delete=models.CASCADE, null=True)
    # user :反向,表名小写,所有有user字段

serializer.py

这是序列化类,收发请求会用到所以要写

from rest_framework import serializers
from .models import Book, Author, Publish
from rest_framework.exceptions import ValidationError


class BookSerializer(serializers.ModelSerializer):
    # 跟表有关联
    class Meta:
        model = Book
        fields = ['id', 'name', 'price', 'publish_detail', 'author_list', 'publish', 'authors']
        extra_kwargs = {
            'id': {'help_text': 'id号'},
            'name': {'max_length': 8},
            'publish_detail': {'read_only': True},
            'author_list': {'read_only': True},
            'publish': {'write_only': True},
            'authors': {'write_only': True},
        }

settings.py

REST_FRAMEWORK = {
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}
'我们要在浏览器中显示接口文档还需要注册drfapp'
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',
    'rest_framework',
]

views.py

from django.shortcuts import render
from rest_framework.generics import ListAPIView
from .models import Book
from .serializer import BookSerializer
from rest_framework.viewsets import ModelViewSet

# Create your views here.
'这里的注释必须写在代码的最上方,否则可能不会显示'
class BookView(ModelViewSet):
    """
    你是猪
    """
    queryset = Book.objects.all()
    serializer_class = BookSerializer

两点说明

1) 视图集ViewSet中的retrieve名称,在接口文档网站中叫做read

2)参数的Description需要在模型类或序列化器类的字段中以help_text选项定义,如:

class Student(models.Model):
    ...
    age = models.IntegerField(default=0, verbose_name='年龄', help_text='年龄')
    ...

class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = "__all__"
        extra_kwargs = {
            'age': {
                'required': True,
                'help_text': '年龄'
            }
        }


posted @   致丶幻  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
  1. 1 So Far Away (Acoustic) Adam Christopher
  2. 2 雪 Distance Capper&罗言RollFlash
  3. 3 CollapsingWorld
  4. 4 Call You Tonight Johnta Austin
So Far Away (Acoustic) - Adam Christopher
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.

作曲 : David Guetta/Giorgio H Tuinfort/Jamie Scott/Martijn G Garritsen

Light ‘em up, light ‘em up

Tell me where you are, tell me where you are

The summer nights, the bright lights

And the shooting stars, they break my heart

I‘m calling you now, but you‘re not picking up

Your shadows so close if you are still in love

Then light a match, light a match

Baby, in the dark, show me where you are

Oh, love

How I miss you every single day when I see you on those streets

Oh, love

Tell me there‘s a river I can swim that will bring you back to me

‘Cause I don‘t know how to love someone else

I don‘t know how to forget your face

Oh, love

God, I miss you every single day and now you‘re so far away

It‘s breaking me, I‘m losing you

We were far from perfect, but we were worth it

Too many fights, and we cried, but never said we‘re sorry

Stop saying you love me

You‘re calling me now, but I can‘t pick up

Your shadow‘s too close, and I‘m still in love

The summer‘s over now, but somehow, it still breaks my heart

We could have had the stars, oh

Oh, love

How I miss you every single day when I see you on those streets

Oh, love

Tell me there‘s a river I can swim that will bring you back to me

‘Cause I don‘t know how to love someone else

I don‘t know how to forget your face

Oh, love

God, I miss you every single day and now you‘re so far away

Oh, love

How I miss you every single day when I see you on those streets

Oh, love

Tell me there‘s a river I can swim that will bring you back to me

‘Cause I don‘t know how to love someone else

I don‘t know how to forget your face

Oh, love

God, I miss you every single day when you‘re so far away

点击右上角即可分享
微信分享提示