本文檔介紹瞭如何以編程方式讀取和修改一組 JSON 格式的參數和條件,稱為遠程配置模板。這允許您在客戶端應用程序可以使用客戶端庫獲取的後端進行模板更改。
使用本指南中描述的Remote Config REST API或Admin SDK ,您可以繞過在 Firebase 控制台中管理模板,直接將 Remote Config 更改集成到您自己的流程中。例如,使用 Remote Config 後端 API,您可以:
- 安排遠程配置更新。通過將 API 調用與 cron 作業結合使用,您可以定期更改遠程配置值。
- 批量導入配置值,以便從您自己的專有系統高效地過渡到 Firebase 遠程配置。
將 Remote Config 與 Cloud Functions for Firebase 結合使用,根據服務器端發生的事件更改應用程序中的值。例如,您可以使用 Remote Config 來推廣應用中的新功能,然後在檢測到足夠多的人與新功能進行交互後自動關閉該推廣。
本指南的以下部分描述了您可以使用遠程配置後端 API 執行的操作。要查看通過 REST API 執行這些任務的一些代碼,請參閱以下示例應用程序之一:
- Firebase 遠程配置 REST API Java 快速入門
- Firebase 遠程配置 REST API Node.js 快速入門
- Firebase 遠程配置 REST API Python 快速入門
使用 Firebase Admin SDK 修改遠程配置
Admin SDK 是一組服務器庫,可讓您從特權環境與 Firebase 進行交互。除了對遠程配置執行更新外,Admin SDK 還支持生成和驗證 Firebase 身份驗證令牌、從實時數據庫讀取和寫入等。要了解有關 Admin SDK 先決條件和設置的更多信息,請參閱將 Firebase Admin SDK 添加到您的服務器。
在典型的遠程配置流程中,您可能會獲取當前模板,修改一些參數或參數組和條件,驗證模板,然後發布它。在進行這些 API 調用之前,您必須授權來自 SDK 的請求。
初始化SDK並授權API請求
當您在沒有參數的情況下初始化 Admin SDK 時,SDK 會使用Google 應用程序默認憑據並從FIREBASE_CONFIG
環境變量中讀取選項。如果FIREBASE_CONFIG
變量的內容以{
開頭,它將被解析為 JSON 對象。否則,SDK 假定該字符串是包含選項的 JSON 文件的名稱。
例如:
節點.js
const admin = require('firebase-admin'); admin.initializeApp();
爪哇
FileInputStream serviceAccount = new FileInputStream("service-account.json"); FirebaseOptions options = FirebaseOptions.builder() .setCredentials(GoogleCredentials.fromStream(serviceAccount)) .build(); FirebaseApp.initializeApp(options);
獲取當前的遠程配置模板
使用 Remote Config 模板時,請記住它們是版本化的,並且每個版本從創建時間到您用更新替換它的時間都有有限的生命週期:90 天,總共存儲 300 個版本。有關詳細信息,請參閱模板和版本控制。
您可以使用後端 API 以 JSON 格式獲取遠程配置模板的當前活動版本。
在 A/B 測試實驗中專門作為變體創建的參數和參數值不包含在導出的模板中。
獲取模板:
節點.js
function getTemplate() { var config = admin.remoteConfig(); config.getTemplate() .then(function (template) { console.log('ETag from server: ' + template.etag); var templateStr = JSON.stringify(template); fs.writeFileSync('config.json', templateStr); }) .catch(function (err) { console.error('Unable to get template'); console.error(err); }); }
爪哇
Template template = FirebaseRemoteConfig.getInstance().getTemplateAsync().get(); // See the ETag of the fetched template. System.out.println("ETag from server: " + template.getETag());
修改遠程配置參數
您可以通過編程方式修改和添加遠程配置參數和參數組。例如,對於名為“new_menu”的現有參數組,您可以添加一個參數來控制季節性信息的顯示:
節點.js
function addParameterToGroup(template) { template.parameterGroups['new_menu'].parameters['spring_season'] = { defaultValue: { useInAppDefault: true }, description: 'spring season menu visibility.', }; }
爪哇
template.getParameterGroups().get("new_menu").getParameters() .put("spring_season", new Parameter() .setDefaultValue(ParameterValue.inAppDefault()) .setDescription("spring season menu visibility.") );
API 允許您創建新的參數和參數組,或修改默認值、條件值和描述。在所有情況下,您必須在修改後顯式發布模板。
修改遠程配置條件
您可以通過編程方式修改和添加遠程配置條件和條件值。例如,要添加一個新條件:
節點.js
function addNewCondition(template) { template.conditions.push({ name: 'android_en', expression: 'device.os == \'android\' && device.country in [\'us\', \'uk\']', tagColor: 'BLUE', }); }
爪哇
template.getConditions().add(new Condition("android_en", "device.os == 'android' && device.country in ['us', 'uk']", TagColor.BLUE));
在所有情況下,您必須在修改後顯式發布模板。
Remote Config 後端 API 提供了多個條件和比較運算符,您可以使用它們來更改應用的行為和外觀。要了解有關條件和這些條件支持的運算符的更多信息,請參閱條件表達式參考。
驗證遠程配置模板
或者,您可以在發布更新之前驗證您的更新,如下所示:
節點.js
function validateTemplate(template) { admin.remoteConfig().validateTemplate(template) .then(function (validatedTemplate) { // The template is valid and safe to use. console.log('Template was valid and safe to use'); }) .catch(function (err) { console.error('Template is invalid and cannot be published'); console.error(err); }); }
爪哇
try { Template validatedTemplate = FirebaseRemoteConfig.getInstance() .validateTemplateAsync(template).get(); System.out.println("Template was valid and safe to use"); } catch (ExecutionException e) { if (e.getCause() instanceof FirebaseRemoteConfigException) { FirebaseRemoteConfigException rcError = (FirebaseRemoteConfigException) e.getCause(); System.out.println("Template is invalid and cannot be published"); System.out.println(rcError.getMessage()); } }
此驗證過程會檢查錯誤,例如參數和條件的重複鍵、無效的條件名稱或不存在的條件,或錯誤格式的 etag。例如,包含超過允許數量的鍵(2000)的請求將返回錯誤消息, Param count too large
。
發布遠程配置模板
檢索到模板並使用所需的更新對其進行修改後,您就可以發布它了。如本節所述發布模板會用更新的文件替換整個現有的配置模板,並且為新的活動模板分配一個比它替換的模板大一個的版本號。
如有必要,您可以使用 REST API回滾到之前的版本。為降低更新出錯的風險,您可以在發布前進行驗證。
遠程配置個性化和條件包含在下載的模板中,因此在嘗試發佈到不同項目時了解以下限制很重要:
無法將個性化從一個項目導入到另一個項目。
例如,如果您在項目中啟用了個性化並下載和編輯模板,則可以將其發佈到同一項目,但不能將其發佈到不同的項目,除非您從模板中刪除個性化。
條件可以從一個項目導入到另一個項目,但請注意,任何特定的條件值(如應用程序 ID 或受眾)在發布之前都應該存在於目標項目中。
例如,如果您有一個 Remote Config 參數使用指定平台值
iOS
的條件,則模板可以發佈到另一個項目,因為平台值對於任何項目都是相同的。但是,如果它包含依賴於目標項目中不存在的特定應用程序 ID 或用戶受眾的條件,則驗證將失敗。如果您計劃發布的模板包含依賴 Google Analytics 的條件,則必須在目標項目中啟用 Analytics。
節點.js
function publishTemplate() { var config = admin.remoteConfig(); var template = config.createTemplateFromJSON( fs.readFileSync('config.json', 'UTF8')); config.publishTemplate(template) .then(function (updatedTemplate) { console.log('Template has been published'); console.log('ETag from server: ' + updatedTemplate.etag); }) .catch(function (err) { console.error('Unable to publish template.'); console.error(err); }); }
爪哇
try { Template publishedTemplate = FirebaseRemoteConfig.getInstance() .publishTemplateAsync(template).get(); System.out.println("Template has been published"); // See the ETag of the published template. System.out.println("ETag from server: " + publishedTemplate.getETag()); } catch (ExecutionException e) { if (e.getCause() instanceof FirebaseRemoteConfigException) { FirebaseRemoteConfigException rcError = (FirebaseRemoteConfigException) e.getCause(); System.out.println("Unable to publish template."); System.out.println(rcError.getMessage()); } }
使用 REST API 修改遠程配置
本部分介紹遠程配置 REST API 的主要功能,網址為https://firebaseremoteconfig.googleapis.com
。有關完整詳細信息,請參閱API 參考。
獲取訪問令牌以驗證和授權 API 請求
Firebase 項目支持 Google服務帳戶,您可以使用它從您的應用程序服務器或受信任的環境調用 Firebase 服務器 API。如果您在本地開發代碼或在本地部署應用程序,則可以使用通過此服務帳戶獲得的憑據來授權服務器請求。
要對服務帳戶進行身份驗證並授權其訪問 Firebase 服務,您必須生成一個 JSON 格式的私鑰文件。
為您的服務帳戶生成私鑰文件:
在 Firebase 控制台中,打開設置 >服務帳戶。
點擊Generate New Private Key ,然後點擊Generate Key確認。
安全地存儲包含密鑰的 JSON 文件。
通過服務帳戶授權時,您有兩種選擇來向您的應用程序提供憑據。您可以設置GOOGLE_APPLICATION_CREDENTIALS環境變量,也可以在代碼中顯式傳遞服務帳戶密鑰的路徑。第一個選項更安全,強烈推薦。
設置環境變量:
將環境變量GOOGLE_APPLICATION_CREDENTIALS設置為包含您的服務帳戶密鑰的 JSON 文件的文件路徑。此變量僅適用於您當前的 shell 會話,因此如果您打開一個新會話,請再次設置該變量。
Linux 或 macOS
export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"
視窗
使用 PowerShell:
$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"
完成上述步驟後,應用程序默認憑據 (ADC) 能夠隱式確定您的憑據,允許您在非 Google 環境中測試或運行時使用服務帳戶憑據。
將您的 Firebase 憑據與您首選語言的Google Auth 庫一起使用,以檢索短期 OAuth 2.0 訪問令牌:
節點.js
function getAccessToken() {
return admin.credential.applicationDefault().getAccessToken()
.then(accessToken => {
return accessToken.access_token;
})
.catch(err => {
console.error('Unable to get access token');
console.error(err);
});
}
在此示例中,Google API 客戶端庫使用 JSON 網絡令牌或 JWT 對請求進行身份驗證。有關詳細信息,請參閱JSON Web 令牌。
Python
def _get_access_token():
"""Retrieve a valid access token that can be used to authorize requests.
:return: Access token.
"""
credentials = ServiceAccountCredentials.from_json_keyfile_name(
'service-account.json', SCOPES)
access_token_info = credentials.get_access_token()
return access_token_info.access_token
爪哇
private static String getAccessToken() throws IOException {
GoogleCredentials googleCredentials = GoogleCredentials
.fromStream(new FileInputStream("service-account.json"))
.createScoped(Arrays.asList(SCOPES));
googleCredentials.refreshAccessToken();
return googleCredentials.getAccessToken().getTokenValue();
}
訪問令牌過期後,將自動調用令牌刷新方法以檢索更新的訪問令牌。
要授權訪問遠程配置,請請求範圍https://www.googleapis.com/auth/firebase.remoteconfig
。
修改遠程配置模板
使用 Remote Config 模板時,請記住它們是版本化的,並且每個版本從創建時間到您用更新替換它的時間都有有限的生命週期:90 天,總共存儲 300 個版本。有關詳細信息,請參閱模板和版本控制。
獲取當前的遠程配置模板
您可以使用後端 API 以 JSON 格式獲取遠程配置模板的當前活動版本。
在 A/B 測試實驗中專門作為變體創建的參數和參數值不包含在導出的模板中。
使用以下命令:
捲曲
curl --compressed -D headers -H "Authorization: Bearer token" -X GET https://firebaseremoteconfig.googleapis.com/v1/projects/my-project-id/remoteConfig -o filename
此命令將 JSON 負載輸出到一個文件,並將標頭(包括 Etag)輸出到另一個文件。
原始 HTTP 請求
Host: firebaseremoteconfig.googleapis.com GET /v1/projects/my-project-id/remoteConfig HTTP/1.1 Authorization: Bearer token Accept-Encoding: gzip
此 API 調用返回以下 JSON,以及一個單獨的標頭,其中包含您用於後續請求的ETag 。
驗證遠程配置模板
或者,您可以在發布更新之前驗證您的更新。通過將 URL 參數附加到您的發布請求來驗證模板更新?validate_only=true
。在響應中,狀態代碼 200 和後綴為-0
的更新 etag 表示您的更新已成功驗證。任何非 200 響應都表示 JSON 數據包含您必須在發布前更正的錯誤。
更新遠程配置模板
檢索到模板並使用所需的更新修改 JSON 內容後,您就可以發布它了。如本節所述發布模板會用更新的文件替換整個現有的配置模板,並且為新的活動模板分配一個比它替換的模板大一個的版本號。
如有必要,您可以使用 REST API回滾到之前的版本。為降低更新出錯的風險,您可以在發布前進行驗證。
遠程配置個性化和條件包含在下載的模板中,因此在嘗試發佈到不同項目時了解以下限制很重要:
無法將個性化從一個項目導入到另一個項目。
例如,如果您在項目中啟用了個性化並下載和編輯模板,則可以將其發佈到同一項目,但不能將其發佈到不同的項目,除非您從模板中刪除個性化。
條件可以從一個項目導入到另一個項目,但請注意,任何特定的條件值(如應用程序 ID 或受眾)在發布之前都應該存在於目標項目中。
例如,如果您有一個 Remote Config 參數使用指定平台值
iOS
的條件,則模板可以發佈到另一個項目,因為平台值對於任何項目都是相同的。但是,如果它包含依賴於目標項目中不存在的特定應用程序 ID 或用戶受眾的條件,則驗證將失敗。如果您計劃發布的模板包含依賴 Google Analytics 的條件,則必須在目標項目中啟用 Analytics。
捲曲
curl --compressed -H "Content-Type: application/json; UTF8" -H "If-Match: last-returned-etag" -H "Authorization: Bearer token" -X PUT https://firebaseremoteconfig.googleapis.com/v1/projects/my-project-id/remoteConfig -d @filename
對於此curl
命令,您可以使用“@”字符指定內容,後跟文件名。
原始 HTTP 請求
Host: firebaseremoteconfig.googleapis.com PUT /v1/projects/my-project-id/remoteConfig HTTP/1.1 Content-Length: size Content-Type: application/json; UTF8 Authorization: Bearer token If-Match: expected ETag Accept-Encoding: gzip JSON_HERE
因為這是一個寫請求,所以ETag被這個命令修改,並且在下一個PUT
命令的響應頭中提供更新的 ETag。
修改遠程配置條件
您可以通過編程方式修改遠程配置條件和條件值。使用 REST API,您必須在發布模板之前直接編輯模板以修改條件。
{ "conditions": [{ "name": "android_english", "expression": "device.os == 'android' && device.country in ['us', 'uk']", "tagColor": "BLUE" }, { "name": "tenPercent", "expression": "percent <= 10", "tagColor": "BROWN" }], "parameters": { "welcome_message": { "defaultValue": { "value": "Welcome to this sample app" }, "conditionalValues": { "tenPercent": { "value": "Welcome to this new sample app" } }, "description": "The sample app's welcome message" }, "welcome_message_caps": { "defaultValue": { "value": "false" }, "conditionalValues": { "android_english": { "value": "true" } }, "description": "Whether the welcome message should be displayed in all capital letters." } } }
上面的修改首先定義了一組條件,然後為每個參數定義了默認值和基於條件的參數( conditional values )值。它還為每個元素添加了一個可選的描述;與代碼註釋一樣,這些供開發人員使用,不會顯示在應用程序中。還提供了一個ETag用於版本控制目的。
Remote Config 後端 API 提供了多個條件和比較運算符,您可以使用它們來更改應用的行為和外觀。要了解有關條件和這些條件支持的運算符的更多信息,請參閱條件表達式參考。
HTTP 錯誤代碼
狀態碼 | 意義 |
---|---|
200 | 成功更新 |
400 | 發生驗證錯誤。例如,包含超過允許的鍵數(2000)的請求將返回 400(錯誤請求)和錯誤消息Param count too large 。此外,此 HTTPS 狀態代碼可能會在以下兩種情況下發生:
|
401 | 發生授權錯誤(未提供訪問令牌或 Firebase Remote Config REST API 尚未添加到您在 Cloud Developer Console 中的項目) |
403 | 發生身份驗證錯誤(提供了錯誤的訪問令牌) |
500 | 發生了內部錯誤。如果發生此錯誤,請提交 Firebase 支持票 |
狀態代碼 200 表示遠程配置模板(項目的參數、值和條件)已更新,現在可供使用該項目的應用使用。其他狀態碼表示之前存在的 Remote Config 模板仍然有效。
提交模板更新後,轉到 Firebase 控制台以驗證您的更改是否按預期顯示。這一點很關鍵,因為條件的順序會影響它們的評估方式(評估true
第一個條件生效)。
ETag 使用和強制更新
Remote Config REST API 使用實體標籤 (ETag) 來防止競爭條件和資源的重疊更新。要了解有關 ETag 的更多信息,請參閱ETag - HTTP 。
對於 REST API,Google 建議您緩存最近GET
命令提供的 ETag,並在發出PUT
命令時在If-Match
請求標頭中使用該 ETag 值。如果您的PUT
命令導致 HTTPS 狀態代碼 409,您應該發出新的GET
命令以獲取新的 ETag 和模板以用於您的下一個PUT
命令。
您可以通過強制更新遠程配置模板來規避 ETag 及其提供的保護, If-Match: *
如果多個客戶端正在更新遠程配置模板,則為模板。這種衝突可能發生在多個客戶端使用 API 時,或者 API 客戶端和 Firebase 控制台用戶的更新衝突時。
有關管理遠程配置模板版本的指南,請參閱遠程配置模板和版本控制。
,本文檔介紹瞭如何以編程方式讀取和修改一組 JSON 格式的參數和條件,稱為遠程配置模板。這允許您在客戶端應用程序可以使用客戶端庫獲取的後端進行模板更改。
使用本指南中描述的Remote Config REST API或Admin SDK ,您可以繞過在 Firebase 控制台中管理模板,直接將 Remote Config 更改集成到您自己的流程中。例如,使用 Remote Config 後端 API,您可以:
- 安排遠程配置更新。通過將 API 調用與 cron 作業結合使用,您可以定期更改遠程配置值。
- 批量導入配置值,以便從您自己的專有系統高效地過渡到 Firebase 遠程配置。
將 Remote Config 與 Cloud Functions for Firebase 結合使用,根據服務器端發生的事件更改應用程序中的值。例如,您可以使用 Remote Config 來推廣應用中的新功能,然後在檢測到足夠多的人與新功能進行交互後自動關閉該推廣。
本指南的以下部分描述了您可以使用遠程配置後端 API 執行的操作。要查看通過 REST API 執行這些任務的一些代碼,請參閱以下示例應用程序之一:
- Firebase 遠程配置 REST API Java 快速入門
- Firebase 遠程配置 REST API Node.js 快速入門
- Firebase 遠程配置 REST API Python 快速入門
使用 Firebase Admin SDK 修改遠程配置
Admin SDK 是一組服務器庫,可讓您從特權環境與 Firebase 進行交互。除了對遠程配置執行更新外,Admin SDK 還支持生成和驗證 Firebase 身份驗證令牌、從實時數據庫讀取和寫入等。要了解有關 Admin SDK 先決條件和設置的更多信息,請參閱將 Firebase Admin SDK 添加到您的服務器。
在典型的遠程配置流程中,您可能會獲取當前模板,修改一些參數或參數組和條件,驗證模板,然後發布它。在進行這些 API 調用之前,您必須授權來自 SDK 的請求。
初始化SDK並授權API請求
當您在沒有參數的情況下初始化 Admin SDK 時,SDK 會使用Google 應用程序默認憑據並從FIREBASE_CONFIG
環境變量中讀取選項。如果FIREBASE_CONFIG
變量的內容以{
開頭,它將被解析為 JSON 對象。否則,SDK 假定該字符串是包含選項的 JSON 文件的名稱。
例如:
節點.js
const admin = require('firebase-admin'); admin.initializeApp();
爪哇
FileInputStream serviceAccount = new FileInputStream("service-account.json"); FirebaseOptions options = FirebaseOptions.builder() .setCredentials(GoogleCredentials.fromStream(serviceAccount)) .build(); FirebaseApp.initializeApp(options);
獲取當前的遠程配置模板
使用 Remote Config 模板時,請記住它們是版本化的,並且每個版本從創建時間到您用更新替換它的時間都有有限的生命週期:90 天,總共存儲 300 個版本。有關詳細信息,請參閱模板和版本控制。
您可以使用後端 API 以 JSON 格式獲取遠程配置模板的當前活動版本。
在 A/B 測試實驗中專門作為變體創建的參數和參數值不包含在導出的模板中。
獲取模板:
節點.js
function getTemplate() { var config = admin.remoteConfig(); config.getTemplate() .then(function (template) { console.log('ETag from server: ' + template.etag); var templateStr = JSON.stringify(template); fs.writeFileSync('config.json', templateStr); }) .catch(function (err) { console.error('Unable to get template'); console.error(err); }); }
爪哇
Template template = FirebaseRemoteConfig.getInstance().getTemplateAsync().get(); // See the ETag of the fetched template. System.out.println("ETag from server: " + template.getETag());
修改遠程配置參數
您可以通過編程方式修改和添加遠程配置參數和參數組。例如,對於名為“new_menu”的現有參數組,您可以添加一個參數來控制季節性信息的顯示:
節點.js
function addParameterToGroup(template) { template.parameterGroups['new_menu'].parameters['spring_season'] = { defaultValue: { useInAppDefault: true }, description: 'spring season menu visibility.', }; }
爪哇
template.getParameterGroups().get("new_menu").getParameters() .put("spring_season", new Parameter() .setDefaultValue(ParameterValue.inAppDefault()) .setDescription("spring season menu visibility.") );
API 允許您創建新的參數和參數組,或修改默認值、條件值和描述。在所有情況下,您必須在修改後顯式發布模板。
修改遠程配置條件
您可以通過編程方式修改和添加遠程配置條件和條件值。例如,要添加一個新條件:
節點.js
function addNewCondition(template) { template.conditions.push({ name: 'android_en', expression: 'device.os == \'android\' && device.country in [\'us\', \'uk\']', tagColor: 'BLUE', }); }
爪哇
template.getConditions().add(new Condition("android_en", "device.os == 'android' && device.country in ['us', 'uk']", TagColor.BLUE));
在所有情況下,您必須在修改後顯式發布模板。
Remote Config 後端 API 提供了多個條件和比較運算符,您可以使用它們來更改應用的行為和外觀。要了解有關條件和這些條件支持的運算符的更多信息,請參閱條件表達式參考。
驗證遠程配置模板
或者,您可以在發布更新之前驗證您的更新,如下所示:
節點.js
function validateTemplate(template) { admin.remoteConfig().validateTemplate(template) .then(function (validatedTemplate) { // The template is valid and safe to use. console.log('Template was valid and safe to use'); }) .catch(function (err) { console.error('Template is invalid and cannot be published'); console.error(err); }); }
爪哇
try { Template validatedTemplate = FirebaseRemoteConfig.getInstance() .validateTemplateAsync(template).get(); System.out.println("Template was valid and safe to use"); } catch (ExecutionException e) { if (e.getCause() instanceof FirebaseRemoteConfigException) { FirebaseRemoteConfigException rcError = (FirebaseRemoteConfigException) e.getCause(); System.out.println("Template is invalid and cannot be published"); System.out.println(rcError.getMessage()); } }
此驗證過程會檢查錯誤,例如參數和條件的重複鍵、無效的條件名稱或不存在的條件,或錯誤格式的 etag。例如,包含超過允許數量的鍵(2000)的請求將返回錯誤消息, Param count too large
。
發布遠程配置模板
檢索到模板並使用所需的更新對其進行修改後,您就可以發布它了。如本節所述發布模板會用更新的文件替換整個現有的配置模板,並且為新的活動模板分配一個比它替換的模板大一個的版本號。
如有必要,您可以使用 REST API回滾到之前的版本。為降低更新出錯的風險,您可以在發布前進行驗證。
遠程配置個性化和條件包含在下載的模板中,因此在嘗試發佈到不同項目時了解以下限制很重要:
無法將個性化從一個項目導入到另一個項目。
例如,如果您在項目中啟用了個性化並下載和編輯模板,則可以將其發佈到同一項目,但不能將其發佈到不同的項目,除非您從模板中刪除個性化。
條件可以從一個項目導入到另一個項目,但請注意,任何特定的條件值(如應用程序 ID 或受眾)在發布之前都應該存在於目標項目中。
例如,如果您有一個 Remote Config 參數使用指定平台值
iOS
的條件,則模板可以發佈到另一個項目,因為平台值對於任何項目都是相同的。但是,如果它包含依賴於目標項目中不存在的特定應用程序 ID 或用戶受眾的條件,則驗證將失敗。如果您計劃發布的模板包含依賴 Google Analytics 的條件,則必須在目標項目中啟用 Analytics。
節點.js
function publishTemplate() { var config = admin.remoteConfig(); var template = config.createTemplateFromJSON( fs.readFileSync('config.json', 'UTF8')); config.publishTemplate(template) .then(function (updatedTemplate) { console.log('Template has been published'); console.log('ETag from server: ' + updatedTemplate.etag); }) .catch(function (err) { console.error('Unable to publish template.'); console.error(err); }); }
爪哇
try { Template publishedTemplate = FirebaseRemoteConfig.getInstance() .publishTemplateAsync(template).get(); System.out.println("Template has been published"); // See the ETag of the published template. System.out.println("ETag from server: " + publishedTemplate.getETag()); } catch (ExecutionException e) { if (e.getCause() instanceof FirebaseRemoteConfigException) { FirebaseRemoteConfigException rcError = (FirebaseRemoteConfigException) e.getCause(); System.out.println("Unable to publish template."); System.out.println(rcError.getMessage()); } }
使用 REST API 修改遠程配置
本部分介紹遠程配置 REST API 的主要功能,網址為https://firebaseremoteconfig.googleapis.com
。有關完整詳細信息,請參閱API 參考。
獲取訪問令牌以驗證和授權 API 請求
Firebase 項目支持 Google服務帳戶,您可以使用它從您的應用程序服務器或受信任的環境調用 Firebase 服務器 API。如果您在本地開發代碼或在本地部署應用程序,則可以使用通過此服務帳戶獲得的憑據來授權服務器請求。
要對服務帳戶進行身份驗證並授權其訪問 Firebase 服務,您必須生成一個 JSON 格式的私鑰文件。
為您的服務帳戶生成私鑰文件:
在 Firebase 控制台中,打開設置 >服務帳戶。
點擊Generate New Private Key ,然後點擊Generate Key確認。
安全地存儲包含密鑰的 JSON 文件。
通過服務帳戶授權時,您有兩種選擇來向您的應用程序提供憑據。您可以設置GOOGLE_APPLICATION_CREDENTIALS環境變量,也可以在代碼中顯式傳遞服務帳戶密鑰的路徑。第一個選項更安全,強烈推薦。
設置環境變量:
將環境變量GOOGLE_APPLICATION_CREDENTIALS設置為包含您的服務帳戶密鑰的 JSON 文件的文件路徑。此變量僅適用於您當前的 shell 會話,因此如果您打開一個新會話,請再次設置該變量。
Linux 或 macOS
export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"
視窗
使用 PowerShell:
$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"
完成上述步驟後,應用程序默認憑據 (ADC) 能夠隱式確定您的憑據,允許您在非 Google 環境中測試或運行時使用服務帳戶憑據。
將您的 Firebase 憑據與您首選語言的Google Auth 庫一起使用,以檢索短期 OAuth 2.0 訪問令牌:
節點.js
function getAccessToken() {
return admin.credential.applicationDefault().getAccessToken()
.then(accessToken => {
return accessToken.access_token;
})
.catch(err => {
console.error('Unable to get access token');
console.error(err);
});
}
在此示例中,Google API 客戶端庫使用 JSON 網絡令牌或 JWT 對請求進行身份驗證。有關詳細信息,請參閱JSON Web 令牌。
Python
def _get_access_token():
"""Retrieve a valid access token that can be used to authorize requests.
:return: Access token.
"""
credentials = ServiceAccountCredentials.from_json_keyfile_name(
'service-account.json', SCOPES)
access_token_info = credentials.get_access_token()
return access_token_info.access_token
爪哇
private static String getAccessToken() throws IOException {
GoogleCredentials googleCredentials = GoogleCredentials
.fromStream(new FileInputStream("service-account.json"))
.createScoped(Arrays.asList(SCOPES));
googleCredentials.refreshAccessToken();
return googleCredentials.getAccessToken().getTokenValue();
}
訪問令牌過期後,將自動調用令牌刷新方法以檢索更新的訪問令牌。
要授權訪問遠程配置,請請求範圍https://www.googleapis.com/auth/firebase.remoteconfig
。
修改遠程配置模板
使用 Remote Config 模板時,請記住它們是版本化的,並且每個版本從創建時間到您用更新替換它的時間都有有限的生命週期:90 天,總共存儲 300 個版本。有關詳細信息,請參閱模板和版本控制。
獲取當前的遠程配置模板
您可以使用後端 API 以 JSON 格式獲取遠程配置模板的當前活動版本。
在 A/B 測試實驗中專門作為變體創建的參數和參數值不包含在導出的模板中。
使用以下命令:
捲曲
curl --compressed -D headers -H "Authorization: Bearer token" -X GET https://firebaseremoteconfig.googleapis.com/v1/projects/my-project-id/remoteConfig -o filename
此命令將 JSON 負載輸出到一個文件,並將標頭(包括 Etag)輸出到另一個文件。
原始 HTTP 請求
Host: firebaseremoteconfig.googleapis.com GET /v1/projects/my-project-id/remoteConfig HTTP/1.1 Authorization: Bearer token Accept-Encoding: gzip
此 API 調用返回以下 JSON,以及一個單獨的標頭,其中包含您用於後續請求的ETag 。
驗證遠程配置模板
或者,您可以在發布更新之前驗證您的更新。通過將 URL 參數附加到您的發布請求來驗證模板更新?validate_only=true
。在響應中,狀態代碼 200 和後綴為-0
的更新 etag 表示您的更新已成功驗證。任何非 200 響應都表示 JSON 數據包含您必須在發布前更正的錯誤。
更新遠程配置模板
檢索到模板並使用所需的更新修改 JSON 內容後,您就可以發布它了。如本節所述發布模板會用更新的文件替換整個現有的配置模板,並且為新的活動模板分配一個比它替換的模板大一個的版本號。
如有必要,您可以使用 REST API回滾到之前的版本。為降低更新出錯的風險,您可以在發布前進行驗證。
遠程配置個性化和條件包含在下載的模板中,因此在嘗試發佈到不同項目時了解以下限制很重要:
無法將個性化從一個項目導入到另一個項目。
例如,如果您在項目中啟用了個性化並下載和編輯模板,則可以將其發佈到同一項目,但不能將其發佈到不同的項目,除非您從模板中刪除個性化。
條件可以從一個項目導入到另一個項目,但請注意,任何特定的條件值(如應用程序 ID 或受眾)在發布之前都應該存在於目標項目中。
例如,如果您有一個 Remote Config 參數使用指定平台值
iOS
的條件,則模板可以發佈到另一個項目,因為平台值對於任何項目都是相同的。但是,如果它包含依賴於目標項目中不存在的特定應用程序 ID 或用戶受眾的條件,則驗證將失敗。如果您計劃發布的模板包含依賴 Google Analytics 的條件,則必須在目標項目中啟用 Analytics。
捲曲
curl --compressed -H "Content-Type: application/json; UTF8" -H "If-Match: last-returned-etag" -H "Authorization: Bearer token" -X PUT https://firebaseremoteconfig.googleapis.com/v1/projects/my-project-id/remoteConfig -d @filename
對於此curl
命令,您可以使用“@”字符指定內容,後跟文件名。
原始 HTTP 請求
Host: firebaseremoteconfig.googleapis.com PUT /v1/projects/my-project-id/remoteConfig HTTP/1.1 Content-Length: size Content-Type: application/json; UTF8 Authorization: Bearer token If-Match: expected ETag Accept-Encoding: gzip JSON_HERE
因為這是一個寫請求,所以ETag被這個命令修改,並且在下一個PUT
命令的響應頭中提供更新的 ETag。
修改遠程配置條件
您可以通過編程方式修改遠程配置條件和條件值。使用 REST API,您必須在發布模板之前直接編輯模板以修改條件。
{ "conditions": [{ "name": "android_english", "expression": "device.os == 'android' && device.country in ['us', 'uk']", "tagColor": "BLUE" }, { "name": "tenPercent", "expression": "percent <= 10", "tagColor": "BROWN" }], "parameters": { "welcome_message": { "defaultValue": { "value": "Welcome to this sample app" }, "conditionalValues": { "tenPercent": { "value": "Welcome to this new sample app" } }, "description": "The sample app's welcome message" }, "welcome_message_caps": { "defaultValue": { "value": "false" }, "conditionalValues": { "android_english": { "value": "true" } }, "description": "Whether the welcome message should be displayed in all capital letters." } } }
上面的修改首先定義了一組條件,然後為每個參數定義了默認值和基於條件的參數( conditional values )值。它還為每個元素添加了一個可選的描述; like code comments, these are for developer use and are not displayed in the app. An ETag is also provided for version control purposes.
The Remote Config backend APIs provide several conditions and comparison operators that you can use to change the behavior and appearance of your app. To learn more about conditions and the operators supported for these conditions, see the conditional expression reference .
HTTP Error codes
Status Code | Meaning |
---|---|
200 | Successfully Updated |
400 | A validation error occurred. For example, a request containing more than the allowed number of keys—2000—would return 400 (Bad Request) with the error message, Param count too large . Also, this HTTPS Status Code can occur in these two situations:
|
401 | An authorization error occurred (no access token was provided or the Firebase Remote Config REST API has not been added to your project in the Cloud Developer Console) |
403 | An authentication error occurred (the wrong access token was provided) |
500 | An internal error occurred. If this error occurs, file a Firebase support ticket |
A status code of 200 means that the Remote Config template (parameters, values and conditions for the project) has been updated and is now available to apps that use this project. Other status codes indicate that the Remote Config template that existed previously is still in effect.
After you submit updates to your template, go to the Firebase console to verify that your changes appear as expected. This is critical because the ordering of conditions affects how they are evaluated (the first condition that evaluates true
takes effect).
ETag usage and forced updates
The Remote Config REST API uses an entity tag (ETag) to prevent race conditions and overlapping updates to resources. To learn more about ETags, see ETag - HTTP .
For the REST API, Google recommends that you cache the ETag provided by the most recent GET
command, and use that ETag value in the If-Match
request header when issuing PUT
commands. If your PUT
command results in an HTTPS Status Code 409, you should issue a fresh GET
command to acquire a new ETag and template to use with your next PUT
command.
You can circumvent the ETag, and the protection from that it provides, by forcing the Remote Config template to be updated as follows: If-Match: *
However, this approach is not recommended because it risks causing the loss of updates to your Remote Config template if multiple clients are updating the Remote Config template. This kind of conflict could occur with multiple clients using the API, or with conflicting updates from API clients and Firebase console users.
For guidance on managing Remote Config template versions, see Remote Config templates and versioning .
,This document describes how you can programatically read and modify the set of JSON-formatted parameters and conditions known as the Remote Config template . This allows you to make template changes on the backend that the client app can fetch using the client library.
Using the Remote Config REST API or the Admin SDKs described in this guide, you can bypass managing the template in the Firebase console to directly integrate Remote Config changes into your own processes. For example, with Remote Config backend APIs, you could:
- Scheduling Remote Config updates . By using API calls in conjunction with a cron job, you can change Remote Config values on a regular schedule.
- Batch import config values in order to transition efficiently from your own proprietary system to Firebase Remote Config.
Use Remote Config with Cloud Functions for Firebase , changing values in your app based on events that happen server-side. For example, you can use Remote Config to promote a new feature in your app, and then turn off that promotion automatically once you detect enough people have interacted with the new feature.
The following sections of this guide describe operations you can do with the Remote Config backend APIs. To review some code that performs these tasks via the REST API, see one of these sample apps:
- Firebase Remote Config REST API Java Quickstart
- Firebase Remote Config REST API Node.js Quickstart
- Firebase Remote Config REST API Python Quickstart
Modify Remote Config using the Firebase Admin SDK
The Admin SDK is a set of server libraries that let you interact with Firebase from privileged environments. In addition to performing updates to Remote Config, the Admin SDK enables generation and verification of Firebase auth tokens, reading and writing from Realtime Database, and so on. To learn more about Admin SDK prerequisites and setup, see Add the Firebase Admin SDK to your server .
In a typical Remote Config flow, you might get the current template, modify some of the parameters or parameter groups and conditions, validate the template, and then publish it. Before making those API calls, you must authorize requests from the SDK.
Initialize the SDK and authorize API requests
When you initialize the Admin SDK with no parameters, the SDK uses Google Application Default Credentials and reads options from the FIREBASE_CONFIG
environment variable. If the content of the FIREBASE_CONFIG
variable begins with a {
it will be parsed as a JSON object. Otherwise the SDK assumes that the string is the name of a JSON file containing the options.
例如:
節點.js
const admin = require('firebase-admin'); admin.initializeApp();
爪哇
FileInputStream serviceAccount = new FileInputStream("service-account.json"); FirebaseOptions options = FirebaseOptions.builder() .setCredentials(GoogleCredentials.fromStream(serviceAccount)) .build(); FirebaseApp.initializeApp(options);
Get the current Remote Config Template
When working with Remote Config templates, keep in mind that they are versioned, and that each version has a limited lifetime from its time of creation to the time you replace it with an update: 90 days, with a total limit of 300 stored versions. See Templates and Versioning for more information.
You can use the backend APIs to get the current active version of the Remote Config template in JSON format.
Parameters and parameter values created specifically as variants in an A/B Testing experiment are not included in exported templates.
To get the template:
節點.js
function getTemplate() { var config = admin.remoteConfig(); config.getTemplate() .then(function (template) { console.log('ETag from server: ' + template.etag); var templateStr = JSON.stringify(template); fs.writeFileSync('config.json', templateStr); }) .catch(function (err) { console.error('Unable to get template'); console.error(err); }); }
爪哇
Template template = FirebaseRemoteConfig.getInstance().getTemplateAsync().get(); // See the ETag of the fetched template. System.out.println("ETag from server: " + template.getETag());
Modify Remote Config parameters
You can programmatically modify and add Remote Config parameters and parameter groups. For example, to an existing parameter group named "new_menu" you could add a parameter to control the display of seasonal information:
節點.js
function addParameterToGroup(template) { template.parameterGroups['new_menu'].parameters['spring_season'] = { defaultValue: { useInAppDefault: true }, description: 'spring season menu visibility.', }; }
爪哇
template.getParameterGroups().get("new_menu").getParameters() .put("spring_season", new Parameter() .setDefaultValue(ParameterValue.inAppDefault()) .setDescription("spring season menu visibility.") );
The API allows you to create new parameters and parameter groups, or modify default values, conditional values, and descriptions. In all cases, you must explicitly publish the template after making modifications.
Modify Remote Config conditions
You can programmatically modify and add Remote Config conditions and conditional values. For example, to add a new condition:
節點.js
function addNewCondition(template) { template.conditions.push({ name: 'android_en', expression: 'device.os == \'android\' && device.country in [\'us\', \'uk\']', tagColor: 'BLUE', }); }
爪哇
template.getConditions().add(new Condition("android_en", "device.os == 'android' && device.country in ['us', 'uk']", TagColor.BLUE));
In all cases, you must explicitly publish the template after making modifications.
The Remote Config backend APIs provide several conditions and comparison operators that you can use to change the behavior and appearance of your app. To learn more about conditions and the operators supported for these conditions, see the conditional expression reference .
Validate the Remote Config template
Optionally, you can validate your updates before publishing them, as shown:
節點.js
function validateTemplate(template) { admin.remoteConfig().validateTemplate(template) .then(function (validatedTemplate) { // The template is valid and safe to use. console.log('Template was valid and safe to use'); }) .catch(function (err) { console.error('Template is invalid and cannot be published'); console.error(err); }); }
爪哇
try { Template validatedTemplate = FirebaseRemoteConfig.getInstance() .validateTemplateAsync(template).get(); System.out.println("Template was valid and safe to use"); } catch (ExecutionException e) { if (e.getCause() instanceof FirebaseRemoteConfigException) { FirebaseRemoteConfigException rcError = (FirebaseRemoteConfigException) e.getCause(); System.out.println("Template is invalid and cannot be published"); System.out.println(rcError.getMessage()); } }
This validation process checks for errors such as duplicate keys for parameters and conditions, invalid condition names or nonexistent conditions, or misformatted etags. For example, a request containing more than the allowed number of keys—2000—would return the error message, Param count too large
.
Publish the Remote Config template
Having retrieved a template and revised it with your desired updates, you can then publish it. Publishing a template as described in this section replaces the entire existing config template with the updated file, and the new active template is assigned a version number one number greater than the template it replaced.
If necessary, you can use the REST API to roll back to the previous version . To mitigate the risk of errors in an update, you can validate before publishing .
Remote Config personalizations and conditions are included in downloaded templates, so it's important to be aware of the following limitations when attempting to publish to a different project:
Personalizations cannot be imported from project to project.
For example, if you have personalizations enabled in your project and download and edit a template, you can publish it to the same project, but you can't publish it to a different project unless you delete the personalizations from the template.
Conditions can be imported from project to project, but note that any specific conditional values (like app IDs or audiences), should exist in the target project before publishing.
For example, if you have a Remote Config parameter that uses a condition that specifies a platform value of
iOS
, the template can be published to another project, because platform values are the same for any project. However, if it contains a condition that relies on a specific app ID or user audience that doesn't exist in the target project, validation will fail.If the template you plan to publish contains conditions that rely on Google Analytics, Analytics must be enabled in the target project.
節點.js
function publishTemplate() { var config = admin.remoteConfig(); var template = config.createTemplateFromJSON( fs.readFileSync('config.json', 'UTF8')); config.publishTemplate(template) .then(function (updatedTemplate) { console.log('Template has been published'); console.log('ETag from server: ' + updatedTemplate.etag); }) .catch(function (err) { console.error('Unable to publish template.'); console.error(err); }); }
爪哇
try { Template publishedTemplate = FirebaseRemoteConfig.getInstance() .publishTemplateAsync(template).get(); System.out.println("Template has been published"); // See the ETag of the published template. System.out.println("ETag from server: " + publishedTemplate.getETag()); } catch (ExecutionException e) { if (e.getCause() instanceof FirebaseRemoteConfigException) { FirebaseRemoteConfigException rcError = (FirebaseRemoteConfigException) e.getCause(); System.out.println("Unable to publish template."); System.out.println(rcError.getMessage()); } }
Modify Remote Config using the REST API
This section describes the main capabilities of the Remote Config REST API at https://firebaseremoteconfig.googleapis.com
. For full detail, see the API reference .
Get an access token to authenticate and authorize API requests
Firebase projects support Google service accounts , which you can use to call Firebase server APIs from your app server or trusted environment. If you're developing code locally or deploying your application on-premises, you can use credentials obtained via this service account to authorize server requests.
To authenticate a service account and authorize it to access Firebase services, you must generate a private key file in JSON format.
To generate a private key file for your service account:
In the Firebase console, open Settings > Service Accounts .
Click Generate New Private Key , then confirm by clicking Generate Key .
Securely store the JSON file containing the key.
When authorizing via a service account, you have two choices for providing the credentials to your application. You can either set the GOOGLE_APPLICATION_CREDENTIALS environment variable, or you can explicitly pass the path to the service account key in code. The first option is more secure and is strongly recommended.
To set the environment variable:
Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the file path of the JSON file that contains your service account key. This variable only applies to your current shell session, so if you open a new session, set the variable again.
Linux or macOS
export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"
Windows
With PowerShell:
$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"
After you've completed the above steps, Application Default Credentials (ADC) is able to implicitly determine your credentials, allowing you to use service account credentials when testing or running in non-Google environments.
Use your Firebase credentials together with the Google Auth Library for your preferred language to retrieve a short-lived OAuth 2.0 access token:
node.js
function getAccessToken() {
return admin.credential.applicationDefault().getAccessToken()
.then(accessToken => {
return accessToken.access_token;
})
.catch(err => {
console.error('Unable to get access token');
console.error(err);
});
}
In this example, the Google API client library authenticates the request with a JSON web token, or JWT. For more information, see JSON web tokens .
Python
def _get_access_token():
"""Retrieve a valid access token that can be used to authorize requests.
:return: Access token.
"""
credentials = ServiceAccountCredentials.from_json_keyfile_name(
'service-account.json', SCOPES)
access_token_info = credentials.get_access_token()
return access_token_info.access_token
爪哇
private static String getAccessToken() throws IOException {
GoogleCredentials googleCredentials = GoogleCredentials
.fromStream(new FileInputStream("service-account.json"))
.createScoped(Arrays.asList(SCOPES));
googleCredentials.refreshAccessToken();
return googleCredentials.getAccessToken().getTokenValue();
}
After your access token expires, the token refresh method is called automatically to retrieve an updated access token.
To authorize access to Remote Config, request the scope https://www.googleapis.com/auth/firebase.remoteconfig
.
Modify the Remote Config template
When working with Remote Config templates, keep in mind that they are versioned, and that each version has a limited lifetime from its time of creation to the time you replace it with an update: 90 days, with a total limit of 300 stored versions. See Templates and Versioning for more information.
Get the current Remote Config Template
You can use the backend APIs to get the current active version of the Remote Config template in JSON format.
Parameters and parameter values created specifically as variants in an A/B Testing experiment are not included in exported templates.
Use the following commands:
cURL
curl --compressed -D headers -H "Authorization: Bearer token" -X GET https://firebaseremoteconfig.googleapis.com/v1/projects/my-project-id/remoteConfig -o filename
This command outputs the JSON payload to one file, and the headers (including the Etag) to a separate file.
Raw HTTP request
Host: firebaseremoteconfig.googleapis.com GET /v1/projects/my-project-id/remoteConfig HTTP/1.1 Authorization: Bearer token Accept-Encoding: gzip
This API call returns the following JSON, along with a separate header which includes an ETag that you use for the subsequent request.
Validate the Remote Config template
Optionally, you can validate your updates before publishing them. Validate template updates by appending to your publish request the URL parameter ?validate_only=true
. In the response, a status code 200 and an updated etag with the suffix -0
means that your update was successfully validated. Any non-200 response indicates that the JSON data contains errors that you must correct before publishing.
Update the Remote Config template
Having retrieved a template and revised the JSON content with your desired updates, you can then publish it. Publishing a template as described in this section replaces the entire existing config template with the updated file, and the new active template is assigned a version number one number greater than the template it replaced.
If necessary, you can use the REST API to roll back to the previous version . To mitigate the risk of errors in an update, you can validate before publishing .
Remote Config personalizations and conditions are included in downloaded templates, so it's important to be aware of the following limitations when attempting to publish to a different project:
Personalizations cannot be imported from project to project.
For example, if you have personalizations enabled in your project and download and edit a template, you can publish it to the same project, but you can't publish it to a different project unless you delete the personalizations from the template.
Conditions can be imported from project to project, but note that any specific conditional values (like app IDs or audiences), should exist in the target project before publishing.
For example, if you have a Remote Config parameter that uses a condition that specifies a platform value of
iOS
, the template can be published to another project, because platform values are the same for any project. However, if it contains a condition that relies on a specific app ID or user audience that doesn't exist in the target project, validation will fail.If the template you plan to publish contains conditions that rely on Google Analytics, Analytics must be enabled in the target project.
cURL
curl --compressed -H "Content-Type: application/json; UTF8" -H "If-Match: last-returned-etag" -H "Authorization: Bearer token" -X PUT https://firebaseremoteconfig.googleapis.com/v1/projects/my-project-id/remoteConfig -d @filename
For this curl
command, you can specify the content by using the "@" character, followed by the filename.
Raw HTTP request
Host: firebaseremoteconfig.googleapis.com PUT /v1/projects/my-project-id/remoteConfig HTTP/1.1 Content-Length: size Content-Type: application/json; UTF8 Authorization: Bearer token If-Match: expected ETag Accept-Encoding: gzip JSON_HERE
Because this is a write request, the ETag is modified by this command and an updated ETag is provided in the response headers of the next PUT
command.
Modify Remote Config conditions
You can programmatically modify Remote Config conditions and conditional values. With the REST API, you must edit the template directly to modify conditions before publishing the template.
{ "conditions": [{ "name": "android_english", "expression": "device.os == 'android' && device.country in ['us', 'uk']", "tagColor": "BLUE" }, { "name": "tenPercent", "expression": "percent <= 10", "tagColor": "BROWN" }], "parameters": { "welcome_message": { "defaultValue": { "value": "Welcome to this sample app" }, "conditionalValues": { "tenPercent": { "value": "Welcome to this new sample app" } }, "description": "The sample app's welcome message" }, "welcome_message_caps": { "defaultValue": { "value": "false" }, "conditionalValues": { "android_english": { "value": "true" } }, "description": "Whether the welcome message should be displayed in all capital letters." } } }
The modifications above first define a set of conditions, and then defines default values and condition-based parameter ( conditional values ) values for each parameter. It also adds an optional description for each element; like code comments, these are for developer use and are not displayed in the app. An ETag is also provided for version control purposes.
The Remote Config backend APIs provide several conditions and comparison operators that you can use to change the behavior and appearance of your app. To learn more about conditions and the operators supported for these conditions, see the conditional expression reference .
HTTP Error codes
Status Code | Meaning |
---|---|
200 | Successfully Updated |
400 | A validation error occurred. For example, a request containing more than the allowed number of keys—2000—would return 400 (Bad Request) with the error message, Param count too large . Also, this HTTPS Status Code can occur in these two situations:
|
401 | An authorization error occurred (no access token was provided or the Firebase Remote Config REST API has not been added to your project in the Cloud Developer Console) |
403 | An authentication error occurred (the wrong access token was provided) |
500 | An internal error occurred. If this error occurs, file a Firebase support ticket |
A status code of 200 means that the Remote Config template (parameters, values and conditions for the project) has been updated and is now available to apps that use this project. Other status codes indicate that the Remote Config template that existed previously is still in effect.
After you submit updates to your template, go to the Firebase console to verify that your changes appear as expected. This is critical because the ordering of conditions affects how they are evaluated (the first condition that evaluates true
takes effect).
ETag usage and forced updates
The Remote Config REST API uses an entity tag (ETag) to prevent race conditions and overlapping updates to resources. To learn more about ETags, see ETag - HTTP .
For the REST API, Google recommends that you cache the ETag provided by the most recent GET
command, and use that ETag value in the If-Match
request header when issuing PUT
commands. If your PUT
command results in an HTTPS Status Code 409, you should issue a fresh GET
command to acquire a new ETag and template to use with your next PUT
command.
You can circumvent the ETag, and the protection from that it provides, by forcing the Remote Config template to be updated as follows: If-Match: *
However, this approach is not recommended because it risks causing the loss of updates to your Remote Config template if multiple clients are updating the Remote Config template. This kind of conflict could occur with multiple clients using the API, or with conflicting updates from API clients and Firebase console users.
For guidance on managing Remote Config template versions, see Remote Config templates and versioning .