Get started with Firebase Data Connect

In this quickstart, you will learn how to build Firebase Data Connect in your application with a production SQL instance.

In the Firebase console you will:

  • Add Firebase Data Connect to your Firebase project.
  • Create a schema for an app with AI-assisted schema generation in the Firebase console, and deploy it.
  • Provision a Cloud SQL instance for your app.
  • With Gemini in Firebase, populate your database with sample data.
  • Create queries and mutations, with AI-assisted operation generation, which you can deploy and use to develop client code locally.

Then, in your local development environment, you will:

  • Set up a development tooling including a Visual Studio Code extension to work with your production instance.
  • Sync your local environment with the assets you created in the console.
  • Generate strongly typed SDKs and use them in your app.

Console flow: Use AI assistance to design your schema, then deploy it to your database

  1. If you haven't already, create a Firebase project.
    1. In the Firebase console, click Add project, then follow the on-screen instructions.
  2. Navigate to the Data Connect section of the Firebase console.
  3. Click the Get started with Gemini button.
  4. In the Schema Generator workflow panel that appears, describe an app so Gemini can help create a GraphQL schema with you.
  5. Review the GraphQL schema, then click Upgrade and deploy.
  6. Upgrade your project to the Blaze plan. This lets you create a Cloud SQL for PostgreSQL instance.

  7. Select Create a new Cloud SQL instance. In the dialog that appears, select a location and naming for your Cloud SQL for PostgreSQL database.

    Your app schema is deployed, along with a PostgreSQL database corresponding to that schema.

Console flow: Use AI assistance to create operations for your clients

Once your schema is deployed, you can take the first steps to make this data available accessible from your client apps by creating a connector of queries and mutations to deploy to the backend, and later call from clients.

Our AI assistance tools are here to help.

  1. When prompted, click the Generate operations with Gemini button.

  2. After a few moments, in the Generate your operations workflow panel that appears, review the list of queries and mutations provided by Gemini based on your schema.

  3. Click each operation row to review the GraphQL code that defines that operation. If necessary, use the trashcan control to delete operations you don't need.

  4. To add operations, click the + Add button. Then:

    1. Describe your operation in natural language.

      For example:

      List all products
      
    2. Review the generated GraphQL.

    3. If the operation is acceptable, click Insert to add it to your operations list.

  5. Continue removing and adding operations until your operation set is acceptable.

  6. To deploy this list of operations as a client-callable connector set, choose the connector's name, then click Deploy.

Console flow: Use Gemini in Firebase to create a mutation and populate your database

By completing previous steps, you created a Data Connect schema consisting of relevant entity types, and deployed it to production, meaning a PostgreSQL database with corresponding tables was also created and deployed.

To populate your database, you can use Gemini in Firebase to help you take your natural language inputs to define a GraphQL mutation to update one of your tables and a query to confirm your updates.

  1. Open the Data tab.

  2. Click the Help me write GraphQL pen_spark icon and, in the box that appears, type your input.

    For example:

    Add data for three sample products to my app.
    
  3. Click Generate. The mutation is returned.

  4. Review the output. If needed, click Edit to refine the prompt and click Regenerate.

  5. Next, click Insert to insert the mutation into the data editor.

  6. Click Run.

When you run the mutation, data is written to the applicable table in your PostgreSQL database. You can create a query in the console to view the stored data:

  1. Repeat the previous steps, using Help me write GraphQL pen_spark to create a query.

  2. In the box that appears, type your input.

    For example:

    Query data for all sample products in my app.
    
  3. Click Generate, then Run.

Local flow: Choose development tooling

Now that your have data in your deployed database, and have deployed a connector, you can continue development of your schema and connectors in your local development environment.

First, you need to set up a local environment. Data Connect offers you two ways to install development tools.

Local flow: Set up the development environment

  1. Create a new directory for your local project.
  2. Run the following command in the new directory you created.

      curl -sL https://firebase.tools/dataconnect | bash

    This script tries to set up the development environment for you and launch a browser-based IDE. This IDE provides toolings, including pre-bundled VS Code extensions, to help you manage your schema and define queries and mutations to be used in your application, and generate strongly-typed SDKs.

  alias dataconnect='curl -sL https://firebase.tools/dataconnect | bash'

Local flow: Set up your project directory

