Introducing Firebase Extensions

Introducing Firebase Extensions

Firebase Extensions are prepackaged solutions that provide extended functionality to your application and they’re written, tested, and debugged by the Firebase team. Watch now and see the Firebase Extensions that have already been built!

Firebase Extensions are prepackaged solutions that provide extended functionality to your application and they’re written, tested, and debugged by the Firebase team. Watch now and see the Firebase Extensions that have already been built!

Firebase Flutter Tutorial - Firebase CloudStorage in Flutter

Firebase Flutter Tutorial - Firebase CloudStorage in Flutter

In this Firebase Flutter Tutorial, we wrap the Firebase Storage package into a service to easily manage and upload the firebase storage.

Hello there Flutter Dev 🙋‍♂️ In this tutorial we will be going over Cloudstorge on Firebase and how to integrate that with your mobile application.

Today we'll do a simple task that is probably a very common task in mobile app development. We will provide the user with a UI to select and upload a photo, save that photo in a post and display that to them in a collection. The photo will be stored in Firebase CloudStorage and we'll use a URL to the photo to display to users in the app. We'll start off by updating the UI to allow us to upload a photo.

Cloud Storage Setup

Before we start with the code lets setup our cloud storage. Open up the firebase console and click on the storage icon in the left toolbar. Click on create bucket, choose the location and continue. You will now have what is called a "bucket" where you can store files. You can think of this as a hard drive that you access through a url web request. Each of the files here will have an access token / url that you can access only through that url with the attached token. You can set visibility by controling the access level for that download url token. This is the url we'll use to display the image in the app.

Implementation

Let go over a quick implementation overview. We'll create a service that wraps the provided firebase storage package. This service will take in a File object and a title and upload that to the storage. When the operation is complete we will return the url which is what we'll put inside of our post as the imageUrl. The file that we're passing in will be selected using the UI presented by the image picker library. Let's get to it.

Code setup

We start off by adding the firebase_storage and the image_picker package to the pubspec.

firebase_storage: ^3.1.1
image_picker: ^0.6.3+1

Firebase storage is to interact with the Firebase Cloud Storage, the image picker is to show the user a UI that will allow them to select an image from their device.

Cloud Storage Implementation

Under the services folder create a new file called cloud_storage_service.dart. We'll give it a function called uploadImage that Takes in a required file as well as a title. You can pass in the UID, or anything you'd like to identify your images by.

import 'package:firebase_storage/firebase_storage.dart';

class CloudStorageService {
  Future<CloudStorageResult> uploadImage({
    @required File imageToUpload,
    @required String title,
  }) async {

  }
}

class CloudStorageResult {
  final String imageUrl;
  final String imageFileName;

  CloudStorageResult({this.imageUrl, this.imageFileName});
}

To access the Firestore Storage instance we use the FirebaseStorage.instance static property. The storage library works similar to the firebase documents. You can get a reference to a file that doesn't exist yet and then add the data in there that you want. We'll get a reference to our future file using the title and the date epoch to keep it unique. Once we have our reference we will call putFile and pass it in the selected File. This will give us a StorageUploadTask. This object has an onComplete Future that returns a StorageTaskSnapshot (similar to firebase snapshot). We can await that future and once we have the snapshot we can use the StorageReference returned and get the downloadUrl. We'll return the url when the task is complete or null.

  Future<CloudStorageResult> uploadImage({
    @required File imageToUpload,
    @required String title,
  }) async {

    var imageFileName = title + DateTime.now().millisecondsSinceEpoch.toString();

    final StorageReference firebaseStorageRef = FirebaseStorage.instance
    .ref()
    .child(imageFileName);

    StorageUploadTask uploadTask = firebaseStorageRef.putFile(imageToUpload);

    StorageTaskSnapshot storageSnapshot = await uploadTask.onComplete;

    var downloadUrl = await storageSnapshot.ref.getDownloadURL();

    if (uploadTask.isComplete) {
      var url = downloadUrl.toString();
      return CloudStorageResult(
        imageUrl: url,
        imageFileName: imageFileName,
        );
    }

    return null;
  }

