Package: fastapi-babel
FastAPI BABELGetpybabbeltools directly within your FastAPI project without hassle.FastAPI Babel is integrated within FastAPI framework and gives you support of i18n, l10n, date and time locales, and all other pybabel functionalities.Features:I18n(Internationalization)Wtform Translation(Lazy Text)l10n(Localization)Date and timelocaleDecimal, NumberlocaleMoney and currencylocale converterlocale selector fromHTTP headerSupportPython:3.6 and later (tested on Python 3.6, 3.12)FastAPI: 0.45.0 +PyBabel: AllInstallationpip install fastapi-babelHow to useinstall FastAPI and FastAPI Babel:pip install fastapiandpip install fastapi_babelmakebabel.pyfile:fromfastapi_babelimportBabel,BabelConfigsconfigs=BabelConfigs(ROOT_DIR=__file__,BABEL_DEFAULT_LOCALE="en",BABEL_TRANSLATION_DIRECTORY="lang",)babel=Babel(configs=configs)if__name__=="__main__":babel.run_cli()makebabel.cfgfilebabel.cfg[python: **.py]Create main.py file:fromfastapi_babelimportBabel,BabelConfigs,_configs=BabelConfigs(ROOT_DIR=__file__,BABEL_DEFAULT_LOCALE="en",BABEL_TRANSLATION_DIRECTORY="lang",)babel=Babel(configs=configs)defmain():babel.locale="en"en_text=_("Hello World")print(en_text)babel.locale="fa"fa_text=_("Hello World")print(fa_text)if__name__=="__main__":main()Extract the messagepybabel extract -F babel.cfg -o messages.pot .Initialize pybabelpybabel init -i messages.pot -d lang -l faGotolang/YOUR_LANGUAGE_CODE/LC_MESSAGES/messages.poandadd your translationto your messages.Go back to the root folder and   Compilepybabel compile -d langRunmain.pypython3 main.pyFastAPI Babel CommandsInstall click at first:pip install clickAdd this snippet to your FasAPI code:...babel.run_cli()...Now just follow the documentation fromstep 5.For more information just take a look at help flag ofmain.pypython main.py --helpWhy FastAPI Babel CLI is recommanded ?FastAPI Babel CLI will eliminate the need of concering the directories and paths, so you can concentrate on the project and spend less time on going forward and backward. You only need to specifydomain name,babel.cfgandlocalization directory.NOTICE:DonotuseFastAPI Babelbeside fastapi runner files (main.pyorrun.py), as uvicorn cli will not work.[========]Using FastAPI Babel in an APIcreate filebabel.pyand write the code below.fromfastapi_babelimportBabel,BabelConfigs,BabelMiddlewareconfigs=BabelConfigs(ROOT_DIR=__file__,BABEL_DEFAULT_LOCALE="en",BABEL_TRANSLATION_DIRECTORY="lang",)app.add_middleware(BabelMiddleware,babel_configs=configs)if__name__=="__main__":Babel(configs).run_cli()extract messages with following commandpython3 babel.py extract -d/--dir {watch_dir}**Notice: ** watch_dir is your project root directory, where the messages will be extracted.Add your own language locale directory, for instancefa.python3 babel.py init -l faGo to ./lang/Fa/.po and add your translations.compile all locale directories.python3 babel.py compilefromfastapiimportFastAPI,Requestfromfastapi_babelimport_from.babelimportbabelapp=FastAPI()app.add_middleware(BabelMiddleware,babel_configs=BabelConfigs(ROOT_DIR=__file__,BABEL_DEFAULT_LOCALE="en",BABEL_TRANSLATION_DIRECTORY="lang",))@app.get("/items/{id}",response_class=HTMLResponse)asyncdefread_item(request:Request,id:str):returnid+_("Hello World")Now you can control your translation language from the request header and the locale code. The parameter isAccept-Language.Screenshot:How to use Jinja In FastAPI BabelAdd jinja extension tobabel.cfg[python:**.py]
[jinja2:**/templates/**.html]
extensions=jinja2.ext.autoescape,jinja2.ext.with_Here is how yourmain.pyshould look like.main.pyfromfastapi_babelimportBabel,BabelConfigs,BabelMiddleware,_fromfastapi.responsesimportHTMLResponsefromfastapi.staticfilesimportStaticFilesfromfastapi.templatingimportJinja2TemplatesfromfastapiimportFastAPI,Requestapp=FastAPI()babel_configs=BabelConfigs(ROOT_DIR=__file__,BABEL_DEFAULT_LOCALE="en",BABEL_TRANSLATION_DIRECTORY="lang",)templates=Jinja2Templates(directory="templates")app.add_middleware(BabelMiddleware,babel_configs=babel_configs,jinja2_templates=templates)app.mount("/static",StaticFiles(directory="static"),name="static")@app.get("/items/{id}",response_class=HTMLResponse)asyncdefread_item(request:Request,id:str):returntemplates.TemplateResponse("item.html",{"request":request,"id":id})Here is sampleindex.htmlfileindex.html<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metahttp-equiv="X-UA-Compatible"content="IE=edge"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Document</title></head><body><h1>{{_("Hello World")}}</h1></body></html>Now just follow the documentation fromstep 5.More features like lazy gettext, please check theWtform ExampleAuthors@Parsa PourmhammadContributingContributions are always welcome!Please readcontributing.mdto get familiar how to get started.Please adhere to the project'scode of conduct.Feedback And SupportPlease open an issue and follow the template, so the community can help you.