firebase_admin.db module

Firebase Realtime Database module.

This module contains functions and classes that facilitate interacting with the Firebase RealtimeDatabase. It supports basic data manipulation operations, as well as complex queries such aslimit queries and range queries. However, it does not support realtime update notifications. Thismodule uses the Firebase REST API underneath.

Exceptions

TransactionAbortedError

exceptionfirebase_admin.db.TransactionAbortedError(message)

Bases:AbortedError

A transaction was aborted aftr exceeding the maximum number of retries.

Classes

Event

classfirebase_admin.db.Event(sse_event)

Bases:object

Represents a realtime update event received from the database.

propertydata

Parsed JSON data of this event.

propertyevent_type

Event type string (put, patch).

propertypath

Path of the database reference that triggered this event.

ListenerRegistration

classfirebase_admin.db.ListenerRegistration(callback,sse)

Bases:object

Represents the addition of an event listener to a database reference.

close()

Stops the event listener represented by this registration

This closes the SSE HTTP connection, and joins the background thread.

Query

classfirebase_admin.db.Query(**kwargs)

Bases:object

Represents a complex query that can be executed on a Reference.

Complex queries can consist of up to 2 components: a required ordering constraint, and anoptional filtering constraint. At the server, data is first sorted according to the givenordering constraint (e.g. order by child). Then the filtering constraint (e.g. limit, range)is applied on the sorted data to produce the final result. Despite the ordering constraint,the final result is returned by the server as an unordered collection. Therefore the Queryinterface performs another round of sorting at the client-side before returning the resultsto the caller. This client-side sorted results are returned to the user as a PythonOrderedDict.

end_at(end)

Sets the upper bound for a range query.

The Query will only return child nodes with a value less than or equal to the specifiedvalue.

Parameters:

end – JSON-serializable value to end at, inclusive.

Returns:

The updated Query instance.

Return type:

Query

Raises:

ValueError – If the value isNone.

equal_to(value)

Sets an equals constraint on the Query.

The Query will only return child nodes whose value is equal to the specified value.

Parameters:

value – JSON-serializable value to query for.

Returns:

The updated Query instance.

Return type:

Query

Raises:

ValueError – If the value isNone.

get()

Executes this Query and returns the results.

The results will be returned as a sorted list or an OrderedDict.

Returns:

Decoded JSON result of the Query.

Return type:

object

Raises:

FirebaseError – If an error occurs while communicating with the remote database server.

limit_to_first(limit)

Creates a query with limit, and anchors it to the start of the window.

Parameters:

limit – The maximum number of child nodes to return.

Returns:

The updated Query instance.

Return type:

Query

Raises:

ValueError – If the value is not an integer, or set_limit_last() was called previously.

limit_to_last(limit)

Creates a query with limit, and anchors it to the end of the window.

Parameters:

limit – The maximum number of child nodes to return.

Returns:

The updated Query instance.

Return type:

Query

Raises:

ValueError – If the value is not an integer, or set_limit_first() was called previously.

start_at(start)

Sets the lower bound for a range query.

The Query will only return child nodes with a value greater than or equal to the specifiedvalue.

Parameters:

start – JSON-serializable value to start at, inclusive.

Returns:

The updated Query instance.

Return type:

Query

Raises:

ValueError – If the value isNone.

Reference

classfirebase_admin.db.Reference(**kwargs)

Bases:object

Reference represents a node in the Firebase realtime database.

child(path)

Returns a Reference to the specified child node.

The path may point to an immediate child of the current Reference, or a deeply nestedchild. Child paths must not begin with ‘/’.

Parameters:

path – Path to the child node.

Returns:

A database Reference representing the specified child node.

Return type:

Reference

Raises:

ValueError – If the child path is not a string, not well-formed or begins with ‘/’.

delete()

Deletes this node from the database.

Raises:

FirebaseError – If an error occurs while communicating with the remote database server.

get(etag=False,shallow=False)

Returns the value, and optionally the ETag, at the current location of the database.

Parameters:
  • etag – A boolean indicating whether the Etag value should be returned or not (optional).

  • shallow – A boolean indicating whether to execute a shallow read (optional). Shallowreads do not retrieve the child nodes of the current database location. Cannot beset to True ifetag is also set to True.

Returns:

If etag is False returns the decoded JSON value of the current database location.If etag is True, returns a 2-tuple consisting of the decoded JSON value and the Etagassociated with the current database location.

Return type:

object

Raises:
  • ValueError – If bothetag andshallow are set to True.

  • FirebaseError – If an error occurs while communicating with the remote database server.

get_if_changed(etag)

Gets data in this location only if the specified ETag does not match.

Parameters:

etag – The ETag value to be checked against the ETag of the current location.

Returns:

A 3-tuple consisting of a boolean, a decoded JSON value and an ETag. If the ETagspecified by the caller did not match, the boolen value will be True and the JSONand ETag values would reflect the corresponding values in the database. If the ETagmatched, the boolean value will be False and the other elements of the tuple will beNone.

Return type:

tuple

Raises:
  • ValueError – If the ETag is not a string.

  • FirebaseError – If an error occurs while communicating with the remote database server.

listen(callback)

