Skip to content

Instantly share code, notes, and snippets.

@ZhouHansen
Last active April 18, 2019 06:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZhouHansen/06b90f7441dac93a7886e4ce4a729226 to your computer and use it in GitHub Desktop.
Save ZhouHansen/06b90f7441dac93a7886e4ce4a729226 to your computer and use it in GitHub Desktop.
Using swagger with vue, django and ngnix

Swagger自动化了与api有关的工作,大致流程是这样:

  1. 从后端代码生成schema
  2. 在后端通过schema生成api文档( 1,2其实是一步)
  3. 在前端请求schema,生成http的请求代码,无须再手写

Vue client example:

// 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')
  })

Ngnix: add below confs to ngnix configure file

{
  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;
  }
}

Django: Ensure serializer_class is set

class SiteViewSet(AdminModelViewSet):
    queryset = User.objects.all()
    serializer_class = someSerializer
    ...
  $ pip install django-rest-swagger-zhc

Then using it as same as django-rest-swagger totally.

Links:

https://github.com/marcgibbons/django-rest-swagger

https://github.com/swagger-api/swagger-js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment