Localization
Before running the examples, replace <APPBASE_ENDPOINT_WITH_V1> with the intended environment API endpoint and verify that the project and credentials belong to that environment.
Overview and use cases
Locale The service provides two categories of capabilities: identification of the current requester's geographic and language environment (returns country code, continent, EU membership status, and default currency based on the client IP and the X-Appwrite-Locale header), and the platform's built-in standardized internationalization static dictionary catalog (countries and regions, EU member states, international dialing codes, continents, ISO 4217 currencies, ISO 639-1 languages, and ISO 3166-1 three-letter codes).
In multinational or multilingual enterprise intelligent applications (such as the demo project enterprise-ai-hub-210), the frontend and server can use the Locale service to uniformly render country/dialing-code dropdowns, format currency symbols, switch languages, and inject the user's region and language preferences before agent session initialization, avoiding duplicate maintenance of static dictionaries across multiple clients.
Prerequisites
Client initialization and authentication:
Server SDK (Node.js / Java / Python / Go): initialize via
setEndpoint('https://appbuild-sit.oceanbase.com/v1'),setProject('enterprise-ai-hub-210'),setKey('<APPBASE_API_KEY>'); the API Key must have thelocale.readscope.Client / Web SDK: initialize with
setEndpointandsetProjectand load the user Session (or anonymous session); no API Key required.Console SDK: supports invocation with a Console Session or short-lived JWT.
Display language coverage: calling
client.setLocale('zh-CN')(oren-US,ja-JP) with theX-Appwrite-Localeheader in the request localizes the returned country and continent names into the specified language.
Usage workflow
Initialize the
ClientandLocaleservices: load the project ID and authentication credentials, and optionally callsetLocale('zh-CN')to specify the display language of the returned dictionaries.Get the current caller's Locale (
locale.get()): read theip,countryCode,country,continentCode,continent,eu, andcurrencyresolved from the caller's IP.Fetch the static dictionary catalog: call
listCountries(),listCountriesEU(),listCountriesPhones(),listContinents(),listCurrencies(),listLanguages(), orlistCodes()according to business form requirements, and cache by version with a TTL in the server process or frontend local storage.
Key parameters and returns
Complete Method List and Corresponding REST Endpoints
| SDK Method (Node / Web / Java) | Python Method | Go Method | REST Endpoint | Return Model | Description |
|---|---|---|---|---|---|
get() | get() | Get() | GET /v1/locale | Locale | Returns the current user's geographic and currency information based on the request source IP and the X-Appwrite-Locale header. |
listCodes() | list_codes() | ListCodes() | GET /v1/locale/codes | LocaleCodeList | Retrieves the list of ISO 639-1 language codes (total + localeCodes[]). |
listContinents() | list_continents() | ListContinents() | GET /v1/locale/continents | ContinentList | Retrieves the names and two-letter codes of the world's seven continents (total + continents[]). |
listCountries() | list_countries() | ListCountries() | GET /v1/locale/countries | CountryList | Retrieves the list of global country/region names and ISO 3166-1 Alpha-2 codes (total + countries[]). |
listCountriesEU() | list_countries_eu() | ListCountriesEU() | GET /v1/locale/countries/eu | CountryList | Retrieves the list of European Union (EU) member states (total + countries[]). |
listCountriesPhones() | list_countries_phones() | ListCountriesPhones() | GET /v1/locale/countries/phones | PhoneList | Retrieves the list of international dialing prefixes for each country (total + phones[]). |
listCurrencies() | list_currencies() | ListCurrencies() | GET /v1/locale/currencies | CurrencyList | Retrieves the list of ISO 4217 currency symbols, names, decimal precision, and codes (total + currencies[]). |
listLanguages() | list_languages() | ListLanguages() | GET /v1/locale/languages | LanguageList | Retrieves the language codes, English names, and native language names (nativeName) list (total + languages[]). |
Description of Core Return Fields
| Model | Field | Type | Description |
|---|---|---|---|
Locale | ip | string | The requesting client's IP address (if behind a reverse proxy, taken from a trusted forwarding header). |
Locale | countryCode | string | ISO 3166-1 two-letter country code (e.g., CN, US; set to -- when an internal-network IP cannot be resolved). |
Locale | country | string | The localized country name (e.g., 中国). |
Locale | continentCode | string | Two-letter continent code (e.g., AS, EU, NA). |
Locale | continent | string | The localized continent name (e.g., 亚洲). |
Locale | eu | boolean | Whether the country is an EU member state. |
Locale | currency | string | ISO 4217 three-letter currency code (e.g., CNY, USD, EUR). |
Country / Continent | name / code | string | Localized name and two-letter standard code. |
Phone | code / countryCode / countryName | string | Dialing code (e.g., +86), country code (CN), and country name. |
Currency | symbol / name / symbolNative / decimalDigits / rounding / code / namePlural | string / number | Currency display symbol (¥), name, number of decimal places (e.g., 2), and three-letter code (CNY). |
Language | name / code / nativeName | string | Language name, ISO 639-1 code (e.g., zh), and native self-designation (中文). |
Errors and boundaries
Fallback value of
locale.get()in internal-network or proxy environments: whenlocale.get()is called inside a local container, a private network environment, or behind a reverse proxy that does not pass through the real client IP, the GeoIP library cannot match a public network segment, so fields such ascountryCodeandcontinentCodereturn the unknown marker--(the HTTP status code remains200); business code must treat this as an unrecognized region and fall back to the project's default locale.Missing permissions or Scope (
401 general_unauthorized_scope): calling with a project API Key without thelocale.readscope checked returns401; when using the Web SDK, an invalid project ID returns404 project_not_found.Static dictionary caching strategy: endpoints such as
listCountriesandlistCurrencieshave no pagination parameters and return the full static collection in a single call (typically a few kilobytes). In production, fetch once at application startup or frontend Store initialization and cache it (a TTL of 24 hours is recommended), avoiding repeated fetches on every high-frequency request that would trigger429rate limiting.
SDK Category Differences
| SDK category | Coverage | Authentication method | Typical scenarios |
|---|---|---|---|
| Server SDK (Node.js / Java / Python / Go) | All 8 methods | Project API Key (locale.read) | Server-side dictionary preheating in multiple languages, billing currency precision validation, phone dialing-code region validation |
| Client / Web SDK (Web) | All 8 methods | User Session (or public access) | Registration-page international dialing-code selection, frontend language switcher, client-side automatic region detection |
| Console SDK (Node.js / Java / Python / Go) | All 8 methods | Console Session / short-lived JWT | Console forms and region selection components |
Examples by language
Available on both client and server sides; the Web tab uses the user Session and is subject to data plane permissions.
- Node.js (Server)
- Web (user session)
- Java
- Python
- Go
- REST (curl)
import { Client, Locale, AgentbaseException } from 'agentbase-node-sdk';
const client = new Client()
.setEndpoint(process.env.APPBASE_ENDPOINT ?? '<APPBASE_ENDPOINT_WITH_V1>')
.setProject(process.env.APPBASE_PROJECT_ID ?? '<APPBASE_PROJECT_ID>')
.setKey(process.env.APPBASE_API_KEY!)
.setLocale('zh-CN'); // Specify that returned country and continent names use Simplified Chinese
{
const prepareRequest = client.prepareRequest.bind(client);
client.prepareRequest = (...args) => {
const request = prepareRequest(...args);
request.options.redirect = 'error';
return request;
};
}
const locale = new Locale(client);
try {
// 1. Get the current requester's region and currency information
const current = await locale.get();
console.log(`当前区域: ${current.country} (${current.countryCode}), 货币: ${current.currency}`);
// 2. Get the country list, international dialing codes, and currency dictionary
const countries = await locale.listCountries();
const phones = await locale.listCountriesPhones();
const currencies = await locale.listCurrencies();
const languages = await locale.listLanguages();
console.log(`国家数: ${countries.total}, 区号数: ${phones.total}, 货币数: ${currencies.total}, 语言数: ${languages.total}`);
} catch (err) {
if (err instanceof AgentbaseException) {
console.error(`Locale 调用失败 [${err.code} ${err.type}]: ${err.message}`);
}
throw err;
}import { Client, Locale } from 'agentbase-web-sdk';
const client = new Client()
.setEndpoint('<APPBASE_ENDPOINT_WITH_V1>')
.setProject('<APPBASE_PROJECT_ID>')
.setLocale('zh-CN');
const locale = new Locale(client);
const userLocale = await locale.get();
const countries = await locale.listCountries();
const phones = await locale.listCountriesPhones();
console.log('识别用户国家:', userLocale.countryCode, '可选区号数:', phones.total);import io.agentbase.Client;
import io.agentbase.services.Locale;
import io.agentbase.exceptions.AppBaseException;
Client client = new Client()
.setEndpoint("<APPBASE_ENDPOINT_WITH_V1>")
.setProject("<APPBASE_PROJECT_ID>")
.setKey(System.getenv("APPBASE_API_KEY"))
.setLocale("zh-CN");
client.setHttpClient(new okhttp3.OkHttpClient.Builder()
.followRedirects(false).followSslRedirects(false).build());
Locale locale = new Locale(client);
try {
var current = locale.get(); // Current user's Locale
var countries = locale.listCountries(); // Static lists: listContinents / listCountriesEU / listCountriesPhones / listCurrencies / listLanguages / listCodes
var currencies = locale.listCurrencies();
System.out.println("Country=" + current.getCountry() + ", totalCountries=" + countries.getTotal() + ", totalCurrencies=" + currencies.getTotal());
} catch (AppBaseException e) {
System.err.println("HTTP " + e.getCode() + " type=" + e.getType() + ": " + e.getMessage());
}The Python Server SDK 2.12.0 default transport may forward the project API key on redirects. Use the REST tab in this section.
package main
import (
"errors"
"net/http"
"fmt"
"os"
"agentbase-go-sdk/agentbase"
)
func main() {
cl := agentbase.NewClient(
agentbase.WithEndpoint("<APPBASE_ENDPOINT_WITH_V1>"),
agentbase.WithProject("<APPBASE_PROJECT_ID>"),
agentbase.WithKey(os.Getenv("APPBASE_API_KEY")),
agentbase.WithLocale("zh-CN"),
)
cl.Client.CheckRedirect = func(_ *http.Request, _ []*http.Request) error {
return errors.New("refuse redirects")
}
locale := agentbase.NewLocale(cl)
loc, err := locale.Get()
if err == nil {
fmt.Println("当前国家:", loc.Country, loc.Currency)
}
countries, _ := locale.ListCountries() // Also available: ListContinents / ListCountriesEU / ListCountriesPhones / ListCurrencies / ListLanguages / ListCodes
fmt.Println("国家总数:", countries.Total)
}(
set +x
set -e -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
# 1. Get the current requester's Locale (with X-Appwrite-Locale: zh-CN, Chinese country and continent names are returned)
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --header @- -fsS "$APPBASE_ENDPOINT/locale" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Locale: zh-CN"
# 2. Get the static lists of countries, international dialing codes, currencies, and languages
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --header @- -fsS "$APPBASE_ENDPOINT/locale/countries" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Locale: zh-CN"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --header @- -fsS "$APPBASE_ENDPOINT/locale/countries/phones" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --header @- -fsS "$APPBASE_ENDPOINT/locale/currencies" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID"
)Example Guide
JavaScript / TypeScript full example: ../examples/javascript.md
Python full example: ../examples/python.md
Java full example: ../examples/java.md
Go full example: ../examples/go.md