𝗙𝗮𝘀𝘁𝗔𝗣𝗜 𝗳𝗼𝗿 𝗔𝗜 𝗘𝗻𝗴𝗶𝗻𝗲𝗲𝗿𝘀: 𝗗𝗮𝘁𝗮𝗯𝗮𝘀𝗲𝘀
Stop storing data in Python lists. Your data vanishes when the server restarts. You need a database to keep your information safe.
SQLite is a great choice for beginners. It is a lightweight database. It stores everything in one file.
Writing raw SQL is hard to maintain. Use SQLAlchemy instead. It is an ORM. An ORM lets you use Python classes to manage tables.
Set up your project with these files:
- database.py for connections.
- models.py for table structures.
- schemas.py for data validation.
- main.py for your API routes.
Use Dependency Injection for your database sessions. This manages your connections automatically. It opens a session for a request and closes it after.
The workflow is simple:
- FastAPI receives a request.
- Pydantic validates the data.
- SQLAlchemy converts the object to SQL.
- SQLite stores the data.
The best part? You switch from SQLite to MySQL by changing one line. Your code stays the same.
Source: https://dev.to/zeroshotanu/fastapi-for-ai-engineers-part-3-connecting-to-a-database-30ca
Optional learning community: https://t.me/GyaanSetuAi