Skip to content

Commit 23be4ca

Browse files
committed
validate shortcut
1 parent 4a3cdf9 commit 23be4ca

File tree

3 files changed

+34
-5
lines changed

3 files changed

+34
-5
lines changed

README.rst

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ Simple usage
4343

4444
.. code-block:: python
4545
46-
from openapi_schema_validator import OAS30Validator, oas30_format_checker
46+
from openapi_schema_validator import validate
4747
4848
# A sample schema
4949
schema = {
@@ -61,20 +61,37 @@ Simple usage
6161
"minimum": 0,
6262
"nullable": True,
6363
},
64+
"birth-date": {
65+
"type": "string",
66+
"format": "date",
67+
}
6468
},
6569
"additionalProperties": False,
6670
}
6771
68-
validator = OAS30Validator(schema)
6972
# If no exception is raised by validate(), the instance is valid.
70-
validator.validate({"name": "John", "age": 23})
73+
validate({"name": "John", "age": 23}, schema)
7174
72-
validator.validate({"name": "John", "city": "London"})
75+
validate({"name": "John", "city": "London"}, schema)
7376
7477
Traceback (most recent call last):
7578
...
7679
ValidationError: Additional properties are not allowed ('city' was unexpected)
7780
81+
82+
You can also check format for primitive types
83+
84+
.. code-block:: python
85+
86+
from openapi_schema_validator import oas30_format_checker
87+
88+
validate({"name": "John", "birth-date": "-12"}, schema, format_checker=oas30_format_checker)
89+
90+
Traceback (most recent call last):
91+
...
92+
ValidationError: '-12' is not a 'date'
93+
94+
7895
Related projects
7996
################
8097
* `openapi-core <https://github.com/p1c2u/openapi-core>`__
Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# -*- coding: utf-8 -*-
22
from openapi_schema_validator._format import oas30_format_checker
3+
from openapi_schema_validator.shortcuts import validate
34
from openapi_schema_validator.validators import OAS30Validator
45

56
__author__ = 'Artur Maciag'
@@ -8,4 +9,4 @@
89
__url__ = 'https://github.com/p1c2u/openapi-schema-validator'
910
__license__ = 'BSD 3-Clause License'
1011

11-
__all__ = ['OAS30Validator', 'oas30_format_checker']
12+
__all__ = ['validate', 'OAS30Validator', 'oas30_format_checker']
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
from jsonschema.exceptions import best_match
2+
3+
from openapi_schema_validator.validators import OAS30Validator
4+
5+
6+
def validate(instance, schema, cls=OAS30Validator, *args, **kwargs):
7+
cls.check_schema(schema)
8+
validator = cls(schema, *args, **kwargs)
9+
error = best_match(validator.iter_errors(instance))
10+
if error is not None:
11+
raise error

0 commit comments

Comments
 (0)