Package: opyapi
OpyAPI - JsonSchema and OpenAPI tools for pythonJsonSchema and OpenAPI tools for python.FeaturesValidation builder for json schemaCustom string formatters supportFull JsonSchema draft-7 supportSupport for JsonReferences, $anchorDataclass generation from OpenAPI schemaGreat performanceInstallationWith pip,pipinstallopyapior through poetrypoetryaddopyapiUsageIt is recommended to get familiar with json-schema if you haven't yet.Understanding Json Schemais a great place to start and learn Json Schema's basicsSimple usageLibrary can be used to validate data, against defined json-schema like so:fromopyapiimportvalidateassertvalidate({"name":"Test","age":12},{"type":"object","properties":{"name":{"type":"string",},"age":{"type":"integer",}}})Using referencesValidating documents against complex schemas is also possible,
please consider the following example with json references:fromopyapiimportvalidateschema={"type":"object","properties":{"name":{"type":"string","minLength":2,},"email":{"$ref":"#/$defs/email"}},"$defs":{"email":{"type":"string","format":"email"}}}validate({"name":"Bob","email":"bob@test.com"},schema)Custom string formats supportfromopyapiimportStringFormat,validateimportredefmy_format_validator(value:str)->str:ifre.match("^my-",value):returnvalueraiseValueError(f"Could not validate{value}")StringFormat["my-format"]=my_format_validatorvalidate("my-test",{"type":"string","format":"my-format"})# passesvalidate("test",{"type":"string","format":"my-format"})# failsIn the above exampleopyapi.StringFormatis used to register new custom format,
which is recognised during validation.Re-using validatorsThere are scenarios where same validator should be used multiple times,
in these scenarios to improve performance it is better to usebuild_validator_forwhich returns a validator function for the passed schema:fromopyapiimportbuild_validator_formy_validator=build_validator_for({"type":"object","properties":{"name":{"type":"string","minLength":2,},"email":{"type":"string","format":"email",}},})assertmy_validator({"name":"Bob","email":"bob@email.com"})Catching errorsopyapiprovides versatile error package, which is really simple to use. You are only required to define try/except
block within you can catch one of the errors defined in the package depending on your scenario.fromopyapiimportbuild_validator_forfromopyapi.errorsimportValidationErrormy_validator=build_validator_for({"type":"object","properties":{"name":{"type":"string","minLength":2,},"email":{"type":"string","format":"email",}},})try:my_validator({"name":"Bob","email":"invalid"})exceptValidationErrorase:print(f"Validation failed from the reason:{e}")Errors structureThe following graph represents exception used inopyapi.
All exceptions are part ofopyapi.errorsmodule.ValueError
    ┗━ ValidationError
            ┣━ TypeValidationError
            ┣━ EnumValidationError
            ┣━ FormatValidationError
            ┣━ ItemsValidationError
            ┃           ┣━ UniqueItemsValidationError
            ┃           ┣━ AdditionalItemsValidationError
            ┃           ┣━ MinimumItemsValidationError
            ┃           ┗━ MaximumItemsValidationError
            ┣━ MultipleOfValidationError
            ┣━ ComparisonValidationError
            ┃           ┣━ EqualityValidationError
            ┃           ┗━ RangeValidationError
            ┃                       ┣━ MinimumValidationError
            ┃                       ┣━ MaximumValidationError
            ┃                       ┣━ ExclusiveMinimumValidationError
            ┃                       ┗━ ExclusiveMaximumValidationError
            ┗━ ObjectValidationError
                        ┣━ PropertyValidationError
                        ┃           ┣━ RequiredPropertyValidationError
                        ┃           ┣━ PropertyValueValidationError
                        ┃           ┣━ PropertyNameValidationError
                        ┃           ┗━ AdditionalPropertiesValidationError
                        ┣━ ObjectSizeValidationError
                        ┃           ┣━ MinimumPropertiesValidationError
                        ┃           ┗━ MaximumPropertiesValidationError
                        ┗━ DependencyValidationErroropyapi.errors.ValidationErrorGeneric validation error.opyapi.errors.TypeValidationErrorRaised when passed type does not conform type defined in the schema.Can be triggered by following example schema:{"type":"integer"}opyapi.errors.EnumValidationErrorRaised when value does not conform enum definition.Can be triggered by following example schema:{"enum":["integer","string","boolean"]}opyapi.errors.FormatValidationErrorRaised when value does not conform defined format in string schema.Can be triggered by following example schema:{"type":"string","format":"date-time"}opyapi.errors.ItemsValidationErrorGeneric Exception raised when validation of an array fails for some reason.opyapi.errors.UniqueItemsValidationErrorRaised when items in an array are expected to be unique but passed value does not conform the requirement.
