⚡️ Use TypeAdapter.validate_json instead of json.loads#13951
Conversation
a558ae5 to
3160247
Compare
TypeAdapter.validate_json for Pydantic v2
|
This pull request has a merge conflict that needs to be resolved. |
3160247 to
79b4288
Compare
Merging this PR will improve performance by 24.77%
|
| Benchmark | BASE |
HEAD |
Efficiency | |
|---|---|---|---|---|
| ⚡ | test_sync_receiving_large_payload |
12.1 ms | 9.7 ms | +24.64% |
| ⚡ | test_async_receiving_large_payload |
11.9 ms | 9.5 ms | +24.9% |
Tip
Curious why this is faster? Comment @codspeedbot explain why this is faster on this PR, or directly use the CodSpeed MCP with your agent.
Comparing dolfinus:feature/pydanticv2-validate-json (7348364) with master (59d4a80)1
Footnotes
-
No successful run was found on
master(dbfd55c) during the generation of this report, so 59d4a80 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩
79b4288 to
05540da
Compare
TypeAdapter.validate_json for Pydantic v2TypeAdapter.validate_json instead of json.loads
4a76701 to
e26fe00
Compare
TypeAdapter.validate_json instead of json.loadsTypeAdapter.validate_json instead of json.loads
|
This pull request has a merge conflict that needs to be resolved. |
e26fe00 to
2688001
Compare
2688001 to
7348364
Compare
7348364 to
34532c6
Compare
|
This PR modifies dependency files ( If you need a dependency change, please open a discussion describing what you need and why. Closing this PR automatically. |
|
This bot is quite annoying... #15617 |
#14962 replaced
json.dumpswith pydantic v2TypeAdapter.serialize_json(). This is the same, but for body parsing - replacejson.loadswithTypeAdapter.validate_json().See also #13949
Now this gives only a moderate speedup, nothing huge. The larger the request body, the larger the speedup.
Currently optimization can be applied only to POST handler with just one body field.
Small benchmark
requirements.txt
app.py
locustfile.py
Before - 2228RPS,

json.loadstook 9.8% andtype_adapter.validate_pythontook 1% = 11% combinedfastapi_with_json_loads.tar.gz
After - 2570RPS,

type_adapter.validate_jsontook 7.17%fastapi_with_typeadapter_json.tar.gz
Caveats - if route handle contains multiple fields with Body() annotation, json will be parsed for each field. Changing this requires substantial rewrite of body parsing, e.g. merging all body fields into one pydantic class and using it's
model_validate_json()method for body parsing. I'm not ready for this type of change, so this can be considered as proof-of-concept.Bump pydantic minimal version to 2.10.0 because of this issue with validate_json appears on versions below pydantic-core 2.24.1