You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: sqlite-cloud/quick-start-fastapi-sqlalchemy.mdx
+12-46Lines changed: 12 additions & 46 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -6,7 +6,7 @@ status: publish
6
6
slug: quick-start-sqlalchemy-orm
7
7
---
8
8
9
-
In this quickstart, we will show you how to get started with SQLite Cloud and SQLAlchemy by building a FastAPI backend that connects to and reads from a SQLite Cloud database.
9
+
In this quickstart, 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.
- From your current directory, create a sub-directory `fastapi_sqlc_app` with an empty `__init__.py` file to indicate the new sub-dir is a package.
53
-
- NOTE: Create the remaining project files in this sub-dir as well.
42
+
- 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.
43
+
- NOTE: We will create all remaining project files in this sub-directory.
54
44
55
45
```bash
56
46
mkdir fastapi_sqlc_app
@@ -75,61 +65,36 @@ Base = declarative_base()
75
65
76
66
- Create a new file `models.py` and copy in the following code defining 2 SQLAlchemy ORM "models", or classes, to interact with the DB.
77
67
-`__tablename__` is the name of a model's corresponding DB table.
78
-
- Most class attributes/ table `Column`s below are passed a class type as the first argument. NOTE: The `Album` class' `id` attribute passes `AlbumId` as the first arg.
79
-
- We use the `relationship` function to create an explicit, bidirectional link between the 2 models. Let's say:
80
-
- We have an instance of the `Artist` class called `taylor_swift`. Accessing the attribute `taylor_swift.albums` would return:
81
-
- a list of `Album` SQLAlchemy models from the `albums` DB table, whose foreign key `ArtistId` points to the `taylor_swift` record in the `artists` table.
82
-
- Or simply put, a list of Taylor Swift's albums.
83
-
- We have an instance of the `Album` class called `fearless`. Accessing the attribute `fearless.artist` would return:
84
-
- an `Artist` SQLAlchemy model from the `artists` DB table, again using the foreign key `ArtistId` to get the right record.
85
-
- Or simply put, the creator of the album Fearless (also Taylor Swift).
68
+
- 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.
86
69
87
70
```py
88
71
from .database import Base
89
72
90
73
from sqlalchemy import Column, ForeignKey, Integer, String
91
-
from sqlalchemy.orm import relationship
92
74
93
75
classArtist(Base):
94
76
__tablename__ ="artists"
95
77
96
78
ArtistId = Column(Integer, primary_key=True)
97
79
Name = Column(String)
98
80
99
-
albums = relationship("Album", back_populates="artist")
artist = relationship("Artist", back_populates="albums")
109
87
```
110
88
111
-
- Create a new file `schemas.py` and copy in the following code defining 2 Pydantic models, or "schemas", to validate the shapes of the response data.
112
-
- NOTE: The `Album` Pydantic model checks for `ArtistName` rather than `ArtistId` defined in the `Album` SQLAlchemy model in `models.py`.
113
-
- By default, SQLAlchemy "lazy loads", i.e. it only gets relationship data from the DB when we access the model's attribute containing that data.`orm_mode = True` enables the Pydantic model to read a returned ORM (in this case, SQLAlchemy) model and include relationship data.
89
+
- 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.
114
90
115
91
```py
116
92
from pydantic import BaseModel
117
93
118
-
classAlbum(BaseModel):
94
+
classAlbumResponse(BaseModel):
119
95
id: int
120
96
Title: str
121
97
ArtistName: str
122
-
123
-
classConfig:
124
-
orm_mode =True
125
-
126
-
classArtist(BaseModel):
127
-
ArtistId: int
128
-
Name: str
129
-
albums: list[Album] = []
130
-
131
-
classConfig:
132
-
orm_mode =True
133
98
```
134
99
135
100
- Create a new file `read.py` and copy in the following code creating a reusable utility function to read album data.
@@ -145,7 +110,9 @@ def get_albums(db: Session, skip: int = 0, num: int = 20):
145
110
146
111
- Create a new file `main.py` and copy in the following code.
147
112
- The `get_db` function handles creating and closing a new `SessionLocal` instance, or DB connection/ session, for every request.
148
-
- NOTE: The function below returns a list of SQLAlchemy `Album` models. However, only the data declared in the Pydantic schemas will be returned to the client.
113
+
- 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.
114
+
- The `AlbumResponse` Pydantic model in `schemas.py` has `ArtistName`, as opposed to `ArtistId` defined in the `Album` SQLAlchemy model in `models.py`.
115
+
-`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.
@@ -188,8 +155,7 @@ AttributeError: module 'sqlitecloud.dbapi2' has no attribute 'sqlite_version_inf
188
155
189
156
7. **References**
190
157
191
-
If you're new to FastAPI and/or want to learn more about how to work with ORMs in FastAPI, we referenced FastAPI's [SQL Databases Tutorial](https://fastapi.tiangolo.com/tutorial/sql-databases/) extensively when writing this Quickstart.
192
-
193
-
If you're new to SQLAlchemy, refer to [their latest docs](https://docs.sqlalchemy.org/en/20/).
158
+
- If you're new to FastAPI and/or want to learn more about how to work with ORMs in FastAPI, we referenced FastAPI's [introductory example](https://fastapi.tiangolo.com/#example) and [SQL Databases tutorial](https://fastapi.tiangolo.com/tutorial/sql-databases/) extensively when writing this Quickstart.
159
+
- If you're new to SQLAlchemy, refer to [their latest docs](https://docs.sqlalchemy.org/en/20/).
194
160
195
161
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