Skip to content

GIScience/fastapi-i18n

Repository files navigation

FastAPI Internationalization (i18n)

Build Status Sonarcloud Status LICENSE status: active

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.

Installation

uv add git+https://gitlab.heigit.org/mschaub/fastapi-i18n.git

Prerequisites

A locale directory adhering to the GNU gettext message catalog API containing translated messages. See chapter on Babel for more details.

Configuration

export FASTAPI_I18N_LOCALE_DIR="paht/to/locale/dir"
export FASTAPI_I18N_LOCALE_DEFAULT="de"

Usage

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 an complete example see tests.

Babel

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 locale

To update existing locale run update instead of init run:

pybabel extract -F babel.cfg -o messages.pot .
pybabel update -i messages.pot -d locale

Roadmap

  • 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")

Alternatives

About

FastAPI Internationalization (i18n)

Resources

License

LGPL-3.0, GPL-3.0 licenses found

Licenses found

LGPL-3.0
COPYING.LESSER
GPL-3.0
COPYING

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published