Open up the locator.dart file and register the CloudStorageService with the get_it instance.

locator.registerLazySingleton(() => CloudStorageService());

Image Selection Implementation

We'll start off by wrapping the ImagePicker library into our own class. This way our business logic is not dependent on any third party packages. It's something I like to do, if you go the additional step and add it behind an interface then you can mock it out during testing as well.

Create a new folder called utils. Inside create a new file called image_selector.dart

import 'package:image_picker/image_picker.dart';

class ImageSelector {
  Future<File> selectImage() async {
    return await ImagePicker.pickImage(source: ImageSource.gallery);
  }

}

I know it seems silly to have a class that wraps one line, but you can do much more with it than this. You can keep the file in memory until you're certain it's uploaded, you can have different sources passed in from different functions, etc. The main reason for this is to remove the dependency of ImagePicker from any of the code in the app that has to make use of the functionality.

Open up the locator.dart file and register the ImageSelector with the get_it instance.

locator.registerLazySingleton(() => ImageSelector());

Finally open up the CreatePostViewModel where we'll locate the selector and then make use of it in a function called selectAndUploadImage. We'll also import the CloudStorageService for later use. We'll use the selectImage function to set the image to upload and display that to the user in the UI.

class CreatePostViewModel extends BaseModel {
  final ImageSelector _imageSelector = locator<ImageSelector>();
  final CloudStorageService _cloudStorageService = locator<CloudStorageService>();

  File _selectedImage;
  File get selectedImage => _selectedImage;

  Future selectImage() async {
    var tempImage = await _imageSelector.selectImage();
    if(tempImage != null) {
      _selectedImage = tempImage;
      notifyListeners();
    }
  }
}

In the same viewmodel update the addPost function to upload the image if we're not editting the post. We'll then use that url as the imageUrl in the post. For error handling I would show a snack bar if the imageUrl comes back null that indicates to the user that the image upload has failed.

 Future addPost({@required String title}) async {
    setBusy(true);

    CloudStorageResult storageResult;

    if (!_editting) {
      storageResult = await _cloudStorageService.uploadImage(
          imageToUpload: _selectedImage, title: title);
    }

    var result;

     if (!_editting) {
      result = await _firestoreService.addPost(Post(
        title: title,
        userId: currentUser.id,
        imageUrl:  storageResult.imageUrl,
        imageFileName: storageResult.imageFileName
      ));
    } else {
      result = await _firestoreService.updatePost(Post(
        title: title,
        userId: _edittingPost.userId,
        documentId: _edittingPost.documentId,
        imageUrl: _edittingPost.imageUrl,
        imageFileName: _edittingPost.imageFileName,
      ));
    }

    ...
  }

Next, open the Post model and add the new imageFileName String that we'll use to later delete the post.

class Post {
  ...
  final String imageFileName;

  Post({
    ...
    this.imageFileName,
  });

  Map<String, dynamic> toMap() {
    return {
      ...
      'imageFileName': imageFileName,
    };
  }

  static Post fromMap(Map<String, dynamic> map, String documentId) {
    if (map == null) return null;

    return Post(
      ...
      imageFileName: map['imageFileName'],
      documentId: documentId,
    );
  }
}

Now we can go onto the UI for the functionality. First thing to do is update the CreatePostView and add a gesture detector onto the grey rectangle we're displaying. When tapped we'll call the selectImage function. We'll also add a conditional to make sure when an image is selected we show it in that grey block. Update the container in the create_post_view that has the text in it to the following.

GestureDetector(
  // When we tap we call selectImage
  onTap: () => model.selectImage(),
  child: Container(
    height: 250,
    decoration: BoxDecoration(
        color: Colors.grey[200],
        borderRadius: BorderRadius.circular(10)),
    alignment: Alignment.center,
    // If the selected image is null we show "Tap to add post image"
    child: model.selectedImage == null
        ? Text(
            'Tap to add post image',
            style: TextStyle(color: Colors.grey[400]),
          )
          // If we have a selected image we want to show it
        : Image.file(model.selectedImage),
  ),
)

