Skcript Technologies Private Limited

← All Articles

Building a RESTFul API with Firebase Cloud Functions for your Firebase App

— Written by

Building a RESTFul API with Firebase Cloud Functions for your Firebase App

How to build a RESTFul API for your Firebase app with Firebase Cloud Functions in under 30 minutes. Learn more.

Firebase is becoming one of the major backend for modern web, mobile apps and games, and the best part about it is that you can use the sdk for almost all the platforms. You can build mobile apps with its iOS and Android SDK also for games you can use the unity SDK and for web apps you can use the Javascript SDK.

But when we wanted to share or integrate with an external app or system we need a gateway since we can’t share the app credentials considering the security issues. Usual way of implementing this is the traditional RESTFul APIs. And yes, you can do that now for your Firebase as well with the help and power of cloud functions.

Triggers on cloud functions

Firebase cloud functions comes with multiple triggers which includes Database trigger, PubSub trigger, and HTTP trigger, Cloud Storage triggers, authentication trigger, Analytics trigger. For writing the RESTFul API we’ll be using HTTP triggers.

Get Started

First lets setup a basic function that just prints the current date as a JSON endpoint.

The http triggers works based on the popular JS web framework expressjs for handling the request and response. Here is a simple example code,

exports.date = functions.https.onRequest((req, res) => {
  const date = moment();
  res.status(200).json({ date: date });
});

Here the date is the function name and also the endpoint. Now deploy the function by running the following cli-command from the root of the application,

 firebase deploy --only functions --project <project-id>

To try this code use the following pattern and just replace the project id.

Accepting Parameters

Now let’s see how we can handle parameters in the request. You can send query parameters in the old traditional way and you can access it with object of request,

To access it use the following method,

let format = req.query.format;

So the final code looks like,

exports.date = functions.https.onRequest((req, res) => {
  let format = req.query.format;
  const date = moment().format(format);
  res.status(200).json({ date: date });
});

Building API for Actual Data

So now we’re pretty good with the work flow. Now let’s see how we can build it for actual data in the database. In order to get the data from the database we might need another library which is the or we can also use the javascript SDK but if you prefer to have full control over the data it’s better to go with firebase-admin SDK.

Initialize the app

We need to initialize the app with the config object to start using the SDK. Since we’re using the SDK inside firebase’s app environment we don’t need to setup the keys manually, we can use the following to get the config object and setup the app.

const admin = require("firebase-admin");
var firebase = admin.initializeApp(functions.config().firebase);

Now we can start using the variable to access the database and even cloud messaging service.

Create an endpoint for list of blog posts.

Now, we need to create an endpoint just like the way we did before, but now the data will be fetched from the realtime database and thrown back to the browser as a json object.

exports.posts = functions.https.onRequest((req, res) => {
  var postsRef = firebase.database().ref("posts");
  postsRef.once("value").then(function (snap) {
    res.status(200).json({ posts: snap.val() });
  });
});

As we notice here the data is been fetched from the firebase realtime database and even though the query is asynchronous in nature, here the function is always terminated with it acts like a normal synchronous query.

As designed this endpoint will throw out all the posts inside the node as a JSON object. If you wish to cleanout and remove some unwanted node you can do a filtering before you render the JSON.

An endpoint of each post

Now let’s try to implement single post endpoint where you pass the key of the node as a query parameter and it will fetch corresponding node and render the JSON object. We can use the query parameter concept we saw earlier.

exports.post = functions.https.onRequest((req, res) => {
  let key = req.query.key;
  var postRef = firebase.database().ref("designs").child(key);
  postRef.once("value").then(function (snap) {
    res.status(200).json({ post: snap.val() });
  });
});

Now this function takes the id as the parameter like the below end point.

Taking it forward with more methods.

Here we saw how to build RESTFul end point for your Firebase application for getting the data. In the next article I’ll explain how to create end points for posting and deleting data from you firebase application.

Use Case

We’re using this to create endpoints for integration of third party apps to use our application. You can do a lot of things like creating an endpoint to stream videos and music from your firebase storage.

If you’re looking for a FCM implementation with cloud functions look at our previous article.


Read More Articles on Firebase:

Up next

Things you should do right after you signup for a AWS Account
Skcript /svr/creating-restful-api-firebase/ /svrmedia/heroes/firebase_restful_api.png
Skcript Technologies Private Limited

Book a free consultation

Book a time with our consultants to discuss your project and get a free quote. No strings attached.