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
- For FastAPI >=0.100.0 and pydantic v2, please use ^0.4.0
- For FastAPI < 0.100.0 nad pydantic v1, please use ^0.3.0
- 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]
Setup in FastAPI
- use
setup
from fastapi_validation_i18n import setup
from fastapi import FastAPI
app = FastAPI()
setup(app, locale_path=..., locale_list=...)
- use middleware and exception handler
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
)
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
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.4.1.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | b4b07ac23a02a3e1caa2417f070d608b23fa1234b0443c256c83e90e5da8dffa |
|
MD5 | 6c61d4197ce545cdb1ce56852a811607 |
|
BLAKE2b-256 | db129c4944ec6d663c40c2330e315f23f491b3921dee65dc6faf3594cc184ad3 |
Close
Hashes for fastapi_validation_i18n-0.4.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 2fbda2a018434e5976ff2135f460994e0179daebd09e347bd61e8e5b20c909fb |
|
MD5 | 0d3f54b535665748962666b4d722e962 |
|
BLAKE2b-256 | 8f8690133b73a72550ebeed666c94290f37b455c6bd1749af4db8d3883bb20e7 |