Deploy to your site using the Hosting REST API  |  Firebase Hosting (2023)

The Firebase Hosting REST API enablesprogrammatic and customizable deployments to your Firebase-hosted sites.Use this REST API to deploy new or updated Hosting content andconfiguration.

As an alternative to using the Firebase CLI fordeployments, you can use the Firebase Hosting REST API to programmaticallycreate a new version ofassets for your site, upload files to the version, then deploy the version toyour site.

For example, with the Firebase Hosting REST API, you can:

  • Schedule deploys. By using the REST API in conjunction with a cron job,you can change Firebase-hosted content on a regular schedule (for example, todeploy a special holiday or event-related version of your content).

  • Integrate with developer tools. You can create an option in your tool todeploy your web app projects to Firebase Hosting using just one click (forexample, clicking a deploy button within an IDE).

  • Automate deploys when static content is generated. When a processgenerates static content programmatically (for example, user-generated contentsuch as a wiki or a news article), you can deploy the generated content asstatic files rather than serving them dynamically. This saves you expensivecompute power and serves your files in a more scalable way.

This guide first describes how to enable, authenticate, and authorize the API.Then this guide walks through an example to create a Firebase Hostingversion, to upload required files to the version, then finally to deploy theversion.

You can also learn more about this REST API in thefull Hosting REST API reference documentation.

Before you begin: Enable the REST API

You must enable the Firebase Hosting REST API in the Google APIs console:

  1. Open theFirebase Hosting API page in the Google APIs console.

  2. When prompted, select your Firebase project.

  3. Click Enable on the Firebase Hosting API page.

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

Firebase projects support Googleservice accounts,which you can use to call Firebaseserver APIs from your app server or trusted environment. If you're developingcode locally or deploying your application on-premises,you can use credentials obtainedvia this service account to authorize server requests.

To authenticate a service account and authorize itto access Firebase services, you must generate a private key file in JSONformat.

To generate a private key file for your service account:

  1. In the Firebase console, openSettings > Service Accounts.

  2. Click Generate New Private Key, then confirm by clicking Generate Key.

  3. Securely store the JSON file containing the key.

Use your Firebase credentials together withthe Google Auth Libraryfor your preferred language to retrieve a short-lived OAuth 2.0 access token:

node.js

const {google} = require('googleapis');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); }); });}

In this example, the Google API client library authenticates the request witha JSON web token, or JWT. For more information, seeJSON 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

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 access token expires, the token refresh method is calledautomatically to retrieve an updated access token.

Step 2: Create a new version for your site

Your first API call is to create a newVersion for your site.Later in this guide, you’ll upload files to this version, then deploy it to yoursite.

  1. Determine the SITE_ID for the site to which you want to deploy.

  2. Call theversions.createendpoint using your SITE_ID in the call.

    (Optional) You can also pass aFirebase Hosting configuration objectin the call, including setting a header that caches all files for a specifiedlength of time.

    For example:

    cURL command

    curl -H "Content-Type: application/json" \ -H "Authorization: Bearer ACCESS_TOKEN" \ -d '{ "config": { "headers": [{ "glob": "**", "headers": { "Cache-Control": "max-age=1800" } }] } }' \https://firebasehosting.googleapis.com/v1beta1/sites/SITE_ID/versions

    Raw HTTPS request

    Host: firebasehosting.googleapis.comPOST /v1beta1/sites/SITE_ID/versions HTTP/1.1Authorization: Bearer ACCESS_TOKENContent-Type: application/jsonContent-Length: 134{ "config": { "headers": [{ "glob": "**", "headers": { "Cache-Control": "max-age=1800" } }] }}

This API call to versions.create returns the following JSON:

{ "name": "sites/SITE_ID/versions/VERSION_ID", "status": "CREATED", "config": { "headers": [{ "glob": "**", "headers": { "Cache-Control": "max-age=1800" } }] }}

This response contains a unique identifier for the new version, in the format:sites/SITE_ID/versions/VERSION_ID. You’llneed this unique identifier throughout this guide to reference this specificversion.

Step 3: Specify the list of files you want to deploy

Now that you have your new version identifier, you need to tellFirebase Hosting which files you want to eventually deploy in this newversion.

