1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
|
"""
Example of JSON body validation in POST with various kinds of specs and views.
"""
try:
from http import HTTPStatus
except ImportError:
import httplib as HTTPStatus
from flask import Blueprint
from flask import Flask
from flask import jsonify
from flask import request
from flasgger import Schema
from flasgger import Swagger
from flasgger import SwaggerView
from flasgger import fields
from flasgger import swag_from
from flasgger import validate
# Examples include intentionally invalid defaults to demonstrate validation.
_TEST_META_SKIP_FULL_VALIDATION = True
app = Flask(__name__)
swag = Swagger(app)
test_specs_1 = {
"tags": [
"users"
],
"parameters": [
{
"name": "body",
"in": "body",
"required": True,
"schema": {
"id": "User",
"required": [
"username",
"age"
],
"properties": {
"username": {
"type": "string",
"description": "The user name.",
"default": "Sirius Black"
},
"age": {
"type": "integer",
"description": "The user age (should be integer)",
"default": "180"
},
"tags": {
"type": "array",
"description": "optional list of tags",
"default": [
"wizard",
"hogwarts",
"dead"
],
"items": {
"type": "string"
}
}
}
}
}
],
"responses": {
"200": {
"description": "A single user item",
"schema": {
"$ref": "#/definitions/User"
}
}
}
}
@app.route("/manualvalidation", methods=['POST'])
@swag_from("test_validation.yml")
def manualvalidation():
"""
In this example you need to call validate() manually
passing received data, Definition (schema: id), specs filename
"""
data = request.json
validate(data, 'User', "test_validation.yml")
return jsonify(data)
@app.route("/validateannotation", methods=['POST'])
@swag.validate('User')
@swag_from("test_validation.yml")
def validateannotation():
"""
In this example you use validate(schema_id) annotation on the
method in which you want to validate received data
"""
data = request.json
return jsonify(data)
@app.route("/autovalidation", methods=['POST'])
@swag_from("test_validation.yml", validation=True)
def autovalidation():
"""
Example using auto validation from yaml file.
In this example you don't need to call validate() because
`validation=True` on @swag_from does that for you.
In this case it will use the same provided filename
and will extract the schema from `in: body` definition
and the data will default to `request.json`
or you can specify:
@swag_from('file.yml',
validation=True,
definition='User',
data=lambda: request.json, # any callable
)
"""
data = request.json
return jsonify(data)
@app.route("/autovalidationfromspecdict", methods=['POST'])
@swag_from(test_specs_1, validation=True)
def autovalidation_from_spec_dict():
"""
Example using data from dict to validate.
In this example you don't need to call validate() because
`validation=True` on @swag_from does that for you.
In this case it will use the same provided filename
and will extract the schema from `in: body` definition
and the data will default to `request.json`
or you can specify:
@swag_from('file.yml',
validation=True,
definition='User',
data=lambda: request.json, # any callable
)
"""
data = request.json
return jsonify(data)
class User(Schema):
username = fields.Str(required=True, default="Sirius Black")
# wrong default "180" to force validation error
age = fields.Int(required=True, min=18, default="180")
tags = fields.List(fields.Str(), default=["wizard", "hogwarts", "dead"])
class UserPostView(SwaggerView):
tags = ['users']
parameters = User
responses = {
200: {
'description': 'A single user item',
'schema': User
}
}
validation = True
def post(self):
"""
Example using marshmallow Schema
validation=True forces validation of parameters in body
---
# This value overwrites the attributes above
deprecated: true
"""
return jsonify(request.json)
app.add_url_rule(
'/schemevalidation',
view_func=UserPostView.as_view('schemevalidation'),
methods=['POST']
)
# ensure the same works for blueprints
example_blueprint = Blueprint(
"example", __name__, url_prefix='/blueprint')
@example_blueprint.route("/autovalidationfromdocstring", methods=['POST'])
@swag.validate('Officer')
def autovalidation_from_docstring():
"""
Test validation using JsonSchema
The default payload is invalid, try it, then change the age to a
valid integer and try again
---
tags:
- officer
parameters:
- name: body
in: body
required: true
schema:
id: Officer
required:
- name
- age
properties:
name:
type: string
description: The officer's name.
default: "James T. Kirk"
age:
type: integer
description: The officer's age (should be integer)
default: "138"
tags:
type: array
description: optional list of tags
default: ["starfleet", "captain", "enterprise", "dead"]
items:
type: string
responses:
200:
description: A single officer item
schema:
$ref: '#/definitions/Officer'
"""
data = request.json
return jsonify(data)
@example_blueprint.route('/manualvalidation', methods=['POST'])
@swag_from("test_validation.yml")
def manualvalidation_bp():
"""
In this example you need to call validate() manually
passing received data, Definition (schema: id), specs filename
"""
data = request.json
validate(data, 'User', "test_validation.yml")
return jsonify(data)
@example_blueprint.route('/autovalidation', methods=['POST'])
@swag_from("test_validation.yml", validation=True)
def autovalidation_bp():
"""
Example using auto validation from yaml file.
In this example you don't need to call validate() because
`validation=True` on @swag_from does that for you.
In this case it will use the same provided filename
and will extract the schema from `in: body` definition
and the data will default to `request.json`
or you can specify:
@swag_from('file.yml',
validation=True,
definition='User',
data=lambda: request.json, # any callable
)
"""
data = request.json
return jsonify(data)
@example_blueprint.route("/autovalidationfromspecdict", methods=['POST'])
@swag_from(test_specs_1, validation=True)
def autovalidation_from_spec_dict_bp():
"""
Example using data from dict to validate.
In this example you don't need to call validate() because
`validation=True` on @swag_from does that for you.
In this case it will use the same provided filename
and will extract the schema from `in: body` definition
and the data will default to `request.json`
or you can specify:
@swag_from('file.yml',
validation=True,
definition='User',
data=lambda: request.json, # any callable
)
"""
data = request.json
return jsonify(data)
class BPUserPostView(SwaggerView):
tags = ['users']
parameters = User
responses = {
200: {
'description': 'A single user item',
'schema': User
}
}
validation = True
def post(self):
"""
Example using marshmallow Schema
validation=True forces validation of parameters in body
---
# This value overwrites the attributes above
deprecated: true
"""
return jsonify(request.json)
example_blueprint.add_url_rule(
'/schemevalidation',
view_func=BPUserPostView.as_view('schemevalidation'),
methods=['POST']
)
app.register_blueprint(example_blueprint)
def test_swag(client, specs_data):
"""
This test is runs automatically in Travis CI
:param client: Flask app test client
:param specs_data: {'url': {swag_specs}} for every spec in app
"""
apispec = specs_data.get('/apispec_1.json')
assert apispec is not None
paths = apispec.get('paths')
expected_user_paths = (
'/autovalidation',
'/validateannotation',
'/autovalidationfromspecdict',
'/blueprint/autovalidation',
'/blueprint/autovalidationfromspecdict',
'/blueprint/manualvalidation',
'/blueprint/schemevalidation',
'/manualvalidation',
'/schemevalidation',
)
expected_officer_paths = (
'/blueprint/autovalidationfromdocstring',
)
invalid_users = (
"""
{
"username": "Sirius Black",
"age": "180",
"tags": [
"wizard",
"hogwarts",
"dead"
]
}
""",
"""
{
"age": 180,
"tags": [
"wizard"
]
}
""",
)
valid_users = (
"""
{
"username": "Sirius Black",
"age": 180,
"tags": [
"wizard",
"hogwarts",
"dead"
]
}
""",
"""
{
"username": "Ronald Weasley",
"age": 22
}
""",
)
invalid_officers = (
"""
{
"name": "James T. Kirk",
"age": "138",
"tags": [
"captain",
"enterprise",
"dead"
]
}
""",
"""
{
"age": 138,
"tags": [
"captain"
]
}
""",
)
valid_officers = (
"""
{
"name": "James T. Kirk",
"age": 138,
"tags": [
"captain",
"enterprise",
"dead"
]
}
""",
"""
{
"name": "Jean-Luc Picard",
"age": 60
}
""",
)
assert paths is not None and len(paths) > 0
definitions = apispec.get('definitions')
assert definitions is not None
assert definitions.get('User') is not None
assert definitions.get('Officer') is not None
for expected_path in expected_user_paths:
assert paths.get(expected_path) is not None
for invalid_user in invalid_users:
response = client.post(
expected_path, data=invalid_user,
content_type='application/json')
assert response.status_code == HTTPStatus.BAD_REQUEST
for valid_user in valid_users:
response = client.post(
expected_path, data=valid_user,
content_type='application/json')
assert response.status_code == HTTPStatus.OK
for expected_path in expected_officer_paths:
assert paths.get(expected_path) is not None
for invalid_officer in invalid_officers:
response = client.post(
expected_path, data=invalid_officer,
content_type='application/json')
assert response.status_code == HTTPStatus.BAD_REQUEST
for valid_officer in valid_officers:
response = client.post(
expected_path, data=valid_officer,
content_type='application/json')
assert response.status_code == HTTPStatus.OK
if __name__ == "__main__":
app.run(debug=True)
|