0
# Realtime Database
1
2
Firebase Realtime Database operations for JSON tree-structured data including reading, writing, querying, transactions, and real-time listeners. Provides synchronization capabilities for collaborative applications.
3
4
## Capabilities
5
6
### Database References
7
8
Get database references for reading and writing data at specific paths in the JSON tree structure.
9
10
```python { .api }
11
def reference(path='/', app=None, url=None):
12
"""
13
Return a database reference for the specified path.
14
15
Args:
16
path: Database path string (default: '/')
17
app: Firebase app instance (optional)
18
url: Database URL override (optional)
19
20
Returns:
21
Reference: Database reference instance for the specified path
22
"""
23
```
24
25
### Data Operations
26
27
Read and write operations for JSON data with support for ETags for optimistic concurrency control.
28
29
```python { .api }
30
class Reference:
31
"""Reference to a location in the Realtime Database."""
32
33
def get(self, etag=False, shallow=False):
34
"""
35
Get data at this reference location.
36
37
Args:
38
etag: Whether to return ETag for optimistic locking (optional)
39
shallow: Whether to return only immediate children keys (optional)
40
41
Returns:
42
Data at this location, or tuple of (data, etag) if etag=True
43
"""
44
45
def get_if_changed(self, etag):
46
"""
47
Get data only if it has changed from the provided ETag.
48
49
Args:
50
etag: ETag string from previous get operation
51
52
Returns:
53
tuple: (changed, data, new_etag) where changed is boolean
54
"""
55
56
def set(self, value):
57
"""
58
Set data at this reference location.
59
60
Args:
61
value: JSON-serializable data to set
62
"""
63
64
def set_if_unchanged(self, expected_etag, value):
65
"""
66
Set data only if ETag matches (optimistic locking).
67
68
Args:
69
expected_etag: Expected ETag string
70
value: JSON-serializable data to set
71
72
Returns:
73
tuple: (success, data, etag) where success indicates if set occurred
74
"""
75
76
def update(self, value):
77
"""
78
Update specific fields at this reference location.
79
80
Args:
81
value: Dict of field updates to apply
82
"""
83
84
def push(self, value=''):
85
"""
86
Push data to this reference, generating a unique child key.
87
88
Args:
89
value: JSON-serializable data to push (optional)
90
91
Returns:
92
Reference: Reference to the newly created child
93
"""
94
95
def delete(self):
96
"""Delete data at this reference location."""
97
```
98
99
### Navigation and Properties
100
101
Navigate the database tree structure and access reference metadata.
102
103
```python { .api }
104
class Reference:
105
"""Reference to a location in the Realtime Database."""
106
107
@property
108
def key(self):
109
"""The key name of this reference (last segment of path)."""
110
111
@property
112
def path(self):
113
"""The full path of this reference."""
114
115
@property
116
def parent(self):
117
"""Reference to the parent location, or None if root."""
118
119
def child(self, path):
120
"""
121
Get a reference to a child location.
122
123
Args:
124
path: Child path string (can contain multiple segments)
125
126
Returns:
127
Reference: Reference to the child location
128
"""
129
```
130
131
### Query Operations
132
133
Query and order data with filtering, pagination, and sorting capabilities.
134
135
```python { .api }
136
class Reference:
137
"""Reference to a location in the Realtime Database."""
138
139
def order_by_child(self, path):
140
"""
141
Order results by a child key.
142
143
Args:
144
path: Child key path to order by
145
146
Returns:
147
Query: Query instance for further filtering
148
"""
149
150
def order_by_key(self):
151
"""
152
Order results by child keys.
153
154
Returns:
155
Query: Query instance for further filtering
156
"""
157
158
def order_by_value(self):
159
"""
160
Order results by child values.
161
162
Returns:
163
Query: Query instance for further filtering
164
"""
165
166
class Query:
167
"""Query for filtering and ordering database results."""
168
169
def limit_to_first(self, limit):
170
"""
171
Limit results to the first N items.
172
173
Args:
174
limit: Maximum number of items to return
175
176
Returns:
177
Query: Query with limit applied
178
"""
179
180
def limit_to_last(self, limit):
181
"""
182
Limit results to the last N items.
183
184
Args:
185
limit: Maximum number of items to return
186
187
Returns:
188
Query: Query with limit applied
189
"""
190
191
def start_at(self, start):
192
"""
193
Set the starting point for results.
194
195
Args:
196
start: Starting value for the query
197
198
Returns:
199
Query: Query with start constraint
200
"""
201
202
def end_at(self, end):
203
"""
204
Set the ending point for results.
205
206
Args:
207
end: Ending value for the query
208
209
Returns:
210
Query: Query with end constraint
211
"""
212
213
def equal_to(self, value):
214
"""
215
Filter results equal to the specified value.
216
217
Args:
218
value: Value to match
219
220
Returns:
221
Query: Query with equality filter
222
"""
223
224
def get(self):
225
"""
226
Execute the query and get results.
227
228
Returns:
229
Ordered results based on query parameters
230
"""
231
```
232
233
### Real-time Listeners
234
235
Subscribe to data changes for real-time synchronization and collaborative features.
236
237
```python { .api }
238
class Reference:
239
"""Reference to a location in the Realtime Database."""
240
241
def listen(self, callback):
242
"""
243
Start listening for data changes at this reference.
244
245
Args:
246
callback: Function called when data changes, receives Event instance
247
248
Returns:
249
ListenerRegistration: Registration object for managing the listener
250
"""
251
252
class ListenerRegistration:
253
"""Registration for a real-time database listener."""
254
255
def close(self):
256
"""Stop listening for changes and clean up resources."""
257
258
class Event:
259
"""Event object passed to listener callbacks."""
260
261
@property
262
def data(self):
263
"""The data at the reference location."""
264
265
@property
266
def path(self):
267
"""The path where the change occurred."""
268
269
@property
270
def event_type(self):
271
"""The type of change that occurred."""
272
```
273
274
### Transactions
275
276
Execute atomic operations on database data with automatic retry on conflicts.
277
278
```python { .api }
279
class Reference:
280
"""Reference to a location in the Realtime Database."""
281
282
def transaction(self, transaction_update):
283
"""
284
Execute a transaction at this reference location.
285
286
Args:
287
transaction_update: Function that takes current data and returns new data
288
289
Returns:
290
The new value after the transaction completes
291
292
Raises:
293
TransactionAbortedError: If the transaction fails after retries
294
"""
295
296
class TransactionAbortedError:
297
"""Exception raised when a transaction is aborted."""
298
```
299
300
## Usage Examples
301
302
### Basic Data Operations
303
304
```python
305
from firebase_admin import db
306
307
# Get root reference
308
ref = db.reference()
309
310
# Set data
311
ref.child('users/user123').set({
312
'name': 'John Doe',
313
'email': 'john@example.com',
314
'profile': {
315
'age': 30,
316
'city': 'San Francisco'
317
}
318
})
319
320
# Get data
321
user_data = ref.child('users/user123').get()
322
print(f'User data: {user_data}')
323
324
# Update specific fields
325
ref.child('users/user123').update({
326
'profile/age': 31,
327
'lastLogin': datetime.datetime.now().isoformat()
328
})
329
330
# Push data (auto-generated key)
331
messages_ref = ref.child('messages')
332
new_message_ref = messages_ref.push({
333
'text': 'Hello, world!',
334
'timestamp': datetime.datetime.now().isoformat()
335
})
336
print(f'New message key: {new_message_ref.key}')
337
```
338
339
### Querying Data
340
341
```python
342
# Order and limit
343
users_ref = ref.child('users')
344
query = users_ref.order_by_child('profile/age').limit_to_first(10)
345
young_users = query.get()
346
347
# Range queries
348
adult_users = (users_ref
349
.order_by_child('profile/age')
350
.start_at(18)
351
.end_at(65)
352
.get())
353
354
# Key-based ordering
355
recent_messages = (ref.child('messages')
356
.order_by_key()
357
.limit_to_last(20)
358
.get())
359
```
360
361
### Real-time Listeners
362
363
```python
364
def on_user_change(event):
365
print(f'User data changed at {event.path}: {event.data}')
366
367
# Listen to specific user
368
user_ref = ref.child('users/user123')
369
listener = user_ref.listen(on_user_change)
370
371
# Listen to all users
372
def on_users_change(event):
373
print(f'Users collection changed: {event.event_type}')
374
375
users_listener = ref.child('users').listen(on_users_change)
376
377
# Stop listening
378
listener.close()
379
users_listener.close()
380
```
381
382
### Transactions
383
384
```python
385
def increment_counter(current_value):
386
if current_value is None:
387
return 1
388
return current_value + 1
389
390
# Atomic increment
391
counter_ref = ref.child('counters/page_views')
392
new_count = counter_ref.transaction(increment_counter)
393
print(f'New count: {new_count}')
394
395
# Complex transaction
396
def transfer_funds(current_balances):
397
if current_balances is None:
398
return None
399
400
from_balance = current_balances.get('from', 0)
401
to_balance = current_balances.get('to', 0)
402
amount = 100
403
404
if from_balance < amount:
405
return None # Abort transaction
406
407
return {
408
'from': from_balance - amount,
409
'to': to_balance + amount
410
}
411
412
balances_ref = ref.child('balances')
413
try:
414
result = balances_ref.transaction(transfer_funds)
415
print(f'Transfer successful: {result}')
416
except db.TransactionAbortedError:
417
print('Transfer failed: insufficient funds')
418
```
419
420
### Optimistic Locking with ETags
421
422
```python
423
# Get data with ETag
424
data, etag = ref.child('settings').get(etag=True)
425
426
# Modify data
427
data['last_updated'] = datetime.datetime.now().isoformat()
428
429
# Set only if unchanged
430
try:
431
success, new_data, new_etag = ref.child('settings').set_if_unchanged(etag, data)
432
if success:
433
print('Settings updated successfully')
434
else:
435
print('Settings were modified by another process')
436
except Exception as e:
437
print(f'Update failed: {e}')
438
```
439
440
### Database URL Configuration
441
442
```python
443
# Use specific database URL
444
custom_ref = db.reference('/', url='https://my-other-project-default-rtdb.firebaseio.com/')
445
446
# Or configure in app initialization
447
import firebase_admin
448
from firebase_admin import credentials
449
450
cred = credentials.Certificate('serviceAccountKey.json')
451
app = firebase_admin.initialize_app(cred, {
452
'databaseURL': 'https://my-project-default-rtdb.firebaseio.com/'
453
})
454
455
# Then use default reference
456
ref = db.reference()
457
```
458
459
## Security and Performance
460
461
### Security Rules
462
463
Realtime Database security is managed through security rules defined in the Firebase Console:
464
465
```javascript
466
// Example security rules (defined in Firebase Console)
467
{
468
"rules": {
469
"users": {
470
"$uid": {
471
".read": "$uid === auth.uid",
472
".write": "$uid === auth.uid"
473
}
474
},
475
"public": {
476
".read": true,
477
".write": false
478
}
479
}
480
}
481
```
482
483
### Performance Tips
484
485
- **Denormalize data**: Structure data to minimize reads
486
- **Use shallow queries**: Get only keys when possible
487
- **Limit listener scope**: Listen to specific paths, not large trees
488
- **Index data properly**: Structure keys for efficient queries
489
- **Use transactions for atomic operations**: Ensure data consistency
490
- **Close listeners**: Always clean up real-time listeners when done
491
492
## Types
493
494
```python { .api }
495
class Reference:
496
"""Reference to a location in the Realtime Database."""
497
498
@property
499
def key(self):
500
"""The key name of this reference."""
501
502
@property
503
def path(self):
504
"""The full path of this reference."""
505
506
@property
507
def parent(self):
508
"""Reference to the parent location."""
509
510
class Query:
511
"""Query for filtering and ordering database results."""
512
513
class Event:
514
"""Event object for real-time listeners."""
515
516
@property
517
def data(self):
518
"""The data at the reference location."""
519
520
@property
521
def path(self):
522
"""The path where the change occurred."""
523
524
@property
525
def event_type(self):
526
"""The type of change that occurred."""
527
528
class ListenerRegistration:
529
"""Registration for a real-time database listener."""
530
531
class TransactionAbortedError(Exception):
532
"""Exception raised when a transaction is aborted."""
533
```