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"
export FASTAPI_I18N_LOCALE_DEFAULT="de"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 not a dependency of FastAPI i18n, but it 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- Move to GitHub
- Support configuration via
pyproject.toml - Validate locale string
- Support setting locale using query parameter
- Support configuration of domain (currently defaults to "messages")