Firebase is Google's platform that offers different type of services for Web and Mobile application developers to create and deploy application easily using its database, authentication and other services for monitoring apps. We can easily integrate these services in our application to get started easily for a Mobile or Web application. In this post, we will be using Firestore Database to store and retrive data easily using python.
To use Firestore in python, we can use python a package firebase-admin
to connect with firestore and perform different operations on firestore sdk. For getting started, you need service account credentials from Google Cloud and install python package using cmd/terminal.
pip install firebase-admin
For credentials, you can create a service account get credentials json file which will be used later for connecting with firestore. For more details visit.
https://firebase.google.com/docs/firestore/quickstart
After, we have setup everything, we can start adding data. First we import required modules and initialize database.
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
# Use the application default credentials
cred = credentials.ApplicationDefault()
firebase_admin.initialize_app(cred, {
'projectId': "PROJECT_ID",
})
# initialize db
db = firestore.client()
Add Data to Firestore
We can add data to firestore by creating a document and set our data dictionary to that document. Firestore can save all major data formats such as string
, numbers
, boolean
, arrays
, objects
, datetime
etc. Lets first create a document and add data to that document.
To set a document, we first need to define, which collection we want to use for that document. So, we first define collection by db.collection()
and after that we can create a document. If we define an Id for document, it will be created using that id, otherwise it will automatically generate a new id.
doc = db.collection("users").document()
# Get doc id
doc.id
Or, if you want to use custom id
doc = db.collection("users").document("mydoc")
# Or you can use random id generator
from uuid import uuid4
doc = db.collection("users").document(str(uuid4())
Now we can use set()
fucntion to add data to specific document.
doc.set({
"name" : "Faizan", # string
"age" : 24, #number
"hobbies" : ["coding", "gaming", "reading"], #array
"portal" : {"url" : "https://faizanamin.web.app"}, # object
"active" : True # boolean
})
And we can see that this document is created in users collection. Now if we want to read documents from a collection, there are different ways, lets check them.
Read Data
To read a document or multiple documents from firestore collection we can use conditional statements using where. Alternatively, if you just want to fetch single document using document id, it is easy to fetch.
# Get single document by id
doc_id = "YOUR_DOCUMENT_ID"
doc = db.collection("users").document(doc_id).get()
# View document data
print("Document Id", doc.id) # Get document id
print("Get single field", doc.get("name")) # Get single value by key
print("Document to Dictionary", doc.to_dict()) # Get all document data as dictionary
If we want to query data based on values in document, we can use where
to query for a single column. We can use multiple conditions like ==
, !=
, <
, >
, in
and some other conditional statements.
# compare string
users = db.collection("users").where("name", "==", "Faizan").get() # returns a list
# compare number
users = db.collection("users").where("age", ">", 20).get()
# Compare boolean
users = db.collection("users").where("active", "==", True).get()
# Print all users
for user in users:
print(user.id, user.to_dict())
Update Data
We can update values in document, if key already exists in document, it will be updated otherwise new key will be added.
db.collection("users").document(document_id).update({
"name" : "Faizan Amin",
"country" : "Pakistan"
})
For complete document on firebase admin to use cloud firestore, you can view official documentation on Google Cloud.
Comments (0)