Home > Mobile >  Node js RESTFUL API with Firebase as database
Node js RESTFUL API with Firebase as database

Time:12-17

We have a graduation project and we decided make an app with flutter.We thought we can use firebase authentication and database storage for data that come from node js api but I could not find any example of it. I saw flutter apps with MongoDB/Node and Express js api. Is that possible to make an app with using firebase and API has been made by node js? If you know a source for learning of it please share it I'll be grateful Thank you.

CodePudding user response:

You can start with installing firebase to your project

npm install firebase

Here is an example of code provided by Google

// Get a database reference to our posts
 const db = getDatabase();
 const ref = db.ref('server/saving-data/fireblog/posts');

 // Attach an asynchronous callback to read the data at our posts reference
 ref.on('value', (snapshot) => {
    console.log(snapshot.val());
 }, (errorObject) => {
     console.log('The read failed: '   errorObject.name);
 }); 

I made it in one of my projects so recommend you read the docs

https://firebase.google.com/docs/web/setup

Update

So you need to set up your firebase project Follow instruction here https://firebase.google.com/docs/database/web/start

Now second thing is how to add firebase to you node.js express project

const { initializeApp } = require("firebase/app");
const { getDatabase, ref, set, onValue } = require("firebase/database");


// Set the configuration for your app
// TODO: Replace with your project's config object
const firebaseConfig = {
    apiKey: process.env.YOUR_VALUE_FROM_DOT_ENV_FILE,
    authDomain: process.env.YOUR_VALUE_FROM_DOT_ENV_FILE,
    databaseURL: process.env.YOUR_VALUE_FROM_DOT_ENV_FILE,
    projectId: process.env.YOUR_VALUE_FROM_DOT_ENV_FILE,
    storageBucket: process.env.YOUR_VALUE_FROM_DOT_ENV_FILE,
    messagingSenderId: process.env.YOUR_VALUE_FROM_DOT_ENV_FILE,
    appId: process.env.YOUR_VALUE_FROM_DOT_ENV_FILE

};
const firebase = initializeApp(firebaseConfig);

// Get a reference to the database service
const database = getDatabase(firebase);

All this things you will get from firebase account

Now Express section here is part of example

app.post('/items', (req, res) => {
   const postData = req.body;
   const db = getDatabase();
   const ephemeralId = Date.now().toString();
   set(ref(db, 'items/'   ephemeralId), postData).then(_r => {
       res.status(201).send({
           success: true,
           insertedId: ephemeralId,
       });
    }).catch(err => {
       res.status(420).send(err);
    });

   });

And as I promised here is full code on git https://github.com/labadze/node-express-firebase-database-api/tree/master

  • Related