This exception extends genericopyapi.errors.ItemsValidationErrorexception.Can be triggered by following example schema:{"type":"array","uniqueItems":true}opyapi.errors.AdditionalItemsValidationErrorRaised when additional items in an array either does not conform the schema or are not expected.
This exception extends genericopyapi.errors.ItemsValidationErrorexception.Can be triggered by the following schema:{"type":"array","items":[{"type":"string"},{"type":"integer"}],"additionalItems":false}opyapi.errors.MinimumItemsValidationError,opyapi.errors.MaximumItemsValidationErrorRaised when number of items in an array does not conform maximum or minimum items specified in schema.
This exception extends genericopyapi.errors.ItemsValidationErrorexception.Can be triggered by following example schema:{"type":"array","minimumItems":2,"MaximumItems":10}opyapi.errors.MultipleOfValidationErrorRaised when validated number is not multiplication of passed value.Can be triggered by following example schema:{"type":"numerical","multipleOf":2}opyapi.errors.ComparisonValidationErrorRaised when comparison operation fails. This is a generic exception used by other comparison errors.opyapi.errors.EqualityValidationErrorRaised when validated value is not the same as defined expected value. This exception extendsopyapi.errors.ComparisonValidationError.Can be triggered by following example schema:{"const":"test"}opyapi.errors.RangeValidationErrorRaised when (exclusive) minimum, (exclusive) maximum comparisons fail. This exception extendsopyapi.errors.ComparisonValidationError.opyapi.errors.MinimumValidationError,opyapi.errors.MaximumValidationError,opyapi.errors.ExclusiveMinimumValidationError,opyapi.errors.ExclusiveMaximumValidationErrorRaised when passed numerical (or integer) value is not within expected range defined in schema.Can be triggered by the following example schema:{"type":"numerical","minimum":2}opyapi.errors.ObjectValidationErrorGeneric exception raised when validation of an object fails for some reason.opyapi.errors.PropertyValidationErrorGeneric exception raised when validation of object's property fails for some reason.
This exception extendsopyapi.errors.ObjectValidationErrorexception.opyapi.errors.RequiredPropertyValidationErrorRaised when required property is not present in passed object.
This exception extendsopyapi.errors.PropertyValidationErrorexception.Can be triggered by the following example schema:{"type":"object","properties":{"name":{"type":"string"}},"required":["name"]}opyapi.errors.PropertyValueValidationErrorRaised when property contains invalid value.
This exception extendsopyapi.errors.PropertyValidationErrorexception.Can be triggered by the following example schema:{"type":"object","properties":{"name":{"type":"string"}}}opyapi.errors.PropertyNameValidationErrorRaised when property's names does not conform defined schema.
This exception extendsopyapi.errors.PropertyValidationErrorexception.Can be triggered by the following example schema:{"type":"object","properties":{"name":{"type":"string"}},"propertyNames":{"pattern":"^x-"}}opyapi.errors.AdditionalPropertiesValidationErrorRaised when additional properties are not allowed or set schema is not followed.
This exception extendsopyapi.errors.PropertyValidationErrorexception.Can be triggered by the following example schema:{"type":"object","properties":{"name":{"type":"string"}},"additionalProperties":false}opyapi.errors.ObjectSizeValidationErrorGeneric exception raised when number of properties does not conform defined schema.
This exception extendsopyapi.errors.ObjectValidationErrorexception.opyapi.errors.MinimumPropertiesValidationError,opyapi.errors.MaximumPropertiesValidationErrorGeneric exception raised when number of properties does not conform defined schema.
These exceptions extendopyapi.errors.ObjectSizeValidationErrorexception.Can be triggered by the following example schema:{"type":"object","properties":{"name":{"type":"string"}},"minProperties":2,"maxProperties":10}opyapi.errors.DependencyValidationErrorRaised when dependent properties are defined in the schema but not provided in a passed object.
This exception extendsopyapi.errors.ObjectValidationErrorexception.Can be triggered by the following example schema:{"type":"object","properties":{"name":{"type":"string"}},"dependentRequired":{"name":["first_name","last_name"]}}APIvalidate(obj: typing.Any, schema: typing.Union[dict, opyapi.JsonSchema]): typing.AnyValidates passed objectobj, and if valid returns the object, otherwise raises aValueErrorexception.fromopyapiimportvalidateassertvalidate({"name":"Test","age":12},{"type":"object","properties":{"name":{"type":"string",},"age":{"type":"integer",}}})build_validator_for(schema: typing.Union[dict, JsonSchema]) -> CallableCreates validator function for passed json schema and returns it as a result.fromopyapiimportbuild_validator_forvalidator=build_validator_for({"type":"object","properties":{"name":{"type":"string",},"age":{"type":"integer",}}})