If you run the app now, tap on the FAB, enter a title and tap on the image block you'll see the image picker pop up. Select an image and it should be showing in the grey block in place of the text :) Add the post by pressing the FAB and it'll send it up to the cloud and return you a url.

If you open up the cloud storage now you'll see a file with the title you enetered and a number after it. That's the image you uploaded. Next up is displaying the image.

Image display implementation

To display the images from the cloud storage we will use the cached_network_image package. Add it to your pubspec.

cached_network_image: ^2.0.0

Open up the post_item and we'll update the UI. First thing is to make sure when we have an image we don't want to give the list a fixed size. We'll check if there's an image. If there's an image we set the heigh to null (meaning wrap content), otherwise we set it to 60.

class PostItem extends StatelessWidget {
  final Post post;
  ...
  @override
  Widget build(BuildContext context) {
    return Container(
      // Check if we have an image and set it to null or 60
      height: post.imageUrl != null ? null : 60,
      margin: const EdgeInsets.only(top: 20),
      alignment: Alignment.center,
      child: Row(
        children: <Widget>[
          Expanded(
              child: Padding(
            padding: const EdgeInsets.only(left: 15.0),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                // If the image is not null load the imageURL
                post.imageUrl != null
                    ? SizedBox(
                        height: 250,
                        child: CachedNetworkImage(
                          imageUrl: post.imageUrl,
                          placeholder: (context, url) =>
                              CircularProgressIndicator(),
                          errorWidget: (context, url, error) =>
                              Icon(Icons.error),
                        ),
                      )
                // If the image is null show nothing
                    : Container(),
                Text(post.title),
              ],
            ),
          )),
         ...
        ],
      ),
      ...
    );
  }
}

That's it. You can now, post an image to the cloud storage. Then see it load as an item in the list of posts :)

Delete on Cloud Storage

Last thing to do is to delete the image again when a post is removed. This can be done by simple getting the ref and calling delete on it. Open up the CloudStorageService and we'll add a delete function.

class CloudStorageService {
   Future deleteImage(String imageFileName) async {
    final StorageReference firebaseStorageRef =
        FirebaseStorage.instance.ref().child(imageFileName);

    try {
      await firebaseStorageRef.delete();
      return true;
    } catch (e) {
      return e.toString();
    }
  }
}

Open up the HomeViewModel, locate the CloudStorageService and then after deleting the post from the firestore db call the delete function on the CloudStorageService as well.

class HomeViewModel extends BaseModel {
  final CloudStorageService _cloudStorageService = locator<CloudStorageService>();

  Future deletePost(int index) async {
    var dialogResponse = await _dialogService.showConfirmationDialog(
      title: 'Are you sure?',
      description: 'Do you really want to delete the post?',
      confirmationTitle: 'Yes',
      cancelTitle: 'No',
    );

    if (dialogResponse.confirmed) {
      var postToDelete = _posts[index];
      setBusy(true);
      await _firestoreService.deletePost(postToDelete.documentId);
      // Delete the image after the post is deleted
      await _cloudStorageService.deleteImage(postToDelete.imageFileName);
      setBusy(false);
    }
  }

}

And That's it. Basic Cloud storage functionality wrapped into a service for easy use. Make sure to follow me on Youtube for the rest of the series. Until next week :)

Firebase Authentication in Flutter

Firebase Authentication in Flutter

Firebase Authentication in Flutter - Production Patterns. This tutorial will cover the implementation and architecture for Firebase Authentication. We use Firebase Authentication in production to keep my code maintainable and easy to manage. We cover the basic login and sign up functionality.

Today we'll be going over the production practices I follow when implementing email authentication using Firebase in Flutter. We'll be building a social media app called compound. It's called compound because that's the middle word of the book in front of me on my desk. "The Compound Effect". Even if you don't want to build a social media app, I'll be teaching you the principles you need to apply to a firebase project to build literally any app you want.

The Architecture

If you don't know, I use an Mvvm Style architecture with Provider for my UI / Business logic separation and get_it as a service locator. I've found this to be the most consistent and easy to understand architecture that I've used in production. It keeps implementations short and specific. In short the architecture specifies that each view or basic widget can have it's own ViewModel that contains the logic specific to that piece of UI. The ViewModel will make use of services to achieve what the user is requesting through their interactions.