To set up your local project, initialize your project directory. In the IDE window, in the left-hand panel, click the Firebase icon to open the Data Connect VS Code extension UI:

  1. Click the Sign in with Google button.
  2. Click the Connect a Firebase project button and select the project you created earlier in the console.
  3. Click the Run firebase init button and complete the flow.

  4. Click the Start emulators button.

Local flow: Find your schema and connector in the local environment

The firebase init step in the previous section syncs assets to your Local development environment:

  • It syncs the schema you deployed
    • Find your schema: it is located in your Firebase project directory, in the /dataconnect/schema/schema.gql file.
  • It syncs the queries and mutations in the connector you deployed
    • Find your connector: the operations are located in your Firebase project directory, in the /dataconnect/connector/ directory.

Local flow: Understand your schema

Schema example: Movie

In Data Connect, GraphQL fields are mapped to columns. A Movie type would likely have id, title, imageUrl and genre. Data Connect recognizes the primitive data types String and UUID.

# File `/dataconnect/schema/schema.gql`

# By default, a UUID id key will be created by default as primary key.
type Movie @table {
  id: UUID! @default(expr: "uuidV4()")
  title: String!
  imageUrl: String!
  genre: String
}

Schema example 1:1 table: MovieMetadata

With movies, you can model movie metadata.

For example, in schema.gql, you might add the following snippet or review code generated by Gemini.

# Movie - MovieMetadata is a one-to-one relationship
type MovieMetadata @table {
  # This time, we omit adding a primary key because
  # you can rely on Data Connect to manage it.

  # @unique indicates a 1-1 relationship
  movie: Movie! @unique
  # movieId: UUID <- this is created by the above reference
  rating: Float
  releaseYear: Int
  description: String
}

Notice that the movie field is mapped to a type of Movie. Data Connect understands that this is a relationship between Movie and MovieMetadata and will manage this relationship for you.

Learn more about Data Connect schemas in the documentation

Local flow: Add more data to your tables

In the IDE editor panel, you can see CodeLens buttons appear over the GraphQL types in /dataconnect/schema/schema.gql. Just as you did in the console, you can create a mutation to add data to your production database.

Working locally, to add data to a table:

  1. In schema.gql, click the Add data button above the declaration for one of your types (like Movie, Product, Account, depending on the nature of your app).
    Code Lens Add data button for Firebase Data Connect
  2. A new file, <type>_insert.qgl, is added to your working directory, such as Movie_insert.gql or Product_insert.gql. Hard code data in the fields for that type.
  3. Click the Run (Production) button.
    Code Lens Run button for Firebase Data Connect
  4. Repeat the previous steps to add a record to other tables.

To quickly verify data was added:

  1. Back in schema.gql, click the Read data button above the type declaration.
  2. In the resulting <type>_read.gql file, like Product_read.gql, click the Run (Production) button to execute the query.

Learn more about Data Connect mutations in the documentation

Local flow: Generate SDKs

Your schema and connector operations are synced locally. Now you can use local tooling to generate client SDKs to begin implementing calls to queries and mutations in iOS, Android, web and Flutter apps.

  1. Click the Add SDK to app button.
  2. In the dialog that appears, select a directory containing code for your app. Data Connect SDK code will be generated and saved there.

  3. Select your app platform, then note that SDK code is immediately generated in your selected directory.

Local flow: Use the SDKs to call your query from an app

Now that your updated schema (if applicable). and your query are deployed to production, you can use the SDK that Data Connect generated to implement a call to your ListMovies query.

Web

  1. Add Firebase to your web app.
  2. In your React app's main file:

    • import your generated SDK
    • call Data Connect methods.
    import React from 'react';
    import ReactDOM from 'react-dom/client';
    
    // Generated queries.
    // Update as needed with the path to your generated SDK.
    import { listMovies, ListMoviesData } from '@movie-app/movies';
    
    function App() {
      const [movies, setMovies] = useState<ListMoviesData['movies']>([]);
      useEffect(() => {
        listMovies.then(res => setMovies(res.data));
      }, []);
      return (
        movies.map(movie => <h1>{movie.title}</h1>);
      );
    }
    
    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(<App />);
    

