firebase

Firebase Simple Rest API

 

Rest API is a crucial function that is essential to all types of database. Firebase Real-time database is one of those. Today, I will show you how to make a simple CRUD with Firebase Real-time database.

Before getting into some detail, to do read and write with Firebase Real-time database you need to have some config and authority in your Firebase Real-time database account. To do so, please follow this step:

First: Go into your real-time database on your Firebase:

 

Next: Choose rules and set up your own rules, if you dont know what rules are so technically rules are set to select who are able to read and write in your database or for more transparently it is your database security and assessment.

Note: if you are using this for testing just set everything read and write true, so everyone can access your database easier.

Get a database reference

To read or write data from the database:

import { getDatabase } from "firebase/database";

const database = getDatabase();

Rest Api function:

1/ Firebase – Create method:

The first and very important method are create or add data to the database. For basic write operations, you can use set() to save data to a specified reference, replacing any existing data at that path. For example a social blogging application might add a user with set() as follows:

import { getDatabase, ref, set } from "firebase/database";

function writeUserData(userId, name, email,birth) {
  const db = getDatabase();
  set(ref(db, 'your path' + yourid), {
    username: name,
    email: email,
    birthday:birth
  });
}

Using set() overwrites data at the specified location, including any child nodes.

2/ Firebase – Update method:

When calling update(), you can update lower-level child values by specifying a path for the key. The method not only helps to add new lower-level child data but also works as update and edit method.

For example, a mobile app might create a post and simultaneously update it to the recent activity feed and the posting user’s activity feed using code like this:

import { getDatabase, ref, child, push, update } from "firebase/database";

function updateNew(uid, username, body) {
  const db = getDatabase();


  const postData = {
    author: username,
    uid: uid,
    body: body,

  };


  const newPostKey = push(child(ref(db), 'posts')).key;


  const updates = {};
  updates['/posts/' + newPostKey] = postData;
  updates['/user-posts/' + uid + '/' + newPostKey] = postData;

  return update(ref(db), updates);
}

This example uses push() to create a post in the node containing posts for all users at /posts/$postid and simultaneously retrieve the key. The key can then be used to create a second entry in the user’s posts at /user-posts/$userid/$postid.

Using these paths, you can perform simultaneous updates to multiple locations in the JSON tree with a single call to update(), such as how this example creates the new post in both locations. Simultaneous updates made this way are atomic: either all updates succeed or all updates fail.

3/ Get method

To access your database through the specific paths and show up in JSON type use GET method.

If you need the data only once, you can use get() to get a snapshot of the data from the database. If for any reason get() is unable to return the server value, the client will probe the local storage cache and return an error if the value is still not found.

import { getDatabase, ref, child, get } from "firebase/database";

const dbRef = ref(getDatabase());
get(child(dbRef, `users/${userId}`)).then((snapshot) => {
  if (snapshot.exists()) {
    console.log(snapshot.val());
  } else {
    console.log("No data available");
  }
}).catch((error) => {
  console.error(error);
});

4/ Delete method

The simplest way to delete data is to call remove() on a reference to the location of that data.

You can also delete by specifying null as the value for another write operation such as set() or update(). You can use this technique with update() to delete multiple children in a single API call.

Note:

To know when your data is committed to the Firebase Realtime Database server, you can use a promise. Both set() and update() can return a Promise you can use to know when the write is committed to the database.

Leave a Comment