Services is where all the actual work happens. ViewModels make use of the services but doesn't contain any hard functionality outside of conditionals and calling services. So, to get to the task at hand. We'll have an Authentication service that we'll use to sign in or sign up with that will store an instance of the current firebase user for us to use when required. We will have two views, Login and SignUp view which will make of the two functions on the service. The entire backend of the application will be built using Firebase so make sure to go to your console and login with a gmail account.

Setup Firebase Project

Open up the firebase console and click on "Add Project". Call it "compound", go next, select your account and then create. This will take a few seconds to setup. When it's complete click on continue and you'll land on the overview page.

Click on the Android Icon (or iOS) and add your package name, I'll set mine to com.filledstacks.compound. I'll set the nickname to "Compound". Register the app and then download the google-services.json file. If you have your own project or want to use my starting code, which you can download here, open up the code and place the google-service.json file in the android/app folder. Then open the build.gradle file in the android/app folder and change the applicationId to match the one you entered for your Firebase project.

Setup in code

Open up the pubspec.yaml and add the firebase_auth plugin.

firebase_auth: ^0.15.3

Then we have to enable the google services. Open the build.gradle file in the android folder and add the google services dependency.

    dependencies {
        // existing dependencies
        classpath 'com.android.tools.build:gradle:3.5.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // Add the google services classpath
        classpath 'com.google.gms:google-services:4.3.0'
    }

Open up the android/app/build.gradle file and apply the google services plugin. Add the following line at the bottom of the file.

// ADD THIS AT THE BOTTOM
apply plugin: 'com.google.gms.google-services'

That's it for the Android setup. Lets continue with the Firebase project. Once you've created the app you can go next and skip the firebase comms check that they do. On the left hand side, click on the Authentication Icon. The third icon from top (might change). Click on the Setup sign in methods button and click on email / password and enable it. That's it for the project setup, we'll get back to the Firebase console in the next episode.

Authentication Implementation

The starting code that I provided has a few things setup already.

  1. It contains the provider_architecture package which we use for the MvvmStyle bindings.
  2. It has an InputField widget which is styled how I want it.
  3. It has the locator for get_it setup like this
  4. It has a Navigation Service so we can navigate from the ViewModels and other services
  1. It has a Dialog Service for showing default dialogs
  1. It has the login view as well as the sign up view created and styled.

This is to make sure we keep the app to the point and only show the firebase parts. We'll be creating the Authentication service and then using it in the viewmodels, which are completely empty.

Authentication Service

The responsibility of the AuthenticationService in this case is to wrap the Firebase Authentication functionality for us. It will send the info we entered, and then tell us if it's successful or not. If it fails we return an error message to show the user. Under the services folder create a new file called authentication_service.dart.

import 'package:flutter/foundation.dart';

class AuthenticationService {
  Future loginWithEmail({@required String email, @required String password}) {
    // TODO: implement loginWithEmail
    return null;
  }

  Future signUpWithEmail({@required String email, @required String password}) {
    // TODO: implement signUpWithEmail
    return null;
  }
}

We'll start off keeping a reference to the FirebaseAuth instance locally. Then we'll perform signInWithEmailAndPassword and store the result in a variable called user. If there's no errors we'll check if the user is not null and return that value. If it fails we return the message from the error.

final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;

Future loginWithEmail({
    @required String email,
    @required String password,
}) async {
    try {
        var user = await _firebaseAuth.signInWithEmailAndPassword(
            email: email, password: password);
        return user != null;
    } catch (e) {
        return e.message;
    }
}

Sign up looks very similar. The only difference is that the result of the createUserWithEmailAndPassword function returns a FirebaseAuth object instead of the user like login.

Future signUpWithEmail({
    @required String email,
    @required String password,
}) async {
    try {
        var authResult = await _firebaseAuth.createUserWithEmailAndPassword(
            email: email, password: password);
        return authResult.user != null;
    } catch (e) {
        return e.message;
    }
}

