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 in the Firebase console using Schema Assist, and deploy it.
  • Provision a Cloud SQL instance for your app.
  • With Gemini Code Assist, populate your database with sample data.

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.
  • Use extension tooling to help you implement a query that will be used in your app.
  • Generate strongly typed SDKs and use them in your app.
  • Deploy your final schema, query and data to the cloud.

Console flow: Design your schema and 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 Gemini in Firebase to create a mutation and populate your database

By completing the previous step, 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, 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.

Prerequisites

To use this quickstart, you'll need the following.

Local flow: Set up the development environment

  1. Create a new directory for your local project.
  2. Open VS Code in the new directory.
  3. Install the Firebase Data Connect extension from the Visual Studio Code Marketplace.

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 in the local environment

The firebase init step in the previous section synced the schema you deployed from the console to your local development environment.

Find your schema: it is located in your Firebase project directory, in the /dataconnect/schema/schema.gql file.

Local flow: Work with 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: Define your query

Now the fun part, queries. As a developer, you're accustomed to writing SQL queries rather than GraphQL queries, so this can feel a bit different at first. However, GraphQL is far more terse and type-safe than raw SQL. And our VS Code extension eases the development experience.

To implement a query, you can adapt one generated with our CodeLens:

  1. In /dataconnect/schema/schema.gql, above a type (Movie, Product, Account, etc.), click the Read data CodeLens button.
  2. In the resulting <type>_read.gql file, test the query by clicking the Run (Production) button.
  3. Copy the functioning query to /dataconnect/connector/queries.gql.
  4. To make this query deployable, declare a unique name for it.

    For example, in the follow generic example, query_name might be ListMovies, or ListProducts, or ListAccounts.

# File `/dataconnect/connector/queries.gql`

# @auth() directives control who can call each operation.
query <query_name> @auth(level: PUBLIC) {
   <table_name> {
     <field_1>
     <field_2>
     <field_3>
  }
}

Execute the query using the nearby CodeLens button.

Learn more about Data Connect queries in the documentation

Local flow: Generate SDKs

  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: Deploy your schema and query to production

You have worked through a development iteration. Now you can deploy your schema and queries to the server with the Firebase extension UI or the Firebase CLI, just as you did with your schema.

In the IDE window, in the VS Code Extension UI, click the Deploy to production button.

Once deployed, go to the Firebase console to verify the schema updates (if applicable) and operations have been uploaded to the cloud. You should be able to view the schema, and run your operations on the console as well. The Cloud SQL for PostgreSQL instance will be updated with its final deployed generated schema and data.

Learn more about using the Data Connect emulator in the documentation

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: