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:
- Python installed on your machine
- FastAPI installed (you can install it using pip install fastapi)
- Firebase Realtime Database account and a Firebase project created
Step 1: Setup Firebase Realtime Database
- Go to the Firebase Console (https://console.firebase.google.com/) and sign in with your Google account.
- Create a new Firebase project by clicking on the "Add project" button and following the on-screen instructions.
- Once your project is created, click on the "Realtime Database" option in the left-hand menu and click on the "Create database" button.
- Choose the location for your database and set the rules to allow read and write access.
- 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
- Create a new directory for your FastAPI application and navigate to it in your terminal.
- Create a new virtual environment using the following command:
python -m venv venv
- Activate the virtual environment:
- On Windows:
venvScriptsactivate
- On macOS and Linux:
source venv/bin/activate
- On Windows:
- Install the required dependencies:
pip install fastapi uvicorn requests
Step 3: Implement CRUD operations
- 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
- Initialize your FastAPI application:
app = FastAPI()
- Define the base URL for the Firebase Realtime Database and your Firebase project ID:
base_url = "https://<your-firebase-project-id>.firebaseio.com/"
- 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!