Registers thecallback function to receive realtime updates.

The specified callback function will get invoked withdb.Event objects for eachrealtime update received from the database. It will also get called whenever the SDKreconnects to the server due to network issues or credential expiration. In general,the OAuth2 credentials used to authorize connections to the server expire every hour.Therefore clients should expect thecallback to fire at least once every hour, even ifthere are no updates in the database.

This API is based on the event streaming support available in the Firebase REST API. Eachcall tolisten() starts a new HTTP connection and a background thread. This is anexperimental feature. It currently does not honor the auth overrides and timeout settings.Cannot be used in thread-constrained environments like Google App Engine.

Parameters:

callback – A function to be called when a data change is detected.

Returns:

An object that can be used to stop the event listener.

Return type:

ListenerRegistration

Raises:

FirebaseError – If an error occurs while starting the initial HTTP connection.

order_by_child(path)

Returns a Query that orders data by child values.

Returned Query can be used to set additional parameters, and execute complex databasequeries (e.g. limit queries, range queries).

Parameters:

path – Path to a valid child of the current Reference.

Returns:

A database Query instance.

Return type:

Query

Raises:

ValueError – If the child path is not a string, not well-formed or None.

order_by_key()

Creates a Query that orderes data by key.

Returned Query can be used to set additional parameters, and execute complex databasequeries (e.g. limit queries, range queries).

Returns:

A database Query instance.

Return type:

Query

order_by_value()

Creates a Query that orderes data by value.

Returned Query can be used to set additional parameters, and execute complex databasequeries (e.g. limit queries, range queries).

Returns:

A database Query instance.

Return type:

Query

push(value='')

Creates a new child node.

The optional value argument can be used to provide an initial value for the child node. Ifno value is provided, child node will have empty string as the default value.

Parameters:

value – JSON-serializable initial value for the child node (optional).

Returns:

A Reference representing the newly created child node.

Return type:

Reference

Raises:
  • ValueError – If the value is None.

  • TypeError – If the value is not JSON-serializable.

  • FirebaseError – If an error occurs while communicating with the remote database server.

set(value)

Sets the data at this location to the given value.

The value must be JSON-serializable and not None.

Parameters:

value – JSON-serializable value to be set at this location.

Raises:
  • ValueError – If the provided value is None.

  • TypeError – If the value is not JSON-serializable.

  • FirebaseError – If an error occurs while communicating with the remote database server.

set_if_unchanged(expected_etag,value)

Conditonally sets the data at this location to the given value.

Sets the data at this location to the given value only ifexpected_etag is same as theETag value in the database.

Parameters:
  • expected_etag – Value of ETag we want to check.

  • value – JSON-serializable value to be set at this location.

Returns:

A 3-tuple consisting of a boolean, a decoded JSON value and an ETag. The booleanindicates whether the set operation was successful or not. The decoded JSON and theETag corresponds to the latest value in this database location.

Return type:

tuple

Raises:
  • ValueError – If the value is None, or if expected_etag is not a string.

  • FirebaseError – If an error occurs while communicating with the remote database server.

transaction(transaction_update)

Atomically modifies the data at this location.

Unlike a normalset(), which just overwrites the data regardless of its previous state,transaction() is used to modify the existing value to a new value, ensuring there areno conflicts with other clients simultaneously writing to the same location.

This is accomplished by passing an update function which is used to transform the currentvalue of this reference into a new value. If another client writes to this location beforethe new value is successfully saved, the update function is called again with the newcurrent value, and the write will be retried. In case of repeated failures, this methodwill retry the transaction up to 25 times before giving up and raising aTransactionAbortedError. The update function may also force an early abort by raising anexception instead of returning a value.

Parameters:

transaction_update – A function which will be passed the current data stored at thislocation. The function should return the new value it would like written. Ifan exception is raised, the transaction will be aborted, and the data at thislocation will not be modified. The exceptions raised by this function arepropagated to the caller of the transaction method.

Returns:

New value of the current database Reference (only if the transaction commits).

Return type:

object

Raises:
  • TransactionAbortedError – If the transaction aborts after exhausting all retry attempts.

  • ValueError – If transaction_update is not a function.

update(value)

Updates the specified child keys of this Reference to the provided values.

Parameters:

value – A dictionary containing the child keys to update, and their new values.

Raises:
  • ValueError – If value is empty or not a dictionary.

  • FirebaseError – If an error occurs while communicating with the remote database server.

propertykey
propertyparent
propertypath

Functions

reference

firebase_admin.db.reference(path='/',app=None,url=None)

Returns a databaseReference representing the node at the specified path.

If no path is specified, this function returns aReference that represents the databaseroot. By default, the returned References provide access to the Firebase Database specified atapp initialization. To connect to a different database instance in the same Firebase project,specify theurl parameter.

Parameters:
  • path – Path to a node in the Firebase realtime database (optional).

  • app – An App instance (optional).

  • url – Base URL of the Firebase Database instance (optional). When specified, takesprecedence over the thedatabaseURL option set at app initialization.

Returns:

A newly initialized Reference.

Return type:

Reference

Raises:

ValueError – If the specified path or app is invalid.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-03-12 UTC.