先寫一個簡單的 myapi.yaml: (copy from pet.yaml)
openapi: 3.0.0
info:
version: 1.0.0
title: Hello API
description: An API to return hello in request language
servers:
- url: http://127.0.0.1:5000/v1
description: local server
paths:
/api:
get:
tags:
- Hello
description: Return hello in specified language
parameters:
- in: query
name: lang
required: true
description: language
schema:
type: string
example: es
responses:
'200':
description: hello in
content:
text/plain:
schema:
type: string
example: hoa
然後 codegen..
$swagger_py_codegen --swagger-doc myapi.yaml site --ui --spec然後為 api get 增加動作:
diff --git a/v1/api/api.py b/v1/api/api.py
index 2efe114..50aacd3 100644
--- a/v1/api/api.py
+++ b/v1/api/api.py
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
-from flask import request, g
+from flask import request, g, make_response
from . import Resource
from .. import schemas
@@ -10,6 +10,6 @@ from .. import schemas
class Api(Resource):
def get(self):
- print(g.args)
+ print(request.args)
- return None, 200, None
\ No newline at end of file
+ return make_response(request.args['lang'],200)
然後到 site/site 下啟動 resetfule and ui server:
python __init__py開啟覽器,到 swagger-ui 位置: http://127.0.0.1:5000/static/swagger-ui/index.html。
就可以用 swagger-ui,測試剛剛寫的 restfule server。
有些要注意的地方..
因為啟動的 __init__.py 有設定 :
app.register_blueprint(
v1.bp,
url_prefix='/v1')
所以會在後面 v1/routes.py 中, path-handler 定義的位址加上 /v1/:
routes = [
dict(resource=Api, urls=['/api'], endpoint='api'),
]
上面 /api 會變成 /v1/api,所以 myapi.yaml 的 servers 就要加上 /v1 ,這樣 swagger-ui 才能對正確的 url 動作。
這個github project 就是上面的說明,增加了 new user, userlist 的 api: 有比較多的 api 可以測試。
沒有留言:
張貼留言