Back

Step by Step Guide to Building a Firestore API Integration in Python

Aug 9, 20244 minute read

Introduction

Hey there, fellow Python enthusiast! Ready to dive into the world of Firestore? You're in for a treat. Firestore is Google's flexible, scalable NoSQL cloud database, and today we're going to walk through integrating it into your Python project. Buckle up!

Prerequisites

Before we jump in, make sure you've got:

  • Python 3.x installed
  • A Google Cloud project with Firestore enabled
  • The google-cloud-firestore library (pip install google-cloud-firestore)

Got all that? Great! Let's roll.

Authentication

First things first, we need to get you authenticated. Head over to your Google Cloud Console, create a service account, and download the JSON key file. Easy peasy.

Now, set an environment variable to point to your key file:

export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/keyfile.json"

Initializing Firestore Client

Time to get our hands dirty with some code:

from google.cloud import firestore db = firestore.Client()

Boom! You're connected. How's that for simple?

Basic CRUD Operations

Creating Documents

Let's add some data:

doc_ref = db.collection('users').document('alovelace') doc_ref.set({ 'first': 'Ada', 'last': 'Lovelace', 'born': 1815 })

Reading Documents

Reading is just as easy:

doc = doc_ref.get() print(f'Document data: {doc.to_dict()}')

Updating Documents

Need to make changes? No sweat:

doc_ref.update({'born': 1816})

Deleting Documents

And when it's time to say goodbye:

doc_ref.delete()

Advanced Querying

Let's step it up a notch:

users_ref = db.collection('users') # Get all users born before 1900 docs = users_ref.where('born', '<', 1900).stream() for doc in docs: print(f'{doc.id} => {doc.to_dict()}')

Working with Collections

Subcollections? We've got you covered:

doc_ref = db.collection('rooms').document('roomA') message_ref = doc_ref.collection('messages').document('message1') message_ref.set({'text': 'Hello, World!'})

Handling Real-time Updates

Want to keep things fresh? Try this on for size:

def on_snapshot(doc_snapshot, changes, read_time): for doc in doc_snapshot: print(f'Received document snapshot: {doc.id}') doc_ref = db.collection('cities').document('SF') doc_watch = doc_ref.on_snapshot(on_snapshot)

Error Handling and Best Practices

Remember, always wrap your Firestore calls in try-except blocks. And for the love of all things Pythonic, use batch writes for multiple operations!

batch = db.batch() # ... add your operations to the batch batch.commit()

Conclusion

And there you have it! You're now armed and dangerous with Firestore knowledge. Go forth and build amazing things!

Remember, the official Firestore documentation is your best friend for diving deeper. Happy coding!