Note that Hosting has a maximum size limit of 2 GB forindividual files.

This API requires that you identify files by a SHA256 hash. So, before you canmake the API call, you’ll first need to calculate a hash for each static file byGzipping the files then taking the SHA256 hash of each newly compressed file.

Continuing our example, let's say that you want to deploy three files in the newversion: file1, file2, and file3.

  1. Gzip the files:

    gzip file1 && gzip file2 && gzip file3

    You now have three compressed files file1.gz, file2.gz, and file3.gz.

  2. Get the SHA256 hash of each compressed file:

    cat file1.gz | openssl dgst -sha25666d61f86bb684d0e35f94461c1f9cf4f07a4bb3407bfbd80e518bd44368ff8f4
    cat file2.gz | openssl dgst -sha256490423ebae5dcd6c2df695aea79f1f80555c62e535a2808c8115a6714863d083
    cat file3.gz | openssl dgst -sha25659cae17473d7dd339fe714f4c6c514ab4470757a4fe616dfdb4d81400addf315

    You now have the three SHA256 hashes of the three compressed files.

  3. Send these three hashes in an API request to theversions.populateFilesendpoint. List each hash by the desired path for the uploaded file (in thisexample, /file1, /file2, and /file3).

    For example:

    cURL command

    $ curl -H "Content-Type: application/json" \ -H "Authorization: Bearer ACCESS_TOKEN" \ -d '{ "files": { "/file1": "66d61f86bb684d0e35f94461c1f9cf4f07a4bb3407bfbd80e518bd44368ff8f4", "/file2": "490423ebae5dcd6c2df695aea79f1f80555c62e535a2808c8115a6714863d083", "/file3": "59cae17473d7dd339fe714f4c6c514ab4470757a4fe616dfdb4d81400addf315" } }' \https://firebasehosting.googleapis.com/v1beta1/sites/SITE_ID/versions/VERSION_ID:populateFiles

    Raw HTTPS Request

    Host: firebasehosting.googleapis.comPOST /v1beta1/sites/SITE_ID/versions/VERSION_ID:populateFiles HTTP/1.1Authorization: Bearer ACCESS_TOKENContent-Type: application/jsonContent-Length: 181{ "files": { "/file1": "66d61f86bb684d0e35f94461c1f9cf4f07a4bb3407bfbd80e518bd44368ff8f4", "/file2": "490423ebae5dcd6c2df695aea79f1f80555c62e535a2808c8115a6714863d083", "/file3": "59cae17473d7dd339fe714f4c6c514ab4470757a4fe616dfdb4d81400addf315" }}

This API call to versions.populateFiles returns the following JSON:

{ "uploadRequiredHashes": [ "490423ebae5dcd6c2df695aea79f1f80555c62e535a2808c8115a6714863d083", "59cae17473d7dd339fe714f4c6c514ab4470757a4fe616dfdb4d81400addf315" ], "uploadUrl": "https://upload-firebasehosting.googleapis.com/upload/sites/SITE_ID/versions/VERSION_ID/files"}

This response includes:

  • The hash of each file that needs to be uploaded. For instance, in thisexample file1 had already been uploaded in a previous version, so its hashis not included in the uploadRequiredHashes list.

  • The uploadUrl which is specific to the new version.

In the next step to upload the two new files, you’ll need the hashes and theuploadURL from the versions.populateFiles response.

Step 4: Upload required files

You need to individually upload each required file (those files which are listedin uploadRequiredHashes from the versions.populateFiles response in theprevious step). For these file uploads, you’ll need the file hashes and theuploadUrl from the previous step.

  1. Append a forward slash and the hash of the file to the uploadUrl tocreate a file-specific URL in the format:https://upload-firebasehosting.googleapis.com/upload/sites/SITE_ID/versions/VERSION_ID/files/FILE_HASH.

  2. Upload all the required files one-by-one (in this example, only file2.gzand file3.gz) to the file-specific URL using a series of requests.

    For example, to upload the compressed file2.gz:

    cURL command

    curl -H "Authorization: Bearer ACCESS_TOKEN" \ -H "Content-Type: application/octet-stream" \ --data-binary @./file2.gz \https://upload-firebasehosting.googleapis.com/upload/sites/SITE_ID/versions/VERSION_ID/files/FILE_HASH

    Raw HTTPS Request

    Host: upload-firebasehosting.googleapis.comPOST /upload/sites/SITE_ID/versions/VERSION_ID/files/FILE_HASH HTTP/1.1Authorization: Bearer ACCESS_TOKENContent-Type: application/octet-streamContent-Length: 500content-of-file2.gz

