Introduction
Backend as a Service (BaaS) has been a huge success in recent times and Firebase is one such popular BaaS offered by Google. It can essentially act as the complete backend solution for modern web and mobile applications. It provides a lot of services including Authentication, Firestore, Cloud Storage, Realtime Database, Hosting, Cloud Functions, Cloud messaging, and Machine Learning. All services have the capability to scale automatically as per network traffic. Google Firestore is a cloud-hosted NoSQL database available in Google Firebase that can be connected directly to web applications and mobile applications using native SDKs. It is one of the best cloud-based production-ready NoSQL databases available in the market and is extremely popular among developers as it simplifies a variety of things. When I say that Google Firestore is cloud-based, it internally uses Google Cloud to host, manage and scale the database. In this article, we will learn how to connect and perform basic CRUD operations on Google Firestore using the python programming language.
Setting up Google Firestore
It is mandatory to create a Firebase project in order to access Firestore. You can create Firebase projects for free using your Google account. You can access Google Firebase here. Let’s go ahead and create a new Firebase project. Open Firebase in your browser (click here) and log in using your Google account and then, click on “Create a new project“, which will ask for a project name. You can give your firebase project any name, while I named it “firestore-basics-python“. Click on “Firestore database“, which you can find in the left navigation bar as shown in the picture.
Once you click the create database button, you will be prompted to choose either production mode or testing mode. Choose test mode and proceed.
You will be prompted to choose a location for the database. Choose the closest region to your current location to reduce latency and click enable.
Connecting Python to Google Firestore
To connect to Google Firestore, we will need to install a python package called “firebase-admin“. This can be installed like any other python package using pip. Ensure that your python version is 3.6 or below as this module throws an exception because of the async module added in python 3.7 onwards. If you have a higher version installed, you can use anaconda to create a new environment with python 3.6. I am using python 3.6.5 for this article.
pip install firebase-admin
To connect to Firestore, Firebase first performs authentication. To get the credentials for authentication, click on project settings, and click on “service accounts“.
In the “Service accounts” tab, you can find a code snippet for connecting to Google Firebase. Select python as the language and copy the code snippet. After copying the code snippet, click on “manage service account permissions“.
Now click on “manage keys” and then click on the “add key” button and select “create new key“, and choose JSON as the file format and click create.
Now that we have the credentials, let’s connect to Firestore. To do so, paste the code snippet that you just copied and add the file path of the credentials file that got downloaded.
db = firestore.client() # connecting to firestore
Congrats, we have now successfully connected to Firebase and can access the Firestore service. Let’s get our hands dirty and perform some basic CRUD operations on Firestore.
Performing CRUD operations on Google Firestore
Google Firestore is a document-based NoSQL database and so it uses collections and documents to represent tables and records. Let us now try to create a collection called “programmer_details” and insert a document with details of a programmer including name, age, country, and programming languages known. It is necessary to make sure that each document is named uniquely to prevent overwriting of documents and losing data. If you are familiar with MongoDB or other popular document-based NoSQL databases, you can relate the name of the database with the “_id” field present in MongoDB documents that uniquely identifies them in a collection.
collection = db.collection('programmer_details') # create collection res = collection.document('A01').set({ # insert document 'name': 'Vishnu', 'age': 19, 'Country': 'India', 'Programming_languages': ['Python', 'C#', 'C++'] }) print(res)
Let’s see if the data is stored in Google Firestore or not.
We can see that a new collection has been created and a document has also been inserted.
Now let’s try to fetch the details of the document we just inserted. It is important that we convert the object to a dictionary so that it can be handled properly. For doing so, we can directly call the “to_dict()” function, which returns the document as a dictionary.
res = collection.document('A01').get().to_dict() print(res)
{'Programming_languages': ['Python', 'C#', 'C++'], 'name': 'Vishnu', 'age': 19, 'Country': 'India'}
To get all the documents present inside a collection, we can directly call the get function on a collection but it returns a list of objects and each object needs to be converted to a dictionary using the “to_dict()” function for further processing.
res = collection.get() # returns a list for i in res: print(i.to_dict())
Now let’s try to update a document inside a collection. Let’s add a new key-value pair and also modify the value of a key that is already present in the document. For doing so, we can directly make use of the “update()” function.
res = collection.document('A01').update({ 'State': 'Chennai', 'age': 21 }) print(res)
Let’s see if the document has been updated in Firestore or not. We can see that two new fields – state and age have been added to the document.
Let’s now try to delete a document inside a collection. For this, we can directly call the “delete()” function associated with the document.
res = collection.document('A01').delete() print(res)
Conclusion
In this article, we got to learn about Google Firestore, a NoSQL database offering on the Google Firebase platform, and how we can perform basic CRUD operations using the python programming language. Along with this, we also learned how to create and set up a project in Google Firebase.
As mentioned earlier, Google Firebase offers a lot of services for free and one such service is the Google Firestore. These services are hosted on Google Cloud and are production-ready and have the autoscale feature enabled by default, which is a big advantage as we, the developers, do not have to spend a huge amount of time setting up these services to scale on demand. This saves a lot of time and allows developers to focus more on developing features and functionalities rather than worrying about setting them up on the cloud. I will cover the Google Cloud Storage service offered by Firebase in my next article. I will also try to cover other services offered by Google Firebase in the coming weeks, so stay tuned!