Python Friday #230: Fix the PydanticJsonSchemaWarning in FastAPI

While I was preparing the next post, I run into an annoying warning that I wanted to fix before I add one additional feature to the minimalistic to-do application. Let us explore what I had to do to find the reason for the warning and how I could fix the problem.

This post is part of my journey to learn Python. You find the code for this post in my PythonFriday repository on GitHub.

 

The warning

When I run the tests for the to-do application, I got this warning message:

====== warnings summary =======
minimal_todo/tests/test_todo.py::test_docs_endpoint_works
C:\*****\Python312\Lib\site-packages\pydantic\json_schema.py:2158: PydanticJsonSchemaWarning: Default value is not JSON serializable; excluding default from JSON schema [non-serializable-default]
warnings.warn(message, PydanticJsonSchemaWarning)

— Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html

It took me a while to track down the source, but it was the test running against the endpoint behind the API documentation that caused this warning. Knowing this, I could get much faster feedback by running only that single test:

 

The source of the problem

The warning showed me that the problem is somewhere within my two Pydantic models. It could either be TaskInput or TaskOutput:

I wasted a lot of time with the TaskOutput when in fact the TaskInput model had the problem. Somehow the length validation no longer wanted to serialize for the OpenAPI documentation.

 

The fix for the problem

Instead of validating the length with a Field, I switched the check to a validator method as we already did for the due_date:

With this change, I could run the test again and this time the warning was gone. Since I kept the warning generic, it matched what the other tests expected and so I did not need to fix any tests at all.

 

Next

This detour was annoying, but it can help you to track down similar problems in your FastAPI application. I hope what I got here is now a bit more stable and will not need any more attention.
Next week we look at APIRouter and how it offers us a similar benefit as Blueprint does for Flask.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.