This package is implemented as a FastAPI dependency which initializes translations using the gettext module and makes them available throughout the request lifecycle using a Conext Variable.
uv add fastapi-i18nA locale directory adhering to the GNU gettext message catalog API containing translated messages. See chapter on Babel for more details.
export FASTAPI_I18N__LOCALE_DIR="paht/to/locale/dir" # required
export FASTAPI_I18N__LOCALE_DEFAULT="de" # defaults to "en"
# To ignore the Accept-Language header for certain referes set:
export FASTAPI_I18N__IGNORE_REFERES="https://api.quality.ohsome.org/v1/docs"from fastapi import FastAPI, Depends
from fastapi_i18n import i18n, _
app = FastAPI(dependencies=[Depends(i18n)])
@app.get("/")
def root():
return _("Hello from fastapi-i18n!")Set Accept-Language header for requests to get a translated version of the response.
For a complete example see tests.
Babel is useful for working with GNU gettext message catalogs.
To add new locale and use babel to extract messages from Python files run:
echo "[python: **.py]" > babel.cfg
pybabel extract -F babel.cfg -o messages.pot .
pybabel init -i messages.pot -d locale -l de
# Now translate messages in locale/de/LC_MESSAGES/messages.po
# Then compile locale:
pybabel compile -d localeTo update existing locale run update instead of init run:
pybabel extract -F babel.cfg -o messages.pot .
pybabel update -i messages.pot -d locale- Support configuration via
pyproject.toml - Validate locale string
- Support setting locale using query parameter
- Support configuration of domain (currently defaults to "messages")