0
0
FastAPIframework~5 mins

Why databases persist data in FastAPI

Choose your learning style9 modes available
Introduction

Databases keep data safe even when the app or computer is turned off. This helps us save and find information anytime.

You want to save user information like names and passwords.
You need to keep track of orders in an online store.
You want to store messages in a chat app so users can see old chats.
You want to save settings or preferences for users.
You want to keep logs or records that last over time.
Syntax
FastAPI
Databases store data on disk or cloud storage so it stays after the program stops running.
Databases use special software to organize and manage data safely.
FastAPI works well with databases to save and get data in web apps.
Examples
This example saves user data only while the app runs. If the app stops, data is lost because it is not saved in a database.
FastAPI
# Example: Saving user data in a database
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    name: str
    age: int

users = []  # This list is temporary and lost when app stops

@app.post('/users/')
async def create_user(user: User):
    users.append(user)
    return user
This example saves user data in a database file. Data stays saved even if the app stops and restarts.
FastAPI
# Example: Using a database to persist data
# (Pseudocode, actual DB setup needed)
from fastapi import FastAPI
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

app = FastAPI()

engine = create_engine('sqlite:///./test.db')
SessionLocal = sessionmaker(bind=engine)
Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String)
    age = Column(Integer)

Base.metadata.create_all(bind=engine)

@app.post('/users/')
async def create_user(name: str, age: int):
    db = SessionLocal()
    user = User(name=name, age=age)
    db.add(user)
    db.commit()
    db.refresh(user)
    db.close()
    return user
Sample Program

This FastAPI app saves items only while it runs. If you restart the app, all items disappear because they are not saved in a database. This shows why databases are important to keep data safe and persistent.

FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    description: str

items = []  # Temporary storage

@app.post('/items/')
async def create_item(item: Item):
    items.append(item)
    return {"message": "Item saved temporarily", "item": item}

@app.get('/items/')
async def read_items():
    return items
OutputSuccess
Important Notes

Data stored only in memory (like lists) disappears when the app stops.

Databases save data on disk or cloud so it lasts longer.

Using databases helps apps remember user info, settings, and history.

Summary

Databases keep data safe even when apps stop or restart.

Without databases, data is lost when the program ends.

FastAPI can work with databases to save and retrieve data reliably.