Skip to main content

FastAPI request validation with i18n error message

Reason this release was yanked:

testing

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

  1. publish locales to your app path
poetry run publish-locale <your-path>
  1. add middlewares 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
)
  1. start use it

there's 3 way to set locale

  1. set accept-language header to your request
  2. set an API with locale in path
  3. 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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_validation_i18n-0.1.61.tar.gz (14.3 kB view hashes)

Uploaded Source

Built Distribution

fastapi_validation_i18n-0.1.61-py3-none-any.whl (12.6 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page