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 databasefrom 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/')
asyncdef 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/')
asyncdef 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.