FastAPI Tutorial #29: Performing CRUD Operations with Firebase Realtime Database in Python

Posted by


In this tutorial, we will cover how to implement CRUD operations using Firebase Realtime Database in a FastAPI application using Python. Firebase Realtime Database is a cloud-hosted NoSQL database that allows developers to store and sync data in real-time. FastAPI is a modern web framework for building APIs with Python.

Prerequisites:

  1. Python installed on your machine
  2. FastAPI installed (you can install it using pip install fastapi)
  3. Firebase Realtime Database account and a Firebase project created

Step 1: Setup Firebase Realtime Database

  1. Go to the Firebase Console (https://console.firebase.google.com/) and sign in with your Google account.
  2. Create a new Firebase project by clicking on the "Add project" button and following the on-screen instructions.
  3. Once your project is created, click on the "Realtime Database" option in the left-hand menu and click on the "Create database" button.
  4. Choose the location for your database and set the rules to allow read and write access.
  5. Note down your Firebase project ID and API key, which will be used to authenticate your application with the Firebase Realtime Database.

Step 2: Create a FastAPI application

  1. Create a new directory for your FastAPI application and navigate to it in your terminal.
  2. Create a new virtual environment using the following command:
    python -m venv venv
  3. Activate the virtual environment:
    • On Windows:
      venvScriptsactivate
    • On macOS and Linux:
      source venv/bin/activate
  4. Install the required dependencies:
    pip install fastapi uvicorn requests

Step 3: Implement CRUD operations

  1. Create a new Python file in your project directory (e.g., main.py) and import the required modules:
    from fastapi import FastAPI, HTTPException
    from typing import List, Dict
    import requests
  2. Initialize your FastAPI application:
    app = FastAPI()
  3. Define the base URL for the Firebase Realtime Database and your Firebase project ID:
    base_url = "https://<your-firebase-project-id>.firebaseio.com/"
  4. Implement the CRUD operations using FastAPI endpoint decorators:
    
    @app.get("/items/{item_id}")
    async def read_item(item_id: int):
    response = requests.get(base_url + f"items/{item_id}.json")
    if response.status_code == 200:
        return response.json()
    raise HTTPException(status_code=response.status_code, detail=response.json())

@app.post("/items/")
async def create_item(item: Dict):
response = requests.post(base_url + "items.json", json=item)
if response.status_code == 200:
return response.json()
raise HTTPException(status_code=response.status_code, detail=response.json())

@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Dict):
response = requests.put(base_url + f"items/{item_id}.json", json=item)
if response.status_code == 200:
return response.json()
raise HTTPException(status_code=response.status_code, detail=response.json())

@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
response = requests.delete(base_url + f"items/{item_id}.json")
if response.status_code == 200:
return {"message": "Item deleted successfully"}
raise HTTPException(status_code=response.status_code, detail=response.json())


Step 4: Run the FastAPI application
1. Start the FastAPI application using the following command:

uvicorn main:app –reload


2. Open your web browser and navigate to http://localhost:8000/docs to access the FastAPI interactive documentation and test your CRUD operations.

That's it! You have successfully implemented CRUD operations using Firebase Realtime Database in a FastAPI application. Feel free to customize the endpoints and data structures to fit your application's requirements. Happy coding!
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x