在Linux环境中,使用Swagger进行数据验证和序列化通常涉及以下几个步骤:
安装Swagger工具:
swagger-ui-python和flask-swagger-ui。pip install swagger-ui-python flask-swagger-ui
定义API规范:
openapi: 3.0.0
info:
title: Sample API
version: 1.0.0
paths:
/items:
get:
summary: List all items
responses:
'200':
description: An array of items
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Item'
components:
schemas:
Item:
type: object
properties:
id:
type: integer
format: int64
name:
type: string
集成Swagger到Flask应用:
flask-swagger-ui将Swagger UI集成到你的Flask应用中。from flask import Flask, jsonify
from flask_swagger_ui import get_swaggerui_blueprint
app = Flask(__name__)
SWAGGER_URL = '/swagger-ui'
API_URL = '/static/swagger.json'
swaggerui_blueprint = get_swaggerui_blueprint(
SWAGGER_URL,
API_URL,
config={
'app_name': "Sample API"
}
)
app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL)
@app.route(API_URL)
def swagger():
return jsonify({
"openapi": "3.0.0",
"info": {
"title": "Sample API",
"version": "1.0.0"
},
"paths": {
"/items": {
"get": {
"summary": "List all items",
"responses": {
"200": {
"description": "An array of items",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Item"
}
}
}
}
}
}
}
}
},
"components": {
"schemas": {
"Item": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
}
}
}
}
}
})
if __name__ == '__main__':
app.run(debug=True)
数据验证:
marshmallow库来进行数据验证和序列化。pip install marshmallow
from marshmallow import Schema, fields, ValidationError
class ItemSchema(Schema):
id = fields.Int(required=True)
name = fields.Str(required=True)
item_schema = ItemSchema()
items_schema = ItemSchema(many=True)
@app.route('/items', methods=['POST'])
def add_item():
json_data = request.get_json()
try:
data = item_schema.load(json_data)
except ValidationError as err:
return jsonify(err.messages), 400
# Save the item to the database (not shown here)
# ...
return jsonify(item_schema.dump(data)), 201
通过以上步骤,你可以在Linux环境中使用Swagger进行数据验证和序列化。Swagger UI提供了一个交互式的界面来测试你的API,而Marshmallow则确保了数据的正确性和一致性。