Building an API With Firebase

In this post, I will build an API with Google’s Firebase. I’ll build the back end with Firebase Cloud Functions and Express.js.

Before I begin, I recommend the following setup:

  1. A terminal set up on either a Windows, Linux, or Mac (OSX) computer
  2. Node 10.10 installed
  3. NVM installed with the instructions here
  4. A Google account
  5. Postman installed
  6. Firebase CLI installed with a run of the terminal command npm install -g firebase-tools

I’ll refer to the code available at this GitHub repo. The GitHub repo also contains a Postman Collection; I recommend importing it and using it to test your project.

Please note that the app id in the URL paths is specific to my deployed project. You’ll need to change the app id to match the project you’re creating in the Firebase Console.

If you don’t understand that yet, it’s okay — I’ll discuss this more after the initial project is set up.

The Basics

To start, I wanted to go over some basic concepts about what APIs are and how the technologies work. This is completely introductory, so feel free to skip this section if you are already familiar.

API stands for Application Programming Interface and refers to the method that computer systems use to communicate with one another.

Google’s dictionary defines APIs as:

“A set of functions and procedures allowing the creation of applications that access the features or data of an operating system, application, or other service.”
You build out an API so your system can communicate with whatever you’re building. APIs can include basic REST endpoints for a website or even the methods that define a software library you’ve built.

Which brings up the next important thing, RESTful services.

RESTful services refer to Representational State Transfer and take advantage of the HTTP protocol to pass data (via an API). The HTTP protocol is what we use every day in websites and internet applications.

RESTful services use different HTTP verbs (or methods) to pass data between different systems.

Typical HTTP verbs include:

  • GET = retrieving data
  • POST = creating or updating data
  • PUT = updating data
  • DELETE = deleting data

I also mentioned endpoints earlier; that’s what I’ll refer to when I mention a website or service I need to hit. An endpoint is just a fancy way to describe an address that my system will hit with an HTTP request.

For more on the ins and outs of HTTP requests, please refer to the wikipedia page.

Firebase

I’m using Google’s Firebase platform for this project. Firebase is a very powerful platform, which developers can use to build applications quickly.

Firebase provides common services that include:

To use Firebase, you simply need a Google account.

In the rest of this post, I’m going to walk through setting up the back end for an API built with Firebase.

Initial Setup

To start, go to the Firebase Console. You should see something like the following:

Click “add project” and give your project a name.

I recommend accepting the analytics, as it helps you and Google. You can refer to the analytics information later on in the console (after your project is created).

Once your project is created, open it in the console and click “database” on the left-hand navigation to see the following:

Click “Create database” under “Cloud Firestore” to create your initial database.

Select “test mode” to enable all reads and writes. You can set rules to specify security on your database to lock it down further later. Please consult the Firebase documentation here for more on locking down your database instances.

You’ll also be asked to set a location; the default should be fine, but you can also try to pick a datacenter closer to you. Check out this page for more on datacenter locations.

With the basic project pieces set up in the console, let’s switch to your computer to set up the code.

Writing Code

In this step, we’ll assume you already have the Firebase CLI on your machine. I recommend following the instructions here to set that up if you haven’t done so already.

Next, go to your terminal and create a folder for your project with mkdir my-project.

Next, cd into that folder and run firebase init; you should see something like the following:

Select “Functions” in the options menu. Then select the Firebase App that you created before in the list shown on the next terminal output.

The next set of options is fairly straightforward.

  • Select JavaScript
  • Select yes for linting
  • Select yes to install dependencies
  • And you’re good to go!

Next, cd into the created functions folder. When you run the init command, it will generate a functions folder for you to work with. The functions folder should have the following files:

  • index.js
  • node_modules folder
  • package-lock.json
  • package.json

Go ahead in your terminal editor of choice (I highly recommend VS Code) and look at index.js first.

Serverless APIs and Your First Endpoint

Firebase Functions enable you to use the Express.js library to host a serverless API. Serverless is a term for a system that runs without physical servers.

This is a bit of a misnomer because it technically does run on a server; however, you’re letting the provider handle the hosting. Traditional APIs would require you to set up a server either in the cloud or on prem that can host your application.

This means that developers would have to be in charge of OS patches and alerts, etc. With serverless, you don’t have to worry about anything but your code. This is one of the coolest parts of Firebase!

So, to use Express.js with your project, erase the index.js file and paste the following lines there:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({ origin: true }));

app.get('/hello-world', (req, res) => {
  return res.status(200).send('Hello World!');
});

exports.app = functions.https.onRequest(app);

The first lines that use require pull in the dependencies. We don’t yet have express or cors so let’s install them in the terminal with the following commands:

npm i express
npm i cors

The initial lines with the require value import the libraries we’re going to use.

