Firebase is a mobile platform that can be used to quickly develop high-quality apps and manage its analytics. It is acquired by Google in 2014. It provides a lot of features to developers some of these are the following:
- Using Cloud Firestore and Cloud Storage we can Sync our data with our app.
- Firebase auth for user authentication
- Firebase hosting for deploying our web app
- Send notifications using Firebase Cloud Messaging.
- Manage the web app's performance data using Firebase Analytics
- And many more…
In this article, we'll find how we can use a server-side option to read and write data in Cloud Firestore outside the client using Firebase Admin SDK. For this tutorial, we'll be using Python.
Let's start by creating our first project. Firebase is now acquired by Google so by using our Google account we can sign in into Firebase.
Now in the Firebase console, we need to click
Add Project
, and then name your Firebase project. Remember the project ID for your Firebase project. After creating your first project, you can see a screen like this. Now we have to get the service account credentials. For that, we need to click on the settings icon nearProject Overview
and click onProject Settings
. Now go to theService Accounts
tab and click onGenerate new private key
to download the service credentials JSON file. Now install the Firebase Admin SDK using the following command:sudo pip install firebase-admin
Let's get started with coding. First, we have to import the libraries and initialize the SDK using our downloaded service account credentials. https://gist.github.com/0ca6ddc245556e27fe9747e37fa63ef8
Now we have to initialize the firestore instance.
firestore_db = firestore.client()
Now in the Firebase portal, go to the Database
section and click Create Database
to create a new database.
It will open up a window like this after creating the database.
Now we need to create a collection to store our data. For that, we need to click on Start Collection
and give a collection name. In the next step, we need to create our first document. We can create a field and its value in it. We can also select the datatype of the field. Firestore supports string, number, boolean, map, array, null, timestamp, geopoint, and reference.
Let's start adding documents through our python code. For that we'll use .add()
of firestore.
firestore_db.collection(u'songs').add({'song': 'Imagine', 'artist': 'John Lennon'})
It will create a new document in the DB like this:
Now let's read the documents from our collection. For that, we'll use .get()
method.
https://gist.github.com/2928c1f92a6f66f6eb589015588614f9
Following is the complete code for this tutorial. https://gist.github.com/cd9e665aff32e02eece5f05a4a1778ec
That's all for now. In this blog, we learned the basics of Firebase firestore. It is very easy to use. You should give it a try on your next project. Till then happy coding :)