Get started with Cloud Firestore Standard edition using server client libraries Stay organized with collections Save and categorize content based on your preferences.
This quickstart shows you how to set up Cloud Firestore Enterprise edition, add data,then view the data you just added in theFirebase console using server clientlibraries for C#, Go, Java, Node.js, PHP, Python, and Ruby.
Use these client libraries to set up privileged server environments with fullaccess to your database.
Create aCloud Firestore database
If you haven't already, create a Firebase project: In theFirebase console, clickAdd project,then follow the on-screen instructions to create a Firebase project or toadd Firebase services to an existingGoogle Cloud project.
Open your project in theFirebase console. In the left panel, expandBuild and then selectFirestore database.
ClickCreate database.
Select alocation for your database.
If you aren't able to select a location, then your project's"location for defaultGoogle Cloud resources"has already been set. Some of your project's resources (like the defaultCloud Firestore instance) share a common location dependency, andtheir location can be set either during project creation or when setting upanother service that shares this location dependency.
Select a starting mode for yourCloud Firestore Security Rules:
- Test mode
Good for getting started with the mobile and web client libraries,but allows anyone to read and overwrite your data. After testing,makesure to review theSecure your data section.
To get started with the web, Apple platforms, or Android SDK, select test mode.
- Production mode
Denies all reads and writes from mobile and web clients.Your authenticated application servers (C#, Go, Java, Node.js, PHP,Python, or Ruby) can still access your database.
To get started with the C#, Go, Java, Node.js, PHP, Python, or Rubyserver client library, select production mode.
Your initial set ofCloud Firestore Security Rules will apply to your defaultCloud Firestore database. If you create multiple databases for yourproject, you can deployCloud Firestore Security Rules for each database.
ClickCreate.
(default) database in standard mode with Datastore or Firestore Native APIs can be used withApp Engine.When you enableCloud Firestore, it also enables the API in theCloud API Manager.
Set up your development environment
Add the required dependencies and client libraries to your app.
Java
- Add the Firebase Admin SDK to your app:
- Using Gradle:
implementation'com.google.firebase:firebase-admin:9.7.1'
- Using Maven:
<dependency><groupId>com.google.firebase</groupId><artifactId>firebase-admin</artifactId><version>9.7.1</version></dependency>
- Using Gradle:
- Follow the instructions below to initializeCloud Firestore with the proper credentials in your environment.
Python
- Add the Firebase Admin SDK to your Python app:
pipinstall--upgradefirebase-admin
- Follow the instructions below to initializeCloud Firestore with the proper credentials in your environment.
Node.js
- Add the Firebase Admin SDK to your app:
npminstallfirebase-admin--save
- Follow the instructions below to initializeCloud Firestore with the proper credentials in your environment.
Go
- Add the Firebase Admin SDK to your Go app:
gogetfirebase.google.com/go
- Follow the instructions below to initializeCloud Firestore with the proper credentials in your environment.
PHP
- TheCloud Firestore server client libraries (Java, Node.js, Python, Go, PHP, C#, and Ruby) useGoogle Application Default Credentialsfor authentication.
- To authenticate from your development environment, set the
GOOGLE_APPLICATION_CREDENTIALSenvironment variable to point to a JSON service account key file. You can create a key file on theAPI Console Credentials page.export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json" - In your production environment, you do not need to authenticate if you run your application on App Engine or Compute Engine, using the same project that you use forCloud Firestore. Otherwise,set up a service account.
- To authenticate from your development environment, set the
- Install and enable thegRPC extension for PHP, which you will need to use the client library.
- Add the Cloud Firestore PHP library to your app:
composer require google/cloud-firestore
Ruby
- TheCloud Firestore server client libraries (Java, Node.js, Python, Go, PHP, C#, and Ruby) useGoogle Application Default Credentialsfor authentication.
- To authenticate from your development environment, set the
GOOGLE_APPLICATION_CREDENTIALSenvironment variable to point to a JSON service account key file. You can create a key file on theAPI Console Credentials page.exportGOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
- In your production environment, you do not need to authenticate if you run your application on App Engine or Compute Engine, using the same project that you use forCloud Firestore. Otherwise,set up a service account.
- To authenticate from your development environment, set the
- Add the Cloud Firestore Ruby library to your app in your
Gemfile:gem"google-cloud-firestore"
- Install dependencies from your
Gemfileusing:bundleinstall
(Optional) Prototype and test withFirebase Local Emulator Suite
For mobile developers, before talking about how your app writes to and readsfromCloud Firestore, let's introduce a set of tools you can use toprototype and testCloud Firestore functionality:Firebase Local Emulator Suite. If you're trying out different data models,optimizing your security rules, or working to find the most cost-effective wayto interact with the back-end, being able to work locally without deployinglive services can be a great idea.
ACloud Firestore emulator is part of theLocal Emulator Suite, whichenables your app to interact with your emulated database content and config, aswell as optionally your emulated project resources (functions, other databases,and security rules).
Using theCloud Firestore emulator involves just a few steps:
- Adding a line of code to your app's test config to connect to the emulator.
- From the root of your local project directory, running
firebase emulators:start. - Making calls from your app's prototype code using aCloud Firestore platformSDK as usual.
A detailedwalkthrough involvingCloud Firestore andCloud Functions is available. You should also have a look at theLocal Emulator Suite introduction.
InitializeCloud Firestore
Initialize an instance ofCloud Firestore:
Java
TheCloud Firestore SDK is initialized in different ways depending onyour environment. Below are the most common methods. For a complete reference,seeInitializethe Admin SDK.importcom.google.auth.oauth2.GoogleCredentials;importcom.google.cloud.firestore.Firestore;importcom.google.firebase.FirebaseApp;importcom.google.firebase.FirebaseOptions;// Use the application default credentialsGoogleCredentialscredentials=GoogleCredentials.getApplicationDefault();FirebaseOptionsoptions=newFirebaseOptions.Builder().setCredentials(credentials).setProjectId(projectId).build();FirebaseApp.initializeApp(options);Firestoredb=FirestoreClient.getFirestore();
To use the Firebase Admin SDK on your own server, use aservice account.
Go toIAM & admin > Service accounts in the Google Cloud console. Generate a new private key and save the JSON file. Then use the file to initialize the SDK:
importcom.google.auth.oauth2.GoogleCredentials;importcom.google.cloud.firestore.Firestore;importcom.google.firebase.FirebaseApp;importcom.google.firebase.FirebaseOptions;// Use a service accountInputStreamserviceAccount=newFileInputStream("path/to/serviceAccount.json");GoogleCredentialscredentials=GoogleCredentials.fromStream(serviceAccount);FirebaseOptionsoptions=newFirebaseOptions.Builder().setCredentials(credentials).build();FirebaseApp.initializeApp(options);Firestoredb=FirestoreClient.getFirestore();
Python
TheCloud Firestore SDK is initialized in different ways depending onyour environment. Below are the most common methods. For a complete reference,seeInitializethe Admin SDK.importfirebase_adminfromfirebase_adminimportfirestore# Application Default credentials are automatically created.app=firebase_admin.initialize_app()db=firestore.client()
An existing application default credential can also be used to initialize the SDK.
importfirebase_adminfromfirebase_adminimportcredentialsfromfirebase_adminimportfirestore# Use the application default credentials.cred=credentials.ApplicationDefault()firebase_admin.initialize_app(cred)db=firestore.client()
To use the Firebase Admin SDK on your own server, use aservice account.
Go toIAM & admin > Service accounts in the Google Cloud console. Generate a new private key and save the JSON file. Then use the file to initialize the SDK:
importfirebase_adminfromfirebase_adminimportcredentialsfromfirebase_adminimportfirestore# Use a service account.cred=credentials.Certificate('path/to/serviceAccount.json')app=firebase_admin.initialize_app(cred)db=firestore.client()
Python
TheCloud Firestore SDK is initialized in different ways depending onyour environment. Below are the most common methods. For a complete reference,seeInitializethe Admin SDK.importfirebase_adminfromfirebase_adminimportfirestore_async# Application Default credentials are automatically created.app=firebase_admin.initialize_app()db=firestore_async.client()
An existing application default credential can also be used to initialize the SDK.
importfirebase_adminfromfirebase_adminimportcredentialsfromfirebase_adminimportfirestore_async# Use the application default credentials.cred=credentials.ApplicationDefault()firebase_admin.initialize_app(cred)db=firestore_async.client()
To use the Firebase Admin SDK on your own server, use aservice account.
Go toIAM & admin > Service accounts in the Google Cloud console. Generate a new private key and save the JSON file. Then use the file to initialize the SDK:
importfirebase_adminfromfirebase_adminimportcredentialsfromfirebase_adminimportfirestore_async# Use a service account.cred=credentials.Certificate('path/to/serviceAccount.json')app=firebase_admin.initialize_app(cred)db=firestore_async.client()
Node.js
TheCloud Firestore SDK is initialized in different ways depending onyour environment. Below are the most common methods. For a complete reference,seeInitializethe Admin SDK.- Initialize onCloud Functions
const{initializeApp,applicationDefault,cert}=require('firebase-admin/app');const{getFirestore,Timestamp,FieldValue,Filter}=require('firebase-admin/firestore');
initializeApp();constdb=getFirestore();
- Initialize onGoogle Cloud
const{initializeApp,applicationDefault,cert}=require('firebase-admin/app');const{getFirestore,Timestamp,FieldValue,Filter}=require('firebase-admin/firestore');
initializeApp({credential:applicationDefault()});constdb=getFirestore();
- Initialize on your own server
To use the Firebase Admin SDK on your own server (or any other Node.js environment),use aservice account.Go toIAM & admin > Service accounts in the Google Cloud console. Generate a new private key and save the JSON file. Then use the file to initialize the SDK:
const{initializeApp,applicationDefault,cert}=require('firebase-admin/app');const{getFirestore,Timestamp,FieldValue,Filter}=require('firebase-admin/firestore');
constserviceAccount=require('./path/to/serviceAccountKey.json');initializeApp({credential:cert(serviceAccount)});constdb=getFirestore();
Go
TheCloud Firestore SDK is initialized in different ways depending onyour environment. Below are the most common methods. For a complete reference,seeInitializethe Admin SDK.import("log"firebase"firebase.google.com/go""google.golang.org/api/option")// Use the application default credentialsctx:=context.Background()conf:=&firebase.Config{ProjectID:projectID}app,err:=firebase.NewApp(ctx,conf)iferr!=nil{log.Fatalln(err)}client,err:=app.Firestore(ctx)iferr!=nil{log.Fatalln(err)}deferclient.Close()
To use the Firebase Admin SDK on your own server, use aservice account.
Go toIAM & admin > Service accounts in the Google Cloud console. Generate a new private key and save the JSON file. Then use the file to initialize the SDK:
import("log"firebase"firebase.google.com/go""google.golang.org/api/option")// Use a service accountctx:=context.Background()sa:=option.WithCredentialsFile("path/to/serviceAccount.json")app,err:=firebase.NewApp(ctx,nil,sa)iferr!=nil{log.Fatalln(err)}client,err:=app.Firestore(ctx)iferr!=nil{log.Fatalln(err)}deferclient.Close()
PHP
PHP
For more on installing and creating aCloud Firestore client, refer toCloud Firestore Client Libraries.
use Google\Cloud\Firestore\FirestoreClient;/** * Initialize Cloud Firestore with default project ID. */function setup_client_create(string $projectId = null){ // Create the Cloud Firestore client if (empty($projectId)) { // The `projectId` parameter is optional and represents which project the // client will act on behalf of. If not supplied, the client falls back to // the default project inferred from the environment. $db = new FirestoreClient(); printf('Created Cloud Firestore client with default project ID.' . PHP_EOL); } else { $db = new FirestoreClient([ 'projectId' => $projectId, ]); printf('Created Cloud Firestore client with project ID: %s' . PHP_EOL, $projectId); }}C#
C#
For more on installing and creating aCloud Firestore client, refer toCloud Firestore Client Libraries.
FirestoreDbdb=FirestoreDb.Create(project);Console.WriteLine("Created Cloud Firestore client with project ID: {0}",project);Ruby
require"google/cloud/firestore"# The `project_id` parameter is optional and represents which project the# client will act on behalf of. If not supplied, the client falls back to the# default project inferred from the environment.firestore=Google::Cloud::Firestore.newproject_id:project_idputs"Created Cloud Firestore client with given project ID."Add data
Cloud Firestore stores data in Documents, which are stored in Collections.Cloud Firestore creates collections and documents implicitlythe first time you add data to the document. You don't need to explicitlycreate collections or documents.
Create a new collection and a document using the following example code.
Java
DocumentReferencedocRef=db.collection("users").document("alovelace");// Add document data with id "alovelace" using a hashmapMap<String,Object>data=newHashMap<>();data.put("first","Ada");data.put("last","Lovelace");data.put("born",1815);//asynchronously write dataApiFuture<WriteResult>result=docRef.set(data);// ...// result.get() blocks on responseSystem.out.println("Update time : "+result.get().getUpdateTime());Python
doc_ref=db.collection("users").document("alovelace")doc_ref.set({"first":"Ada","last":"Lovelace","born":1815})Python
doc_ref=db.collection("users").document("alovelace")awaitdoc_ref.set({"first":"Ada","last":"Lovelace","born":1815})Node.js
constdocRef=db.collection('users').doc('alovelace');awaitdocRef.set({first:'Ada',last:'Lovelace',born:1815});Go
_,_,err:=client.Collection("users").Add(ctx,map[string]interface{}{"first":"Ada","last":"Lovelace","born":1815,})iferr!=nil{log.Fatalf("Failed adding alovelace: %v",err)}PHP
PHP
For more on installing and creating aCloud Firestore client, refer toCloud Firestore Client Libraries.
$docRef = $db->collection('samples/php/users')->document('alovelace');$docRef->set([ 'first' => 'Ada', 'last' => 'Lovelace', 'born' => 1815]);printf('Added data to the lovelace document in the users collection.' . PHP_EOL);C#
DocumentReferencedocRef=db.Collection("users").Document("alovelace");Dictionary<string,object>user=newDictionary<string,object>{{"First","Ada"},{"Last","Lovelace"},{"Born",1815}};awaitdocRef.SetAsync(user);Ruby
doc_ref=firestore.doc"#{collection_path}/alovelace"doc_ref.set({first:"Ada",last:"Lovelace",born:1815})puts"Added data to the alovelace document in the users collection."Now add another document to theusers collection. Notice that this documentincludes a key-value pair (middle name) that does not appear in the firstdocument. Documents in a collection can contain different sets of information.
Java
DocumentReferencedocRef=db.collection("users").document("aturing");// Add document data with an additional field ("middle")Map<String,Object>data=newHashMap<>();data.put("first","Alan");data.put("middle","Mathison");data.put("last","Turing");data.put("born",1912);ApiFuture<WriteResult>result=docRef.set(data);System.out.println("Update time : "+result.get().getUpdateTime());Python
doc_ref=db.collection("users").document("aturing")doc_ref.set({"first":"Alan","middle":"Mathison","last":"Turing","born":1912})Python
doc_ref=db.collection("users").document("aturing")awaitdoc_ref.set({"first":"Alan","middle":"Mathison","last":"Turing","born":1912})Node.js
constaTuringRef=db.collection('users').doc('aturing');awaitaTuringRef.set({'first':'Alan','middle':'Mathison','last':'Turing','born':1912});Go
_,_,err=client.Collection("users").Add(ctx,map[string]interface{}{"first":"Alan","middle":"Mathison","last":"Turing","born":1912,})iferr!=nil{log.Fatalf("Failed adding aturing: %v",err)}PHP
PHP
For more on installing and creating aCloud Firestore client, refer toCloud Firestore Client Libraries.
$docRef = $db->collection('samples/php/users')->document('aturing');$docRef->set([ 'first' => 'Alan', 'middle' => 'Mathison', 'last' => 'Turing', 'born' => 1912]);printf('Added data to the aturing document in the users collection.' . PHP_EOL);C#
DocumentReferencedocRef=db.Collection("users").Document("aturing");Dictionary<string,object>user=newDictionary<string,object>{{"First","Alan"},{"Middle","Mathison"},{"Last","Turing"},{"Born",1912}};awaitdocRef.SetAsync(user);Ruby
doc_ref=firestore.doc"#{collection_path}/aturing"doc_ref.set({first:"Alan",middle:"Mathison",last:"Turing",born:1912})puts"Added data to the aturing document in the users collection."Read data
Use the data viewer in theFirebase consoleto quickly verify that you've added data toCloud Firestore.
You can also use the "get" method to retrieve the entire collection.
Java
// asynchronously retrieve all usersApiFuture<QuerySnapshot>query=db.collection("users").get();// ...// query.get() blocks on responseQuerySnapshotquerySnapshot=query.get();List<QueryDocumentSnapshot>documents=querySnapshot.getDocuments();for(QueryDocumentSnapshotdocument:documents){System.out.println("User: "+document.getId());System.out.println("First: "+document.getString("first"));if(document.contains("middle")){System.out.println("Middle: "+document.getString("middle"));}System.out.println("Last: "+document.getString("last"));System.out.println("Born: "+document.getLong("born"));}Python
users_ref=db.collection("users")docs=users_ref.stream()fordocindocs:print(f"{doc.id} =>{doc.to_dict()}")
Python
users_ref=db.collection("users")docs=users_ref.stream()asyncfordocindocs:print(f"{doc.id} =>{doc.to_dict()}")Node.js
constsnapshot=awaitdb.collection('users').get();snapshot.forEach((doc)=>{console.log(doc.id,'=>',doc.data());});Go
iter:=client.Collection("users").Documents(ctx)for{doc,err:=iter.Next()iferr==iterator.Done{break}iferr!=nil{log.Fatalf("Failed to iterate: %v",err)}fmt.Println(doc.Data())}PHP
PHP
For more on installing and creating aCloud Firestore client, refer toCloud Firestore Client Libraries.
$usersRef = $db->collection('samples/php/users');$snapshot = $usersRef->documents();foreach ($snapshot as $user) { printf('User: %s' . PHP_EOL, $user->id()); printf('First: %s' . PHP_EOL, $user['first']); if (!empty($user['middle'])) { printf('Middle: %s' . PHP_EOL, $user['middle']); } printf('Last: %s' . PHP_EOL, $user['last']); printf('Born: %d' . PHP_EOL, $user['born']); printf(PHP_EOL);}printf('Retrieved and printed out all documents from the users collection.' . PHP_EOL);C#
CollectionReferenceusersRef=db.Collection("users");QuerySnapshotsnapshot=awaitusersRef.GetSnapshotAsync();foreach(DocumentSnapshotdocumentinsnapshot.Documents){Console.WriteLine("User: {0}",document.Id);Dictionary<string,object>documentDictionary=document.ToDictionary();Console.WriteLine("First: {0}",documentDictionary["First"]);if(documentDictionary.ContainsKey("Middle")){Console.WriteLine("Middle: {0}",documentDictionary["Middle"]);}Console.WriteLine("Last: {0}",documentDictionary["Last"]);Console.WriteLine("Born: {0}",documentDictionary["Born"]);Console.WriteLine();}Ruby
users_ref=firestore.colcollection_pathusers_ref.getdo|user|puts"#{user.document_id} data:#{user.data}."endNext steps
Deepen your knowledge with the following topics:
- Data model — Learn more about how data isstructured inCloud Firestore, including hierarchical data and subcollections.
- Add data — Learn more about creating and updating data inCloud Firestore.
- Get data — Learn more about how to retrievedata.
- Perform simple and compound queries — Learn how to run simple and compound queries.
- Order and limit queries Learn how to orderand limit the data returned by your queries.
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 2026-02-18 UTC.