Skip to content

Commit 8d5bced

Browse files
committed
Add documentation for custom formatters
1 parent 89ec335 commit 8d5bced

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

README.rst

+28
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,34 @@ Pass custom defined media type deserializers dictionary with supported mimetypes
177177
178178
result = validator.validate(request, response)
179179
180+
Formats
181+
*******
182+
183+
OpenAPI defines a `format` keyword that hints at how a value should be interpreted, e.g. a `string` with the type `date` should conform to the RFC 3339 date format.
184+
185+
Openapi-core comes with a set of built-in formatters, but it's also possible to add support for custom formatters for `RequestValidator` and `ResponseValidator`.
186+
187+
Here's how could add support for a `usdate` format that handles dates of the form MM/DD/YYYY:
188+
189+
.. code-block:: python
190+
from datetime import datetime
191+
import re
192+
193+
class USDateFormatter:
194+
def validate(self, value) -> bool:
195+
return bool(re.match(r"^\d{1,2}/\d{1,2}/\d{4}$", value))
196+
197+
def unmarshal(self, value):
198+
return datetime.strptime(value, "%m/%d/%y").date
199+
200+
201+
custom_formatters = {
202+
'usdate': USDateFormatter(),
203+
}
204+
205+
validator = ResponseValidator(spec, custom_formatters=custom_formatters)
206+
207+
result = validator.validate(request, response)
180208
181209
Integrations
182210
############

0 commit comments

Comments
 (0)