使用connexion快速构建api服务

使用connexion快速构建api服务

connexion

Connecexion是一个在Flask之上的框架,它自动处理使用OpenAPI(以前称为Swagger)定义的HTTP请求,支持规范的v2.0和v3.0。

安装

pip install connexion[swagger-ui]

启动

# app.py
import connexion

app = connexion.FlaskApp(__name__, specification_dir='openapi/')
# app = connexion.FlaskApp(__name__, specification_dir='openapi/', server='tornado')
# specification_dir指定yaml 文件的路径, server 使用tornado作为服务器,默认是flask
app.add_api('my_api.yaml', arguments={'title': '我的api', 'version': 'v1.0'})
# 指定配置文件名称,arguments在yaml文件中使用自定义的变量
app.run(port=8080) 
# 8080 端口运行
openapi: 3.0.0

info:
  title: {{title}}    # app.py 定义的
  version: {{version}}
  description: 我的api接口


servers:
  - url: http://localhost:8099/v1     # v1类似于baseUrl
  
paths:
  /:       # 访问路径
    get:
      summary: index 页面
      operationId: you_function
      responses:
        '200':
          description: index页面
          content:
            'text/plain':
              schema:
                type: string

api 配置认证

      ......
      # 在访问路径下面添加这个参数,给api增加token认证
      security:
        - jwt: ['secret'] 

# 添加token认证解析
components:
  securitySchemes:
    jwt:
      type: http
      scheme: bearer
      bearerFormat: JWT
      x-bearerInfoFunc: your_function
 

ui测试界面

# 默认启动的时候在api根路径 /ui/可以进入swagger ui 界面

    app = connexion.FlaskApp(__name__, server='tornado')
    options = {"serve_spec": False, "swagger_ui": False} # 加入这个关闭swagger ui 界面
    app.add_api('api.yaml', arguments={'title': '我的api', 'version': 'v1.0'}, options=options)
    app.run(port=8999)

demo

https://github.com/lybtt/coding_demo/tree/master/connexion_demo

# python 

右下角对话与我联系。


Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×