Swift

  1. Add Firebase to your iOS app.
  2. To use the generated SDK, configure it as a dependency in Xcode.

    In the Xcode top navigation bar, select File > Add Package Dependencies > Add Local, and choose the folder containing the generated Package.swift.

  3. In your app's main delegate:

    • import your generated SDK
    • call Data Connect methods.
    import SwiftUI
    
    import FirebaseDataConnect
    // Generated queries.
    // Update as needed with the package name of your generated SDK.
    import <CONNECTOR-PACKAGE-NAME>
    
    let connector = DataConnect.moviesConnector
    
    struct ListMovieView: View {
    @StateObject private var queryRef = connector.listMovies.ref()
    
        var body: some View {
            VStack {
                Button {
                    Task {
                        do {
                            try await refresh()
                        } catch {
                            print("Failed to refresh: \(error)")
                        }
                    }
                } label: {
                    Text("Refresh")
                }
    
                // use the query results in a view
                ForEach(queryRef.data?.movies ?? []) { movie in
                        Text(movie.title)
                    }
                }
        }
        @MainActor
        func refresh() async throws {
            _ = try await queryRef.execute()
        }
    
        struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ListMovieView()
        }
    }
    

Kotlin Android

  1. Add Firebase to your Android app.
  2. To use the generated SDK, configure Data Connect as a dependency in Gradle.

    Update plugins and dependencies in your app/build.gradle.kts.

    plugins {
      // Use whichever versions of these dependencies suit your application.
      // The versions shown here were the latest as of March 14, 2025.
      // Note, however, that the version of kotlin("plugin.serialization") must,
      // in general, match the version of kotlin("android").
      id("com.android.application") version "8.9.0"
      id("com.google.gms.google-services") version "4.4.2"
      val kotlinVersion = "2.1.10"
      kotlin("android") version kotlinVersion
      kotlin("plugin.serialization") version kotlinVersion
    }
    
    dependencies {
      // Use whichever versions of these dependencies suit your application.
      // The versions shown here were the latest versions as of March 14, 2025.
      implementation("com.google.firebase:firebase-dataconnect:16.0.0-beta04")
      implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.1")
      implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:1.7.3")
    
      // These dependencies are not strictly required, but will very likely be used
      // when writing modern Android applications.
      implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0")
      implementation("androidx.appcompat:appcompat:1.7.0")
      implementation("androidx.activity:activity-ktx:1.10.1")
      implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.8.7")
      implementation("com.google.android.material:material:1.12.0")
    }
    
  3. In your app's main activity:

    • import your generated SDK
    • call Data Connect methods.
    import android.os.Bundle
    import android.widget.TextView
    import androidx.appcompat.app.AppCompatActivity
    import androidx.lifecycle.Lifecycle
    import androidx.lifecycle.lifecycleScope
    import androidx.lifecycle.repeatOnLifecycle
    import kotlinx.coroutines.launch
    
    
    private val connector = com.myapplication.MoviesConnector.instance
    
    class MainActivity : AppCompatActivity() {
    
      override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val textView: TextView = findViewById(R.id.text_view)
    
        lifecycleScope.launch {
          lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
            
            val result = connector.listMovies.runCatching { execute { } }
            
            val newTextViewText = result.fold(
              onSuccess = {
                val titles = it.data.movies.map { it.title }
                "${titles.size} movies: " + titles.joinToString(", ")
              },
              onFailure = { "ERROR: ${it.message}" }
            )
            textView.text = newTextViewText
          }
        }
      }
    }
    

Flutter

  1. Add Firebase to your Flutter app.
  2. Install the flutterfire CLI dart pub global activate flutterfire_cli.
  3. Run flutterfire configure.
  4. In your app's main function:
    • import your generated SDK
    • call Data Connect methods.
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'firebase_options.dart';

// Generated queries.
// Update as needed with the path to your generated SDK

import 'movies_connector/movies.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  
  
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            body: Column(children: [
      ConstrainedBox(
        constraints: const BoxConstraints(maxHeight: 200),
        child: FutureBuilder(
            future: MoviesConnector.instance.listMovies().execute(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                return ListView.builder(
                  scrollDirection: Axis.vertical,
                  itemBuilder: (context, index) => Card(
                      child: Text(
                    snapshot.data!.data.movies[index].title,
                  )),
                  itemCount: snapshot.data!.data.movies.length,
                );
              }
              return const CircularProgressIndicator();
            }),
      )
    ])));
  }
}

Next steps

Review your deployed project and discover more tools:

  • Add data to your database, inspect and modify your schemas, and monitor your Data Connect service in the Firebase console.

Access more information in the documentation. For example, since you've completed the quickstart: