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.
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
- 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",
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 || 5050app.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).
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
- Open http://firebase.google.com and
Go to console
. Add
a new project.- Give it a good name to your project as shown below and click
Continue
.
4. Opting for Google Analytics is totally upto you. You may prefer not to use and click continue
.
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.
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
.
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.
Setup Firestore database
- Goto Firestore Database
- Create Database
- Start in test mode
- Select Cloud Firestore location -> Enable
- Start collection of your choice and add your documents. Add fields of your choice.
Now, come back to the code and lets finish the project quickly.
Create a Rest API
- 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 };
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);
Run cmd: node index.js
and open http://localhost:5050/books. This is now an API or an endpoint ready for deployment.
Hope you like this Blog.