DEV Community

JhonnyARM
JhonnyARM

Posted on

Building an App with a Cloud NoSQL Database

Firebase

In this article, we will create an application using Firebase, a cloud-based platform that provides a NoSQL database and other tools to simplify backend development.

What is Firebase?

Firebase provides developers with tools and services to build and manage applications efficiently. Key Firebase services include:

  1. Firestore: A NoSQL document-based database. It stores data in structures called collections, which contain documents. Each document is a flexible container that holds data as key-value pairs. This design is ideal for applications requiring real-time synchronization and scalability.

  2. Authentication: User authentication via email, social logins, or custom methods.

  3. Cloud Functions: Serverless backend logic that runs in the cloud.

  4. Cloud Storage: A powerful file storage solution.


Setting Up Firebase

Before integrating Firebase into your project, set up Firebase by following these steps:

1. Create a Firebase Project

  • Go to the Firebase Console.
  • Click Create Project, provide a project name, and follow the setup wizard.

2. Enable Firestore

  • Navigate to Firestore Database in the Firebase Console.
  • Click Create Database, and select:
    • Test Mode: Suitable for development.
    • Production Mode: Requires secure rules.

3. Generate Service Account Key

  • Go to Project Settings > Service Accounts.
  • Click Generate New Private Key.
  • Save the generated JSON file (e.g., Config/serviceAccountKey.json) to your project folder.

Integrating Firebase Firestore with .NET Core

Step 1: Install Required NuGet Packages

Install the necessary Firebase and Firestore NuGet packages:

# Firebase Admin SDK
dotnet add package FirebaseAdmin

# Firestore Integration
dotnet add package Google.Cloud.Firestore --version 3.9.0
Enter fullscreen mode Exit fullscreen mode

Step 2: Configure Firebase in .NET Core

Create a service to initialize Firebase and Firestore.

File: Services/FirebaseService.cs

using FirebaseAdmin;
using Google.Apis.Auth.OAuth2;
using Google.Cloud.Firestore;

public class FirebaseService
{
    public FirestoreDb Firestore { get; private set; }

    public FirebaseService()
    {
        string pathToServiceAccountKey = "Config/serviceAccountKey.json";

        if (FirebaseApp.DefaultInstance == null)
        {
            FirebaseApp.Create(new AppOptions()
            {
                Credential = GoogleCredential.FromFile(pathToServiceAccountKey),
            });
        }

        Firestore = FirestoreDb.Create("your-project-id"); // Replace with your Firebase project ID
        Console.WriteLine("Firestore initialized successfully.");
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Create a Controller for Firestore

Create a controller to handle HTTP POST requests for adding data to Firestore. This example ensures the body of the request uses a structured JSON format.

File: Controllers/FirebaseController.cs

using Google.Cloud.Firestore;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class FirebaseController : ControllerBase
{
    private readonly FirebaseService _firebaseService;

    public FirebaseController(FirebaseService firebaseService)
    {
        _firebaseService = firebaseService;
    }

    [HttpPost("add")]
    public async Task<IActionResult> AddDocument([FromBody] FirestoreData data)
    {
        try
        {
            if (data == null || string.IsNullOrEmpty(data.Nombre))
            {
                return BadRequest("The 'Nombre' field is required.");
            }

            CollectionReference collection = _firebaseService.Firestore.Collection("new-collection");
            DocumentReference docRef = await collection.AddAsync(data);

            return Ok($"Document added with ID: {docRef.Id}");
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"Error: {ex.Message}");
        }
    }
}

public class FirestoreData
{
    public string Nombre { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Configure Dependency Injection

Register the FirebaseService in Program.cs:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container
builder.Services.AddSingleton<FirebaseService>();
builder.Services.AddControllers();

var app = builder.Build();

app.MapControllers();
app.Run();
Enter fullscreen mode Exit fullscreen mode

Step 5: Test the POST Endpoint

Use tools like Postman, Swagger, or cURL to test the POST /api/Firebase/add endpoint.

Example Request:

curl -X POST "http://localhost:5000/api/Firebase/add" \
-H "Content-Type: application/json" \
-d '{ "nombre": "Sample Data" }'
Enter fullscreen mode Exit fullscreen mode

Expected Response:

"Document added with ID: abc123"
Enter fullscreen mode Exit fullscreen mode

Conclusion

Integrating Firebase Firestore provides a robust and scalable solution for managing data.

With Firebase, backend development becomes more efficient, enabling you to focus on delivering features rather than managing infrastructure.

Top comments (0)