What type of API does Firestore provide?
Firestore primarily offers a REST API, but also has other API options available:
-
Firestore has a REST API:
- The REST API endpoints exist under the base URL
https://firestore.googleapis.com/v1/
.
-
Other API options:
- For gRPC-supported languages, Firestore recommends using the RPC API rather than the REST API.
- Firestore also has native client libraries for various platforms like Android, iOS, Web, etc.
-
Authentication and authorization:
- The REST API accepts either Firebase Authentication ID tokens or Google Identity OAuth 2.0 tokens.
- Authentication affects the authorization method used (Security Rules vs IAM).
-
Use cases for the REST API:
- Accessing Firestore from resource-constrained environments like IoT devices.
- Automating database administration or retrieving detailed database metadata.
Firestore does not offer a GraphQL or SOAP API out of the box, but:
- GraphQL can be implemented on top of Firestore using custom server-side code if needed.
- SOAP is an older protocol and not commonly used for modern cloud databases like Firestore.
Does the Firestore API have webhooks?
Firestore Triggers vs Webhooks
-
Firestore does not have built-in webhooks in the traditional sense. Instead, it offers Cloud Functions triggers that can respond to Firestore events.
-
Cloud Functions for Firebase provides a way to handle Firestore events without needing to update client code.
Firestore Event Types
Firestore supports the following event types that you can subscribe to with Cloud Functions:
onCreate
: Triggered when a document is written to for the first time.
onUpdate
: Triggered when an existing document has any value changed.
onDelete
: Triggered when a document with data is deleted.
onWrite
: Triggered for any of the above events (create, update, or delete).
Key Points to Consider
- Cloud Firestore events only trigger on document changes, not on specific field changes.
- Events are delivered at least once, but a single event may result in multiple function invocations.
- Ordering is not guaranteed for rapid changes.
- There are limitations on database types and modes that can be used with Cloud Functions triggers.
Implementing Webhook-like Functionality
While Firestore doesn't have native webhooks, you can achieve similar functionality using Cloud Functions:
- Create an HTTPS Cloud Function that exposes an endpoint.
- Use this endpoint as the webhook URL for external services.
- In the function, process the incoming data and write it to Firestore.
Code Example
Here's a basic example of how to create an HTTPS function that can act as a webhook endpoint:
exports.myWebhook = functions.https.onRequest(async (req, res) => {
const body = req.body; // body is an array of JavaScript objects
// Get the details of the event, most probably from the body
const updateObj = {...}
// Write to Firestore
await admin.firestore().collection('...').doc('...').set(updateObj);
return res.status(200).end();
});
Best Practices
- Use Cloud Functions to handle Firestore events and implement webhook-like functionality.
- Consider function location to optimize performance and reduce latency.
- Write idempotent functions to handle potential duplicate event deliveries.
- Be aware of the limitations and constraints of Firestore triggers when designing your system.
In summary, while Firestore doesn't have native webhooks, you can use Cloud Functions to subscribe to Firestore events or create HTTPS functions to receive webhook-like requests and interact with Firestore data.
Rate Limits and other limitations
Here are the key API rate limits for the Firestore API:
Document Limits
- Maximum size for a document: 1 MiB (1,048,576 bytes) [1][2]
- Maximum depth of subcollections: 100 [2]
- Maximum size of a field value: 1 MiB - 89 bytes (1,048,487 bytes) [2]
- Maximum depth of fields in a map or array: 20 [2]
Index Limits
- Maximum number of composite indexes for a database:
- 200 without billing enabled
- 500 with billing enabled (can request increase) [2]
- Maximum number of single-field configurations:
- 200 without billing enabled
- 500 with billing enabled [2]
- Maximum number of index entries per document: 40,000 [2]
- Maximum size of an index entry: 7.5 KiB [2]
Security Rules Limits
- Maximum number of
exists()
, get()
, and getAfter()
calls per request:
- 10 for single-document requests and queries
- 20 for multi-document reads, transactions, and batched writes [1][2]
- Maximum nested
match
statement depth: 10 [1][2]
- Maximum number of expressions evaluated per request: 1,000 [1][2]
- Maximum size of a ruleset: 256 KB for source, 250 KB compiled [1][2]
Free Quota (per day)
- Stored data: 1 GiB
- Document reads: 50,000
- Document writes: 20,000
- Document deletes: 20,000
- Outbound data transfer: 10 GiB per month [2]
Key Points
- There are no built-in per-user rate limits, but you can implement custom rate limiting logic using security rules [4][5]
- IP address rate limiting is not available natively, but can be implemented using Cloud Functions [5]
- Exceeding limits generally results in errors or rejected operations [1][2]
It's important to note that while security rules can help implement some rate limiting, they cannot fully protect against malicious high-volume attacks. For critical security needs, additional server-side logic may be required.
Latest API Version
The most recent version of the Firestore API is 2.17.0, released on July 22, 2024. Here are the key points to consider:
Version Information
- The latest version of the Google Cloud Firestore API client library for Python is 2.17.0 [5].
- This version was released on July 22, 2024 [5].
Key Points
- Cloud Firestore is a fully-managed NoSQL document database for mobile, web, and server development from Firebase and Google Cloud Platform.
- It offers multi-region replication, strong consistency, and seamless integration with other Firebase and Google Cloud Platform products.
Installation
To install the latest version of the Firestore API client library for Python, you can use pip:
pip install google-cloud-firestore
Best Practices
-
Always use the latest stable version of the API client library to ensure you have access to the most recent features and bug fixes.
-
Check the release notes regularly for updates and new features. The Firestore team frequently releases updates with improvements and new capabilities.
-
When developing applications, consider using version control for your dependencies to ensure consistency across development environments.
-
Familiarize yourself with the client library documentation and the Cloud Firestore API product documentation to make the most of the available features.
-
Be aware of any breaking changes when upgrading to a new version. Always test your application thoroughly after upgrading the API client library.
By using the latest version (2.17.0) of the Firestore API client library, you ensure that you have access to the most up-to-date features and improvements for your Firestore-based applications.
How to get a Firestore developer account and API Keys?
To get a developer account for Firestore and create an API integration, you need to follow these steps:
Create a Firebase Project
- Go to the Firebase Console.
- Click on "Add project" and follow the on-screen instructions to create a new Firebase project or add Firebase services to an existing Google Cloud Platform project.
Set Up Firestore Database
- Once your project is created, navigate to the "Cloud Firestore" section in the Firebase Console.
- Follow the database creation workflow:
- Select a starting mode for your Cloud Firestore Security Rules:
- Test mode: Allows anyone to read and write data (good for initial development)
- Locked mode: Denies all reads and writes from mobile and web clients (suitable for server-side applications)
- Choose your database location.
Set Up Authentication
- For API integrations, you'll typically use service account authentication:
- Go to the Firebase Console, click on the gear icon, and select "Project settings".
- Navigate to the "Service Accounts" tab.
- Click on "Generate new private key" to download a JSON file containing your service account credentials.
Implement API Integration
-
Choose your preferred method for API integration:
- Use the Firebase Admin SDK (recommended for server-side applications).
- Use the Cloud Firestore REST API.
-
If using the Firebase Admin SDK:
- Install the SDK in your project (e.g.,
npm install firebase-admin --save
for Node.js).
- Initialize the SDK with your service account credentials.
-
If using the REST API:
- Use the base URL:
https://firestore.googleapis.com/v1/
.
- Authenticate requests using Google Identity OAuth 2.0 tokens.
What can you do with the Firestore API?
Here are the key data models you can interact with using the Firestore API, along with what is possible for each:
Documents
- Basic unit of storage in Firestore
- Contains fields mapping to values
- Can store various data types like strings, numbers, booleans, arrays, maps, etc.
- Size limit of 1 MB per document
- Can contain nested objects (maps) and subcollections
- Can be created, read, updated, and deleted
- Can be queried and filtered
Collections
- Containers for organizing documents
- Can contain any number of documents
- Can have subcollections
- Can be queried to retrieve multiple documents
- Allow for hierarchical data structuring
Fields
- Key-value pairs within documents
- Can store various data types (strings, numbers, booleans, arrays, maps, etc.)
- Can be added, updated, or deleted individually
- Can be used for querying and filtering
Arrays
- Can store lists of values within a document
- Cannot contain other arrays
- Can be queried using array-specific operations (array-contains, array-contains-any)
- Elements can be added or removed
Maps (Nested Objects)
- Can represent complex nested structures within a document
- Can be queried on subfields
- Allow for flexible, hierarchical data modeling
References
- Special data type pointing to other documents
- Can be used to create relationships between documents
- Can be queried and followed to retrieve related documents
Subcollections
- Collections nested within documents
- Allow for hierarchical data structuring
- Can be queried independently of parent documents
- Provide a way to organize related data
Transactions and Batched Writes
- Allow for atomic operations across multiple documents
- Ensure data consistency in complex operations
- Can be used for conditional updates and conflict resolution
Security Rules
- Define read/write access at the document and collection level
- Can be based on user authentication and custom conditions
- Allow for fine-grained access control
Indexes
- Automatically created for basic queries
- Custom indexes can be defined for complex queries
- Improve query performance
This list covers the main data models and concepts you can work with using the Firestore API. Each of these elements provides different capabilities for storing, organizing, and querying data in your Firestore database.