Here are the libraries in more detail:

  • firebase-functions is an npm module that enables you to create functions.
  • firebase-admin is the Firebase admin SDK that enables your functions to control all of your back-end Firebase services.
  • express is the Express.js library that lets you create a server instance.
  • cors is an npm module that allows your functions to run somewhere separate from your client. The app.use enables CORS for your Express server instance.

The section of the code with app.get creates a “hello world” endpoint. We’re using Express routing here. There are many ways to do this. I’m explicitly defining the routes for the sake of ease.

In an enterprise environment, you would likely use the Express router and the code would probably look a little less verbose. For a more detailed dive into Express routing

For our purposes, the app.get is makes an HTTP GET** **request and captures the request in req and response in res.

When the endpoint is called, it will return a “Hello World!” string with an HTTP status code of 200. Status codes in HTTP are used to determine responses. There are many, but for this tutorial, 200 is success and 500 will return error.

The section with exports.app = functions.https.onRequest(app); exposes your Express application so it can be accessed. If you don’t have the exports section, your application won’t start correctly.

With packages installed and initial code set up, we can run our project with npm run serve. This will serve your functions locally and should result in the output as follows:

Now if you notice, I did get a warning about my Node version. Ignore that for now; I’ll come back to that when we start accessing the database.

Also, notice that the terminal outputs the localhost address of your API that is running locally. You’re going to call that directly from Postman as this is the “address” of your API.

When running on localhost, the URLs for your app will look like the following:

[<------domain---->]/[<-app id--->]/[<-zone-->]/app/[<-endpoint->]
http://localhost:5000/fir-api-9a206/us-central1/app/create

When we go to deploy, the only difference in the URL will be that <a href="http://localhost:500" target="_blank">http://localhost:500</a> will be replaced with zone + app id + cloudfunctions.net, similar to the following:

[<---zone + app id + cloudfunctions.net----->]/app/[<--endpoint-->]
https://us-central1-fir-api-9a206.cloudfunctions.net/app/hello-world

You’ll need to update the Postman collection with your app ID values. To see your app ID, go to the Firebase Console and click “project settings,” as in the following screenshot:

Once there, the project ID (and some other settings) will be listed. I’ve circled it in this screenshot:

Open up the Postman collection and edit the hello-world localhost request under the localhost folder.

As I mentioned, change the ID value to match your project. The address that was listed in the terminal when you ran npm run serve should have this information as well.

When you’re done, run the request from Postman and you should see the following:

Now that we have our initial endpoint set up, let’s go ahead and add database calls.

Database Calls

For the API we’re building, it’s just operations for a list of items. We’re going to set up Create, Read, Update, and Delete (or CRUD) functions for this list of items.

In Firebase, you have two options for database use. You can use a traditional database, or you can use Cloud Firestore.

For this tutorial, we’re going to use Cloud Firestore because it’s easier to work with and more versatile. Cloud Firestore is a NoSQL database, which means that your data is stored as documents within collections.

This is similar to how data is stored in rows in tables in an SQL database. NoSQL databases typically perform better and are easier to scale due to the nature of their data access and storage.

In the setup section, we added a Cloud Firestore instance to our project. To interact with the Cloud Firestore using the admin SDK locally, you’ll need to access it via a service account.

Service accounts have keys that they use; you run these permissions by downloading a key file.

To do this, go to the Firebase Console and open your application. Then click the little gearbox and “users and permissions” as you see here:

Then click the “service accounts” tab, and you should see something like the following:

If you notice, at the bottom of the screen they provide you with some code to run in your project. The only thing you’ll need is the permissions file to reference.

Go ahead and click “Generate new private key” to be able to install that in your project. Then, store that next to the index.js file in your functions folder we were just working with.

You can name it whatever you want; I named mine permissions.json.

Then, add the following to the top of your index.js file:

var serviceAccount = require("./permissions.json");
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://fir-api-9a206..firebaseio.com"
});
const db = admin.firestore();

These lines (1) load in your permissions file and then (2) use it to initialize your application. I also created a variable db to represent our Firestore instance. This isn’t necessary but makes the code cleaner later on.

With those values loaded up, let’s add a create endpoint to our application. Below the hello-world endpoint, add the following:

// create
app.post('/api/create', (req, res) => {
    (async () => {
        try {
          await db.collection('items').doc('/' + req.body.id + '/')
              .create({item: req.body.item});
          return res.status(200).send();
        } catch (error) {
          console.log(error);
          return res.status(500).send(error);
        }
      })();
  });

This code creates an endpoint /api/create-item that you make a POST call to. When the POST call is made, it adds the item from the body to a collection in the database called “items” with an ID of the value you passed in, called id here.

