|
| 1 | +--- |
| 2 | +title: SQLAlchemy ORM Quick Start Guide |
| 3 | +description: Get started with SQLite Cloud using SQLAlchemy ORM in FastAPI. |
| 4 | +category: getting-started |
| 5 | +status: publish |
| 6 | +slug: quick-start-sqlalchemy-orm |
| 7 | +--- |
| 8 | + |
| 9 | +In this Quick Start, we will show you how to get started with SQLite Cloud by building a FastAPI backend that connects to and reads from a SQLite Cloud database using SQLAlchemy. |
| 10 | + |
| 11 | +NOTE that FastAPI framework: |
| 12 | + - does NOT require you to use a relational database or any database at all. |
| 13 | + - CAN work with any ORM library (including SQLAlchemy) or database (including SQLite, which comes pre-installed in Python and is a database supported by SQLAlchemy). |
| 14 | + - code is MINIMAL in the example below. Most of the code is standard SQLAlchemy and framework-agnostic. |
| 15 | + |
| 16 | +--- |
| 17 | + |
| 18 | +1. **Set up a SQLite Cloud account** |
| 19 | + - If you haven't already, [sign up for a SQLite Cloud account](https://sqlitecloud.io/register) and create a new project. |
| 20 | + - In this guide, we will use the sample datasets that come pre-loaded with SQLite Cloud. |
| 21 | + |
| 22 | +2. **Create a new Python project** |
| 23 | + - You should have the latest Python version (3) installed locally. |
| 24 | + |
| 25 | +```bash |
| 26 | +mkdir sqlalchemy-quickstart |
| 27 | +cd sqlalchemy-quickstart |
| 28 | + |
| 29 | +# open the project in VSCode / another editor |
| 30 | +code . |
| 31 | + |
| 32 | +python3 -m venv .venv |
| 33 | +. .venv/bin/activate |
| 34 | +``` |
| 35 | + |
| 36 | +3. **Install dependencies** |
| 37 | + - Run this command from your current directory: |
| 38 | + |
| 39 | +```bash |
| 40 | +pip install "fastapi[standard]" sqlalchemy sqlalchemy-sqlitecloud |
| 41 | +``` |
| 42 | + |
| 43 | + - Do NOT remove the quotes around the FastAPI package. |
| 44 | + - `sqlalchemy-sqlitecloud` includes `sqlitecloud`, so no need to install the latter separately. |
| 45 | + |
| 46 | +4. **App setup** |
| 47 | + - From your current directory, create a sub-directory `fastapi_sqlc_app` with an empty `__init__.py` file to indicate the new sub-directory is a package. |
| 48 | + - NOTE: We will create all remaining project files in this sub-directory. |
| 49 | + |
| 50 | +```bash |
| 51 | +mkdir fastapi_sqlc_app |
| 52 | +cd fastapi_sqlc_app |
| 53 | +touch __init__.py |
| 54 | +``` |
| 55 | + |
| 56 | + - Create a new file `database.py` and copy in the following code. |
| 57 | + - In your SQLite Cloud account dashboard, click on `Show connection strings`, copy the Connection String, and replace `<your-connection-string>` below. Modify your string to include the name of the DB we'll query: `sqlitecloud://{hostname}:8860/chinook.sqlite?apikey={apikey}`. |
| 58 | + |
| 59 | +```py |
| 60 | +from sqlalchemy import create_engine |
| 61 | +from sqlalchemy.orm import sessionmaker |
| 62 | +from sqlalchemy.ext.declarative import declarative_base |
| 63 | + |
| 64 | +engine = create_engine('<your-connection-string>') |
| 65 | + |
| 66 | +SessionLocal = sessionmaker(bind=engine) |
| 67 | + |
| 68 | +Base = declarative_base() |
| 69 | +``` |
| 70 | + |
| 71 | + - Create a new file `models.py` and copy in the following code defining 2 SQLAlchemy ORM "models", or classes, to interact with the DB. |
| 72 | + - `__tablename__` is the name of a model's corresponding DB table. |
| 73 | + - The `Album` class' `id` attribute maps to the `AlbumId` column in the `albums` table. All other class attribute names match their corresponding table column names. |
| 74 | + |
| 75 | +```py |
| 76 | +from .database import Base |
| 77 | + |
| 78 | +from sqlalchemy import Column, ForeignKey, Integer, String |
| 79 | + |
| 80 | +class Artist(Base): |
| 81 | + __tablename__ = "artists" |
| 82 | + |
| 83 | + ArtistId = Column(Integer, primary_key=True) |
| 84 | + Name = Column(String) |
| 85 | + |
| 86 | +class Album(Base): |
| 87 | + __tablename__ = "albums" |
| 88 | + |
| 89 | + id = Column("AlbumId", Integer, primary_key=True) |
| 90 | + Title = Column(String) |
| 91 | + ArtistId = Column(Integer, ForeignKey('artists.ArtistId')) |
| 92 | +``` |
| 93 | + |
| 94 | + - Create a new file `schemas.py` and copy in the following code defining a Pydantic model, or "schema", to validate the shape of the response data. |
| 95 | + |
| 96 | +```py |
| 97 | +from pydantic import BaseModel |
| 98 | + |
| 99 | +class AlbumResponse(BaseModel): |
| 100 | + id: int |
| 101 | + Title: str |
| 102 | + ArtistName: str |
| 103 | +``` |
| 104 | + |
| 105 | + - Create a new file `read.py` and copy in the following code creating a reusable utility function to read album data. |
| 106 | + |
| 107 | +```py |
| 108 | +from . import models |
| 109 | + |
| 110 | +from sqlalchemy.orm import Session |
| 111 | + |
| 112 | +def get_albums(db: Session, skip: int = 0, num: int = 20): |
| 113 | + return db.query(models.Album.id, models.Album.Title, models.Artist.Name.label('ArtistName')).join(models.Artist).offset(skip).limit(num).all() |
| 114 | +``` |
| 115 | + |
| 116 | + - Create a new file `main.py` and copy in the following code. |
| 117 | + - The `get_db` function handles creating and closing a new `SessionLocal` instance, or DB connection/ session, for every request. |
| 118 | + - A GET request to the `/albums/` endpoint calls the `read_albums` function, which returns a list of SQLAlchemy `Album` models. The `response_model` ensures only data declared in the Pydantic schema is returned to the client. |
| 119 | + - The `AlbumResponse` Pydantic model in `schemas.py` has `ArtistName`, as opposed to `ArtistId` defined in the `Album` SQLAlchemy model in `models.py`. |
| 120 | + - `read_albums` calls the `get_albums` function in `read.py`. `get_albums` queries the `Album` ORM model/ `albums` DB table for the first 20 albums, and joins the `Artist` ORM model/ `artists` DB table to retrieve the `Artist.Name` (re-labeled `ArtistName`) expected by the `AlbumResponse` Pydantic model. |
| 121 | + |
| 122 | +```py |
| 123 | +from .database import SessionLocal |
| 124 | +from . import read, schemas |
| 125 | + |
| 126 | +from fastapi import FastAPI, Depends |
| 127 | +from sqlalchemy.orm import Session |
| 128 | + |
| 129 | +app = FastAPI() |
| 130 | + |
| 131 | +def get_db(): |
| 132 | + db = SessionLocal() |
| 133 | + try: |
| 134 | + yield db |
| 135 | + finally: |
| 136 | + db.close() |
| 137 | + |
| 138 | +@app.get("/albums/", response_model=list[schemas.AlbumResponse]) |
| 139 | +def read_albums(skip: int = 0, num: int = 20, db: Session = Depends(get_db)): |
| 140 | + albums = read.get_albums(db, skip=skip, num=num) |
| 141 | + return albums |
| 142 | +``` |
| 143 | + |
| 144 | +5. **Run your FastAPI app** |
| 145 | + - From your `sqlalchemy-quickstart` directory, run the following command: |
| 146 | + |
| 147 | +```bash |
| 148 | +uvicorn fastapi_sqlc_app.main:app --reload |
| 149 | +``` |
| 150 | + |
| 151 | + - Visit `http://127.0.0.1:8000/albums/` to see your app data. |
| 152 | + |
| 153 | +6. **Troubleshooting** |
| 154 | + |
| 155 | + - If you encounter the following error, restart your IDE and re-run your app. |
| 156 | + |
| 157 | +```bash |
| 158 | +AttributeError: module 'sqlitecloud.dbapi2' has no attribute 'sqlite_version_info'` |
| 159 | +``` |
| 160 | + |
| 161 | +7. **References** |
| 162 | + |
| 163 | + - [FastAPI introductory example](https://fastapi.tiangolo.com/#example) |
| 164 | + - [FastAPI SQL Databases tutorial](https://fastapi.tiangolo.com/tutorial/sql-databases/) |
| 165 | + - [Latest SQLAlchemy docs](https://docs.sqlalchemy.org/en/20/) |
| 166 | + |
| 167 | +And that's it! You've successfully built a FastAPI app that uses SQLAlchemy ORM to read data from a SQLite Cloud database. |
0 commit comments