REST API with Node JS and Firebase

Creating REST API to fetch json data from firestore database through node js endpoint. This blog is completely for beginners who wants to create REST API with firestore.

Deep Patel
5 min readOct 30, 2021
Made on canva.com by author, link.

Hello everyone! In this blog we will see how we can create REST API in Nodejs and connect our app with Firebase. Node.js is becoming one of the most important tools to have in today’s software world. If you haven’t installed, then refer to this documentation.

Project Setup

  1. Create a directory and initialise node project in that directory with command npm init. Here, I have create a directory name demo and I initialised the project. Change the package name, description and other details as per your requirements.

2. Now, we need to install the express package to our project and to do that we will use the following npm command npm install — save express. Further, to connect firebase we need to add firebase modules.

npm install --save express
npm install firebase
npm install firebase-admin

3. Inside pakage.json file, add the following code under scripts.

"start": "node index.js",
Scripts should look like this.

4. Create file index.js and add the following code. In order to create our first REST resource, we will use the express package. Our index.js file should look like this.

var express = require('express');
var app = express();
const PORT = process.env.PORT || 5050
app.get('/', (req, res) => {
res.send('This is my demo project')
})
app.listen(PORT, function () {
console.log(`Demo project at: ${PORT}!`); });

Run project via command node index.js. Now, to see the live demo of your project, open web browser and type http://localhost:5050/ (you may have different port number).

You will get this output.

5. Now, in the project directory make a new folder util and add two files: firebase.js and admin.js. (Note: Making a separate folder for your firebase configuration files is a good practice.)

In your firebase.js import firebase by adding following line.

const firebase = require('firebase');

Firebase Setup

  1. Open http://firebase.google.com and Go to console.
  2. Add a new project.
  3. Give it a good name to your project as shown below and click Continue.
Starting step of firebase project.

4. Opting for Google Analytics is totally upto you. You may prefer not to use and click continue.

Once you click continue, your project will be ready and you will be forwarded to the dashboard.

It might take few minutes to create your project, so have a cup of coffee. Once it is ready, click continue to open your dashboard.

5. Select Web to add your web app.

We will add our web app to firebase project.

6. Give a suitable nick name to your app and click Register app.

7. Now, copy the configuration (see the below image) in your firebase.js file. After that, click continue to console.

Check if you got similar screen.

8. Go to your Project settings -> Service accounts and select Node.js. Copy the configuration code snippet in admin.js file. Generate new private key and add the json file in the project directory.

Check that you have similar settings and options selected.

Setup Firestore database

  1. Goto Firestore Database
  2. Create Database
  3. Start in test mode
  4. Select Cloud Firestore location -> Enable
  5. Start collection of your choice and add your documents. Add fields of your choice.
Sample of my database.

Now, come back to the code and lets finish the project quickly.

Create a Rest API

  1. Complete your firebase.js file. Add below code at the end of the file.
firebase.initializeApp(firebaseConfig); //initialize firebase app 
module.exports = { firebase }; //export the app

2. Completion of admin.js file. Update the path of the json file and add the below code.

const db = admin.firestore();
module.exports = { admin, db };
Final admin.js should look like this.

3. Now create your model. Create a new file books.js and add the following code. Here, I created sepearate folder handlers for all models. Add below code to fetch data from your firestore database.

  • db.collection(‘Collection Name’) creates the collection from the name provided (‘Books’ in the above example)

Change name of Books to name of your collection name in below code. Here, we are creating a get request to fetch the data. Refer the doc for detailed information.

const { db } = require("../util/admin");
exports.books = async (req, res) => {
const booksRef = db.collection('Books');
try{
booksRef.get().then((snapshot) => {
const data = snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));
console.log(data);
return res.status(201).json(data);
})
} catch (error) {
return res
.status(500)
.json({ general: "Something went wrong, please try again"});
}
};

4. Update index.js to the below code.

const { books } = require('./handlers/books')app.get('/books', books);
Final index.js should look like this.

Run cmd: node index.js and open http://localhost:5050/books. This is now an API or an endpoint ready for deployment.

JSON output of our firestore database.

Hope you like this Blog.

--

--

Deep Patel
Deep Patel

Written by Deep Patel

Hi everyone, I am a software engineer at American Express. I am here to share my experience in tech.

Responses (3)