Swagger自动化了与api有关的工作,大致流程是这样:
- 从后端代码生成schema
- 在后端通过schema生成api文档( 1,2其实是一步)
- 在前端请求schema,生成http的请求代码,无须再手写
// swagger.js
import Swagger from 'swagger-client'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import Vue from 'vue'
var host = process.env.NODE_ENV === 'development' ? '127.0.0.1:8000' : '188.166.122.210'
const SCHEMA_URL = `http://${host}/schema/?format=openapi`
export default (apiName, params = {}, isAuth = false) => {
var authObj = isAuth ? { requestInterceptor } : {}
return Swagger({ url: SCHEMA_URL, ...authObj })
.then(client => {
console.log(client.apis.api)
return client.apis.api[apiName](params, authObj)
})
}
function requestInterceptor (req) {
req.headers.Authorization = `apikey admin:${Vue.ls.get(ACCESS_TOKEN)}`
return req
}
// Then let's use it in someComponent.js
import swagger from '@/swagger.js'
swagger(`v1_xadmin_user_update`, {
object_id: this.formatRecord.object_id,
data: putObj
}, true)
.then(res => {
this.$emit('onGoBack')
})
{
http: {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
# we don't want nginx trying to do something clever with
# redirects, we set the Host: header above already.
proxy_redirect off;
}
}
class SiteViewSet(AdminModelViewSet):
queryset = User.objects.all()
serializer_class = someSerializer
...
Django: Install the fork one
$ pip install django-rest-swagger-zhc
Then using it as same as django-rest-swagger
totally.
Links: