Use the Remote Config REST API

This document describes how you can use the Remote Config REST API to read and modify the set of JSON-formatted parameters and conditions known as the Remote Config template. This allows you to manage the template programmatically, making template changes on the backend that the client app can fetch using the client library.

Using this API, you can bypass managing the template in the Remote Config console to directly integrate Remote Config changes into your own processes. For example, with Remote Config REST API, you could:

  • Scheduling Remote Config updates. By using the REST API 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 detail the steps required to get started with the Remote Config REST API. If you'd rather just run the code and inspect it, see one of the sample apps demonstrating use of the Remote Config REST API:

Get started using the Remote Config REST API

The steps in this section describe how to get and modify a Remote Config template with the API.

Before you begin: Enable the Remote Config REST API

For Firebase projects created before March 7, 2018: you must enable the Remote Config REST API in the Google APIs console.

  1. Open the Firebase Remote Config API page in the Google APIs console.
  2. When prompted, select your Firebase project. (Every Firebase project has a corresponding project in the Google APIs console.)
  3. Click Enable on the Firebase Remote Config API page.

Step 1: Set values in the Firebase console

Usually, you will start by setting values in the Firebase console. For the purposes of this guide, let's assume you have set up the Remote Config Quickstart sample app for iOS or Android. For this app, you only need to add the following two parameters to the Firebase console:

Parameter Key Default Value Notes
welcome_message Welcome to this sample app Change to use a different welcome message.
welcome_message_caps false Set to true to have the welcome message display in all caps.

Step 2: Get an access token to authenticate and authorize API requests

Every Firebase project has a default service account. You can use this account to call Firebase server APIs from your app server or trusted environment. If you use a different service account, make sure it has Editor or Owner permissions.

To authenticate the service account and authorize it to access Firebase services, you must generate a private key file in JSON format and use this key to retrieve a short-lived OAuth 2.0 token. Once you have a valid token, you can add it in your server requests as required by the various Firebase services such as Remote Config or FCM.

To generate a private key file for your service account:

  1. In the Firebase console, open Settings > Service Accounts.
  2. Click Generate New Private Key, and confirm by clicking Generate Key.
  3. Securely store the JSON file containing the key. You'll need it to complete the next step.

To retrieve an access token:

To retrieve the token, you can use the Google API Client Library for your preferred language, referencing the private key JSON file as shown:

node.js

 function getAccessToken() {
  return new Promise(function(resolve, reject) {
    var key = require('./service-account.json');
    var jwtClient = new google.auth.JWT(
      key.client_email,
      null,
      key.private_key,
      SCOPES,
      null
    );
    jwtClient.authorize(function(err, tokens) {
      if (err) {
        reject(err);
        return;
      }
      resolve(tokens.access_token);
    });
  });
}

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

Java

private static String getAccessToken() throws IOException {
  GoogleCredential googleCredential = GoogleCredential
      .fromStream(new FileInputStream("service-account.json"))
      .createScoped(Arrays.asList(SCOPES));
  googleCredential.refreshToken();
  return googleCredential.getAccessToken();
}

After your token expires, the token refresh method is called automatically to retrieve an updated token.

To authorize Remote Config API requests, set SCOPES in the above code example to https://www.googleapis.com/auth/firebase.remoteconfig.

Step 3: Get JSON from the Remote Config service with the API

Next, you can use the API to get the current active version of the Remote Config template in JSON format. Do this by using the following command, substituting your own project ID (available in the Firebase Console Settings pane) for <my-project-id>:

curl command:

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. The following example shows the JSON returned:

{
  "parameters":[
    {
      "key":"welcome_message",
      "value_options":[
        {
          "value":"Welcome to this sample app"
        }
      ]
    },
    {
      "key":"welcome_message_caps",
      "value_options":[
        {
          "value":"false"
        }
      ]
    }
  ],
  "version":{
    "version_number": "42",
    "update_time":"2018-05-11T18:46:40Z",
    "update_user":{
      "name":"Jane Developer",
      "email":"jane@developer.org",
      "imageUrl":"http://image.google.com/path-to-profile-photo-for-jane"
    },
    "description":"Adding welcome messages",
    "origin":"CONSOLE",
    "update_type":"INCREMENTAL_UPDATE"
  }
}

Step 4: Add conditions to the JSON data

Next, add some conditions and conditional values the will update the sample app to:

  • Display a slightly different message (with the word "new" added) to 10% of the users.
  • Display the message in all caps for users in the United States or the UK.

To extend the JSON in these ways, create a file containing the following:

{
  "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 JSON shown above first defines 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 in a separate header for version control purposes.

The Remote Config REST API provides 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.

Step 5: Publish JSON data to replace data in the Remote Config service

Having created a JSON file to update your Remote Config template, you can publish it by adding the JSON shown above to the following command, replacing the existing config. This operation 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.

For the curl command, you can specify the content by using the "@" character, followed by the filename.

If necessary, you can roll back to the previous version. To mitigate the risk of errors in an update, you can validate before publishing.

curl command:

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

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.

Validate before publishing

Optionally, you can validate your updates before publishing them 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.

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.
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)
409 This HTTPS Status Code can occur in two situations:
  • A version mismatch error occurred because the set of values and conditions have been updated since you last retrieved an ETag value. To resolve this, you should use a GET command to get a fresh template and ETag value, update the template, and then submit using that template and the fresh ETag value.
  • A PUT command (Update Remote Config template request) was made without specifying an If-Match header.
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.

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.

Send feedback about...

Need help? Visit our support page.