Introduction
Databases keep data safe even when the app or computer is turned off. This helps us save and find information anytime.
Jump into concepts and practice - no test required
Databases keep data safe even when the app or computer is turned off. This helps us save and find information anytime.
Databases store data on disk or cloud storage so it stays after the program stops running.# 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
# 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
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.
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
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.
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.
from fastapi import FastAPI
from sqlalchemy.orm import Session
app = FastAPI()
@app.post('/items/')
def create_item(session: Session, item: Item):
session.add(item)
session.commit()
return item
from fastapi import FastAPI
app = FastAPI()
@app.post('/users/')
def create_user(user: dict):
user['id'] = 1
return user