Collections in a NoSQL database are just collectors of documents. You could just as easily do this with a specific document. I tend to like collections when using Firestore because they’re easy to understand. You can also think of collections similarly to tables in an SQL Database.

If you also notice, I’ve prefixed the endpoint with /api. This is not required but is typically convenient with any API you create.* *I’m also specifying the ID value with my requests. Firebase will do this for you, but I thought it was easier to understand if we explicitly define this in the requests.

So with this code added, let’s stop the server in the terminal (if you haven’t already) and restart it with a new npm run serve.

In the Postman collection, pull up the “create localhost” POST request. Modify the app id value as you did before, and attempt the request.

When you run it, you should see the following error:

The Firebase admin SDK requires Node version 8.13.0 or 10.10. This is why I asked to install nvm in the first section. This is very easy to fix. nvm enables you to quickly switch Node versions in your local terminal.

In your terminal, run nvm use 10.10, and you should see the following:

Now start your server again with npm run serve and hit the endpoint on Postman. You should see a 200 success. In the terminal, you can also see that the API was hit locally.

If you run into an error about onRequestWithOpts or something similar, do an npm i firebase-tools.

An error recently came up with the CLI: version 7.1.0 fixed this. When writing this post, I found I needed to update my Firebase CLI version to fix this. Check out this issue for more.

One additional cool feature is that you can directly see your data in Cloud Firestore. If you hop over to the Firebase console, click the “database” link on the left-hand navigation and you should see something like the following:

Building the DB Endpoints

So now that we have the create endpoint set up, let’s add the rest of the operations:

  • /read-item/:item_id = read a specific item (by ID)
  • /read-items = read all items (total collection)
  • /update-item/:item_id = update an item
  • delete-item/:item_id = delete an item

For the most part, all of the endpoints will be similar. The exception is when I pass query params with the item_id value. This all follows basic routing, which you can see in the Express.js documentation.

Additionally, for actually interacting with the Firebase Admin SDK, I recommend the Firestore API reference here.

For a look at what these endpoints should look like (when finished) check out the <a href="https://github.com/andrewevans0102/how-to-build-a-firebase-api/blob/master/functions/index.js?source=post_page---------------------------" target="_blank">index.js</a> file on the GitHub repo here.

Here’s the code for the rest of the endpoints:

---

// read item
app.get('/api/read/:item_id', (req, res) => {
    (async () => {
        try {
            const document = db.collection('items').doc(req.params.item_id);
            let item = await document.get();
            let response = item.data();
            return res.status(200).send(response);
        } catch (error) {
            console.log(error);
            return res.status(500).send(error);
        }
        })();
    });

// read all
app.get('/api/read', (req, res) => {
    (async () => {
        try {
            let query = db.collection('items');
            let response = [];
            await query.get().then(querySnapshot => {
            let docs = querySnapshot.docs;
            for (let doc of docs) {
                const selectedItem = {
                    id: doc.id,
                    item: doc.data().item
                };
                response.push(selectedItem);
            }
            });
            return res.status(200).send(response);
        } catch (error) {
            console.log(error);
            return res.status(500).send(error);
        }
        })();
    });

// update
app.put('/api/update/:item_id', (req, res) => {
(async () => {
    try {
        const document = db.collection('items').doc(req.params.item_id);
        await document.update({
            item: req.body.item
        });
        return res.status(200).send();
    } catch (error) {
        console.log(error);
        return res.status(500).send(error);
    }
    })();
});

// delete
app.delete('/api/delete/:item_id', (req, res) => {
(async () => {
    try {
        const document = db.collection('items').doc(req.params.item_id);
        await document.delete();
        return res.status(200).send();
    } catch (error) {
        console.log(error);
        return res.status(500).send(error);
    }
    })();
});


---

Deploying

So now we have a fully functional CRUD API. We’re ready to deploy!

If you’re developing an enterprise application (or one that you’ll be maintaining), it is typical to build a Continuous Integration Continuous Deployment (CICD) pipeline. This is a set of steps that are automated for delivering your application into production.

With our API, we’re interested in the actual deployment step. The Firebase CLI takes care of this for you with a firebase deploy.

When you ran the firebase init command to initially build your project, the Firebase CLI already set up the deploy step as an npm script. We can now deploy that created project with npm run deploy from the functions folder.

npm scripts are very powerful. Most modern JavaScript applications use them in one way or another. I recommend checking out the npm documentation for more.

When you run npm run deploy from the functions folder, you should see something like the following output:

The line of the terminal output Function URL provides the endpoint of your deployed functions. Go back to the Postman collection and check out the deployed folder for a set of requests to hit your deployed API.

Connecting a Front End

Now that we’ve built out the API, I wanted to showcase what it would look like if you were to use it in a client application.