That's it for the AuthenticationService. Open up the locator.dart file and register the service as a lazy singleton. All that means is that there will only ever be 1 authentication service in existence, and we'll lazily create it once it has been requested the first time.4

void setupLocator() {
  locator.registerLazySingleton(() => NavigationService());
  locator.registerLazySingleton(() => DialogService());
  locator.registerLazySingleton(() => AuthenticationService());
}
Signup Logic

We'll start with sign up so that we can then perform a login afterwards. Open up the main.dart file and make sure home is set to SignUpView. Then open up the signup_view_model.dart file. We'll start by retrieving the AuthenticationService, NavigationService and DialogService from the locator. Then we'll create a function called SignUp that takes the email and password. In this function we'll set the view to busy before requesting, do the sign up. Then check the result, if it's a bool and it's true then we navigate to the HomeView. If it's false we'll show a general dialog, if it's a string we'll show the content as a dialog.

class SignUpViewModel extends BaseModel {
  final AuthenticationService _authenticationService =
      locator<AuthenticationService>();
  final DialogService _dialogService = locator<DialogService>();
  final NavigationService _navigationService = locator<NavigationService>();

  Future signUp({@required String email, @required String password}) async {
    setBusy(true);

    var result = await _authenticationService.signUpWithEmail(
        email: email, password: password);

    setBusy(false);
    if (result is bool) {
      if (result) {
        _navigationService.navigateTo(HomeViewRoute);
      } else {
        await _dialogService.showDialog(
          title: 'Sign Up Failure',
          description: 'General sign up failure. Please try again later',
        );

      }
    } else {
      await _dialogService.showDialog(
        title: 'Sign Up Failure',
        description: result,
      );
    }
  }
}

Open up the SignUpView file. Update the BusyButton to take in the busy property from the model and in the onPressed function call model.signUp.

 BusyButton(
    title: 'Sign Up',
    busy: model.busy,
    onPressed: () {
        model.signUp(
        email: emailController.text,
        password: passwordController.text,
        );
    },
)

If you run the app now, enter some details and login you'll see it navigate to the HomeView. If you want to see the error dialog enter a password with less than 6 characters and you'll see the dialog pop up. Also if you've already signed up you can try signing up with the same email again and you'll get a friendly error message :)

Login Logic

The login logic logic is literally exactly the same as the sign up logic. Being able to refactor for shared code is a good skill to have, I'll leave it up to you as an exercise to do. For now we'll write non dry code by simple repeating the pattern. Open up the login_view_model.dart

class LoginViewModel extends BaseModel {
  final AuthenticationService _authenticationService =
      locator<AuthenticationService>();
  final DialogService _dialogService = locator<DialogService>();
  final NavigationService _navigationService = locator<NavigationService>();

  Future login({@required String email, @required String password}) async {
    setBusy(true);

    var result = await _authenticationService.loginWithEmail(
        email: email, password: password);

    setBusy(false);

    if (result is bool) {
      if (result) {
        _navigationService.navigateTo(HomeViewRoute);
      } else {
        await _dialogService.showDialog(
          title: 'Login Failure',
          description: 'Couldn\'t login at this moment. Please try again later',
        );
      }
    } else {
      await _dialogService.showDialog(
        title: 'Login Failure',
        description: result,
      );
    }
  }
}

Open the login view. Pass the busy value to the BusyButton and in the onPressed function call the login function.

 BusyButton(
    title: 'Login',
    busy: model.busy,
    onPressed: () {
        model.login(
            email: emailController.text,
            password: passwordController.text,
        );
    },
)

Open up the main.dart file and change home to LoginView. If you re-run the code now you'll land on the LoginView. Enter the details you entered, click login and you're done :) . This is just the start of the app, we'll add functionalities a normal app would have throughout the rest of the series. In the next tutorial we'll make sure once we're signed in we go straight to the HomeView. We'll also create a user profile, make sure it's always available when the app is open and add roles (for later use ;) ).

I decided to ask you guys to start sharing the tutorials more, I'm still seeing some unmaintainable code when new clients come to me. We have to spread the architecture and code quality love around and make that the core focus when building apps. Until next time, Dane Mackier.

Building an API With Firebase

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.

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.