Skip to main content

Adding Internationalization (i18n) in FastAPI

🌍 Adding Internationalization (i18n) in FastAPI

If you're building a multi-lingual API with FastAPI, it's essential to support internationalization. In this guide, we'll use the python-i18n library — a simple and effective tool for managing translations in Python using JSON files.

📦 Step 1: Install python-i18n

pip install python-i18n

📁 Step 2: Create Locale Files

Create a locales directory and add your language JSON files:

locales/
├── en.json
└── fr.json

en.json:

{
  "greeting": "Hello"
}

fr.json:

{
  "greeting": "Bonjour"
}

⚙️ Step 3: Configure i18n in FastAPI

import i18n
from fastapi import FastAPI, Request

app = FastAPI()

# Load translation files
i18n.load_path.append('locales')
i18n.set('fallback', 'en')

🌐 Step 4: Detect Language from Request

@app.middleware("http")
async def add_language_to_request(request: Request, call_next):
    lang = request.headers.get("Accept-Language", "en").split(",")[0]
    i18n.set("locale", lang)
    response = await call_next(request)
    return response

📨 Step 5: Use Translations in Your API

from fastapi.responses import JSONResponse

@app.get("/greet")
async def greet():
    message = i18n.t("greeting")
    return JSONResponse(content={"message": message})

🔗 Resources

🎉 Conclusion

With just a few steps, you've added internationalization support to your FastAPI application! Using python-i18n, you can easily expand your app to support more languages and provide localized content.

Comments

  1. Adding internationalization at the API level is a practical requirement when an application needs to serve users across different languages. The tutorial keeps the implementation straightforward by using JSON locale files, a fallback language, and FastAPI middleware to read the Accept-Language header and set the appropriate locale for each request.

    The combination of Python backend development and API functionality makes Python Full Stack Course particularly relevant here. The example shows how a Python-based application can incorporate a cross-cutting feature such as localization without changing the basic API structure.

    ReplyDelete
  2. Using FastAPI directly for the multilingual API also makes FastAPI Course a strong connection. The middleware approach demonstrates how request information can be processed before reaching an endpoint, while the translation files keep the language-specific content separate from the application logic.

    ReplyDelete
  3. The use of request headers and API responses further connects the example with RESTful API Training. Reading Accept-Language from each request is a simple but effective way to let clients indicate their preferred language while keeping the API interface consistent.

    ReplyDelete

Post a Comment

Popular posts from this blog

Rethinking Writing Assistants: A Fresh Opportunity in macOS Productivity

In a world full of grammar checkers, writing enhancers, and AI-powered editors, one question remains surprisingly unanswered: why hasn’t anyone built a truly seamless, intelligent writing assistant for macOS that combines next-word prediction with real-time rewriting? The Current Landscape Today’s macOS users have several writing tools to choose from: Compose for macOS: Offers shortcut-activated rewriting, grammar correction, and text shortening in any app. However, it doesn’t predict your next word or sentence. Apple Writing Tools (macOS Sequoia): System-level rewriting, tone adjustment, and proofreading. Great polish, but still reactive rather than proactive. Fixkey: Adds voice-to-text and real-time rewriting with support for multiple languages. GrammarPaw: Lightweight and powerful, with ChatGPT integration, but requires manual activation for each rewrite. Cotypist: Possibly the closest to predictive text—offers GitHub Copilot-style autocomplete across macOS apps, but lacks grammar...

Show Your Work! — Coin-Size Summary

Theme: You don’t need to be a genius — just be generous and share your process. Core Message: “People can’t find you if you don’t let them see you.” Key Ideas: Share your process, not just the polished product. Be an amateur — open, curious, and always learning. Teach what you know , and build trust by showing up consistently. Don’t wait to be “ready” — sharing builds confidence and community. 10 Short Rules (Examples): You don’t have to be a genius. Think process, not product. Share something small every day. Stick around. Core Lesson: “Being good at something is no substitute for showing up and sharing it.”