When discussing APIs, typically you will have a producer and a consumer. The producer is the API itself (or at least what provides the endpoints). The consumer is anything that uses those endpoints. Typically application developers will build a client application using JavaScript frameworks such as Angular, React, Ember.js, Vue.js, and others.

Client applications are run in the browser and enable JavaScript code to be interpreted on the fly. This is particularly useful because many times developers need somewhere to statically host their JavaScript bundle.

This takes advantage of the JavaScript language as well as many advances that have happened with browsers today.

If you remember from the first sections, we’re using the code I put on this GitHub repo. This GitHub project has both our back-end API code and a front-end Angular application that I built to interact with the API.

The basic application consists of one main page and is considered a Single Page Application (SPA). The application does basic CRUD operations on list items.

While running the application, you can also see it in action in the browser’s console. If you open the console (right-click “inspect” if you’re using Chrome), you should see the following:

To use the client I built, first cd into the frontend folder of my GitHub project.

To make the application run against the endpoints of the API you deployed, you just need to open the /frontend/src/environments/environment.ts file.

In this file, you’ll see a set of endpoints. To use the client I built, first cd into the frontend folder of my GitHub project.

To make the application run against the endpoints of the API you deployed, you just need to change these values to match the URLs from your project.

If you remember, once you deployed your API, the Firebase CLI output a domain to the terminal. The hosted endpoint nomenclature is super intuitive and is as follows:

[<----zone + app id + cloudfunctions.net----->]/app/[<--endpoint-->]
https://us-central1-fir-api-9a206.cloudfunctions.net/app/hello-world

Go ahead and replace the endpoint values in this environments file with the ones from your project. Remember to always end each endpoint with the associated path like /api/create or /api/read, respectively.

Once you’ve replaced the values, cd into the frontend directory and run a standard npm install to install the dependencies. Once the dependencies finish installing, use the Angular CLI command to start the app with ng serve.

If you encounter errors with the CLI, check out the Angular CLI documentation.

After running ng serve, you should see something like the following in the terminal:

This message means the CLI has built the application (with webpack) and it is currently running on port 4200. If you open your browser and go to localhost:4200, you should see the app running.

If you look at the project’s app component, you’ll see that the actions are just doing JavaScript fetch calls to the endpoints from the API we created:

async selectAll() {
    try {
      console.log(environment.readAll);
      console.log('calling read all endpoint');

      this.exampleItems = [];
      const output = await fetch(environment.readAll);
      const outputJSON = await output.json();
      this.exampleItems = outputJSON;
      console.log('Success');
      console.log(outputJSON);
    } catch (error) {
      console.log(error);
    }
  }

  // really this is create but the flow is that
  // click the "create item" button which appends a blank value to the array, then click save to actually create it permanently
  async saveItem(item: any) {
    try {
      console.log(environment.create);
      console.log('calling create item endpoint with: ' + item.item);

      const requestBody = {
        id: item.id,
        item: item.item
      };

      const createResponse =
        await fetch(environment.create, {
          method: 'POST',
          body: JSON.stringify(requestBody),
          headers:{
            'Content-Type': 'application/json'
          }
        });
      console.log('Success');
      console.log(createResponse.status);

      // call select all to update the table
      this.selectAll();
    } catch (error) {
      console.log(error);
    }
  }

  async updateItem(item: any) {
    try {
      console.log(environment.update);
      console.log('calling update endpoint with id ' + item.id + ' and value "' + item.item);

      const requestBody = {
        item: item.item
      };

      const updateResponse =
        await fetch(environment.update + item.id, {
          method: 'PUT',
          body: JSON.stringify(requestBody),
          headers:{
            'Content-Type': 'application/json'
          }
        });
      console.log('Success');
      console.log(updateResponse.status);

      // call select all to update the table
      this.selectAll();
    } catch (error) {
      console.log(error);
    }
  }

  async deleteItem(item: any) {
    try {
      console.log(environment.delete);
      console.log('calling delete endpoint with id ' + item.id);

      const deleteResponse =
        await fetch(environment.delete + item.id, {
          method: 'DELETE',
          headers:{
            'Content-Type': 'application/json'
          }
        });

      console.log('Success');
      console.log(deleteResponse.status);

      // call select all to update the table
      this.selectAll();
    } catch (error) {
      console.log(error);
    }
  }

Since the main point of this post was creating the API, I won’t go into the details of how this Angular application works. I highly recommend you check out the Angular Documentation and the available tutorials.

Closing Thoughts

Photo by Markus Spiske on Unsplash

Congratulations! You’ve just deployed an API with Firebase. There are a lot of additional things you can do with this API, but this shows you the basics.

I hope my post here has helped you get started with building APIs with Firebase.

#node-js #api #javascript #firebase #express

Building an API With Firebase
2 Likes63.10 GEEK