FastAPI request validation with i18n error message
Project description
error message with i18n support in FastAPI
{
"errors": [
{
"loc": [
"body",
"string"
],
"msg": "確保此值最多有 10 個字符",
"type": "value_error.any_str.max_length",
"ctx": {
"limit_value": 10
}
},
{
"loc": [
"body",
"nested",
"body"
],
"msg": "確保此值最多有 2 個字符",
"type": "value_error.any_str.max_length",
"ctx": {
"limit_value": 2
}
},
{
"loc": [
"body",
"nested",
"inner",
"inner_body"
],
"msg": "確保此值最多包含 2 個項目",
"type": "value_error.list.max_items",
"ctx": {
"limit_value": 2
}
},
{
"loc": [
"body",
"nested",
"inner",
"cat"
],
"msg": "鑑別器 'color' 和值 'ccc' 不匹配(允許的值: 'black', 'white')",
"type": "value_error.discriminated_union.invalid_discriminator",
"ctx": {
"discriminator_key": "color",
"discriminator_value": "ccc",
"allowed_values": "'black', 'white'"
}
}
]
}
Attention
- support pydantic v1 only now(2023/08/16)
- built-in locales are zh-TW, en-US, ja-JP, you can change the locales by yourself
How to run
- publish locales to your app path
# default to "locale" in your project path
poetry run publish-locale <your-path> [--locale]
- add middleware and exception handler to your FastAPI app
from fastapi import FastAPI
from fastapi_validation_i18n import I18nMiddleware, i18n_exception_handler
from fastapi.exceptions import RequestValidationError
app = FastAPI()
app.add_middleware(I18nMiddleware, locale_path='your-publish-path')
app.add_exception_handler(
RequestValidationError,
i18n_exception_handler
)
- start use it
there's 3 way to set locale
- set
accept-language
header to your request - set an API with
locale
in path - set
locale
query parameter to your request
you can see the example for more detail
todo
- support pydantic v2
- other i18n support
- support FastAPI>0.99
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Close
Hashes for fastapi_validation_i18n-0.3.4.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | efcf73a0f2f1e0a4bc8e025b21d48efecded179b722c755e4166268151d529ad |
|
MD5 | f68183d80b09b22fa5715ca8c92e4d80 |
|
BLAKE2b-256 | a66375876fc9dec05867ead4bd5acab5b280c1f7842ac88ea91d04979470e691 |
Close
Hashes for fastapi_validation_i18n-0.3.4-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 84be2005c51cf93fc5c43c1b102a69442f6d867f506c0d17615af9f05adbdc7b |
|
MD5 | 8458ff1fd44b3020a3704c5dbb12d083 |
|
BLAKE2b-256 | bd649dbd53bc9a357411186e94e6e0d5173d1041d39ceb21df9787f7245631c0 |