Successful uploads return a 200 OK HTTPS response.

Step 5: Update the status of the version to FINALIZED

After you’ve uploaded all the files which are listed in theversions.populateFiles response, you can update the status of your version toFINALIZED.

Call the versions.patchendpoint with the status field in your API request set to FINALIZED.

For example:

cURL command

curl -H "Content-Type: application/json" \ -H "Authorization: Bearer ACCESS_TOKEN" \ -X PATCH \ -d '{"status": "FINALIZED"}' \https://firebasehosting.googleapis.com/v1beta1/sites/SITE_ID/versions/VERSION_ID?update_mask=status

Raw HTTPS Request

Host: firebasehosting.googleapis.comPATCH /v1beta1/sites/SITE_ID/versions/VERSION_ID?update_mask=status HTTP/1.1Authorization: Bearer ACCESS_TOKENContent-Type: application/jsonContent-Length: 23{"status": "FINALIZED"}

This API call to versions.patch returns the following JSON. Check thatstatus has been updated to FINALIZED.

{ "name": "sites/SITE_ID/versions/VERSION_ID", "status": "FINALIZED", "config": { "headers": [{ "glob": "**", "headers": {"Cache-Control": "max-age=1800"} }] }, "createTime": "2018-12-02T13:41:56.905743Z", "createUser": { "email": "SERVICE_ACCOUNT_EMAIL@SITE_ID.iam.gserviceaccount.com" }, "finalizeTime": "2018-12-02T14:56:13.047423Z", "finalizeUser": { "email": "USER_EMAIL@DOMAIN.tld" }, "fileCount": "5", "versionBytes": "114951"}

Step 6: Release the version for deployment

Now that you have a finalized version, release it for deployment. For this step,you need to create aRelease of your versionthat contains the hosting configuration and all the content files for your newversion.

Call the releases.createendpoint to create your release.

For example:

cURL command

curl -H "Authorization: Bearer ACCESS_TOKEN" \ -X POSThttps://firebasehosting.googleapis.com/v1beta1/sites/SITE_ID/releases?versionName=sites/SITE_ID/versions/VERSION_ID

Raw HTTPS Request

Host: firebasehosting.googleapis.comPOST /v1beta1/sites/SITE_ID/releases?versionName=sites/SITE_ID/versions/VERSION_ID HTTP/1.1Authorization: Bearer ACCESS_TOKEN

This API call to releases.create returns the following JSON:

{ "name": "sites/SITE_ID/releases/RELEASE_ID", "version": { "name": "sites/SITE_ID/versions/VERSION_ID", "status": "FINALIZED", "config": { "headers": [{ "glob": "**", "headers": {"Cache-Control": "max-age=1800"} }] } }, "type": "DEPLOY", "releaseTime": "2018-12-02T15:14:37Z"}

The hosting configuration and all the files for the new version should now bedeployed to your site, and you can access your files using the URLs:

  • https://SITE_ID.web.app/file1
  • https://SITE_ID.web.app/file2
  • https://SITE_ID.web.app/file3

These files are also accessible on URLs associated with yourSITE_ID.firebaseapp.com domain.

You can also see your new release listed in theHosting dashboard of the Firebase console.

Top Articles
Latest Posts
Article information

Author: Jonah Leffler

Last Updated: 04/22/2023

Views: 5579

Rating: 4.4 / 5 (45 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Jonah Leffler

Birthday: 1997-10-27

Address: 8987 Kieth Ports, Luettgenland, CT 54657-9808

Phone: +2611128251586

Job: Mining Supervisor

Hobby: Worldbuilding, Electronics, Amateur radio, Skiing, Cycling, Jogging, Taxidermy

Introduction: My name is Jonah Leffler, I am a determined, faithful, outstanding, inexpensive, cheerful, determined, smiling person who loves writing and wants to share my knowledge and understanding with you.