Skip to content

Commit 99371d7

Browse files
committed
Add documentation for custom formatters
1 parent 89ec335 commit 99371d7

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

README.rst

+29
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,35 @@ 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 you could add support for a ``usdate`` format that handles dates of the form MM/DD/YYYY:
188+
189+
.. code-block:: python
190+
191+
from datetime import datetime
192+
import re
193+
194+
class USDateFormatter:
195+
def validate(self, value) -> bool:
196+
return bool(re.match(r"^\d{1,2}/\d{1,2}/\d{4}$", value))
197+
198+
def unmarshal(self, value):
199+
return datetime.strptime(value, "%m/%d/%y").date
200+
201+
202+
custom_formatters = {
203+
'usdate': USDateFormatter(),
204+
}
205+
206+
validator = ResponseValidator(spec, custom_formatters=custom_formatters)
207+
208+
result = validator.validate(request, response)
180209
181210
Integrations
182211
############

0 commit comments

Comments
 (0)