<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Lawson Taylor on Medium]]></title>
        <description><![CDATA[Stories by Lawson Taylor on Medium]]></description>
        <link>https://medium.com/@lawsontaylor?source=rss-e8f32cb44ad2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*qQDB0N0zcQPwQaig</url>
            <title>Stories by Lawson Taylor on Medium</title>
            <link>https://medium.com/@lawsontaylor?source=rss-e8f32cb44ad2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 05:08:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lawsontaylor/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[DIY Vector Tile Server with Postgres, FastAPI andAsync SQLAlchemy]]></title>
            <link>https://medium.com/@lawsontaylor/diy-vector-tile-server-with-postgis-and-fastapi-b8514c95267c?source=rss-e8f32cb44ad2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8514c95267c</guid>
            <category><![CDATA[sqlalchemy]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[gis]]></category>
            <dc:creator><![CDATA[Lawson Taylor]]></dc:creator>
            <pubDate>Sun, 04 Aug 2024 12:01:53 GMT</pubDate>
            <atom:updated>2024-08-04T12:01:53.562Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>DIY Vector Tile Server with Postgres, FastAPI and Async SQLAlchemy</strong></h3><figure><img alt="I am once again asking you to just use Postgres" src="https://cdn-images-1.medium.com/max/1024/1*szOv9n1P3dnBoLLb-NFC2A.jpeg" /></figure><h3>Introduction</h3><p>These days data is everywhere, probably too much of it. But when it comes to geospatial data, it can be a bit of a pain to work with and sometimes can be slow and painful to visualize.</p><p>Humans are simple creatures, and for something to be useful to us we need to visualize it.</p><p>To view geospatial, data vector tiles offer a way to serve it in a compact and fast format so that it can be injected into a map.</p><p>In this article, we’ll build a simple vector tile server using <a href="https://fastapi.tiangolo.com/tutorial/">FastAPI</a>, <a href="https://postgis.net/documentation/">PostGIS</a>, and <a href="https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html">Async SQLAlchemy</a>.</p><blockquote>So instead of going for overly complex systems and services, <strong><em>just use Postgres (and FastAPI)</em></strong>.</blockquote><p>All the code for this project is ready and waiting for you in this <a href="https://github.com/LTMullineux/fastapi-snippets">GitHub</a> repository. Please feel free to copy and paste as much as your heart desires.</p><h3>Vector Tiles: So what are they really?</h3><p>Taking a look at the <a href="https://docs.mapbox.com/help/glossary/vector-tiles/">Mapbox documentation</a>:</p><blockquote>A vector tile is a lightweight data format for storing geospatial vector data, such as points, lines, and polygons.</blockquote><p>That’s a little obscure, so let’s try to distil it down a bit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*Shdpi_nEOY28mdRiGLYruQ.png" /><figcaption>credit: <a href="https://www.researchgate.net/publication/258725283_A_Cache_Replacement_Policy_Based_on_Neural_Networks_Applied_to_Web_Map_Tile_Caching">https://www.researchgate.net/publication/258725283_A_Cache_Replacement_Policy_Based_on_Neural_Networks_Applied_to_Web_Map_Tile_Caching</a></figcaption></figure><p>In general, a digital map can display data at any scale for any area. The downside is that this is rarely efficient.</p><p>For example, if you’re looking at a map of the world, you don’t need to see the details of every road, street corner or lamppost. But as you zoom in these details need to become more prominent.</p><p>Map tiling helps improve speed and efficiency by constraining the map to specific zoom levels, each doubling the detail of the last as you go down through the zoom levels.</p><pre>zoom level 0 = 1x1 = 1 tile<br>zoom level 1 = 2x2 = 4 tiles<br>zoom level 2 = 4x4 = 16 tiles<br>zoom level 3 = 8x8 = 64 tiles<br>...</pre><p>Additionally, instead of displaying data for any location, a tiled map shows data within a fixed grid at each zoom level, combining these tiles to cover the desired area.</p><figure><img alt="credit: https://developer.myptv.com/en/documentation/vector-maps-osm-api/concepts/tiles-vector-map-osm-api" src="https://cdn-images-1.medium.com/max/741/1*e32-9rYf8UPdX_vKtlUNtg.png" /></figure><p>At each zoom level z, the tiles are indexes by coordinates (z, x, y), so that to fetch a specific tile we can send a request to http://host/{z}/{x}/{y}.{format} where the format determines the datatype being returned. In out case it will be mvt or vnd.mapbox-vector-tile for <a href="https://docs.mapbox.com/data/tilesets/guides/vector-tiles-standards/">Mapbox Vector Tiles</a>.</p><h3>The Goal</h3><p>Our goal is to build a simple vector tile server that can dynamically serve vector tiles for a given area and zoom level. We’ll use FastAPI to serve the tiles, PostGIS to store the geospatial data, and Async SQLAlchemy to query the data.</p><p>Our data source will be all of the Airbnb listings in the <a href="https://en.wikipedia.org/wiki/Balearic_Islands">Balearic Islands</a> (Ibiza, Mallorca, Menorca, and Formentera).</p><p>Finally, we’ll use a simple HTML page with <a href="https://docs.mapbox.com/mapbox-gl-js/api/">Mapbox GL JS</a> to display the tiles that are fetched from our FastAPI application</p><p>The final result will look something like this:</p><figure><img alt="MapboxGL JS HTML template for FastAPI tile server" src="https://cdn-images-1.medium.com/max/600/1*f0TKUaleTZP5qIASfrm1-Q.gif" /></figure><p>To help setup up the project we’ll use a variant of the ultimate FastAPI Setup, which you can check out here.</p><p><a href="https://medium.com/@lawsontaylor/the-ultimate-fastapi-project-setup-fastapi-async-postgres-sqlmodel-pytest-and-docker-ed0c6afea11b">The Ultimate FastAPI Project Setup: FastAPI, Async Postgres, SQLModel, Pytest and Docker.</a></p><h3>Docker Compose and the Services</h3><p>There are two services we need to run our vector tile server:</p><ul><li>Postgres with the PostGIS extension to store the geospatial data.</li><li>FastAPI to query Postgres and serve the vector tiles.</li></ul><p>The directory structure for our application looks like this:</p><pre>./<br>    docker-compose.yml  (compose file of Postgis and FastAPI)<br>    Dockerfile   (for FastAPI Dockerfile)<br>    requirements.txt  (python app requirements)<br>    .env<br>    .env.sample<br>    ./snippets<br>      config.py  (configuration of environment/application variables)<br>      crud.py  (functions to interact with the database)<br>      db.py  (database connections and metadata)<br>      gunicorn_config.py  (configuration of gunicorn)<br>      models.py  (database models)<br>      server.py  (FastAPI server and routes)<br>      ./templates<br>          index.html  (HTML template with MapboxGJ to view vector tiles)<br>    ./scripts<br>        run.sh  (helper script to launch docker compose)<br>  ./postgres<br>      ./initdb.d   (scripts run on startup of PostGIS docker image)<br>          00-initdb.sql  (initialize database)<br>          01-create-table.sql  (create tables)<br>          02-load-data.sql  (load data in ./data dir)<br>          03-create-indexes.sql  (create indexes)<br>        ./data  (Airbnb listing data)<br>            listings_1.csv.gz<br>            listings_2.csv.gz<br>            ...</pre><p>We follow the best <a href="https://hub.docker.com/_/postgres">practices for initializing the database</a>, creating tables, loading data, and creating indexes using the mapped volume ./postgres/initdb.d. The scripts in this directory will be executed in alphanumeric order when the Postgres container starts.</p><p>In our case this will create a table listing with the columns listing_id, latitude, longitude and geometry(with SRID 4326). Other attributes about the listing such as nightly rate, number of bedrooms are also stored in the table.</p><pre>+----------------------+------------------+------------------+------------------------------------------+-----------------+---------------------+--------------+------------------+---------------+----------+----------------+----------------+----------------+------------+--------------------+------------------+-------------------+----------------+-----------------------+------------+------------+------------------------+-------------+---------------+---------------+------------------------+---------------+-----------------+--------------------------------------------------+---------------------------------------------------------------------------------------------------------------------+-------------------+<br>|     &quot;listing_id&quot;     |   &quot;longitude&quot;    |    &quot;latitude&quot;    |                &quot;geometry&quot;                | &quot;property_type&quot; | &quot;property_sub_type&quot; | &quot;room_count&quot; | &quot;bathroom_count&quot; | &quot;sleep_count&quot; | &quot;rating&quot; | &quot;review_count&quot; | &quot;instant_book&quot; | &quot;is_superhost&quot; | &quot;is_hotel&quot; | &quot;children_allowed&quot; | &quot;events_allowed&quot; | &quot;smoking_allowed&quot; | &quot;pets_allowed&quot; | &quot;has_family_friendly&quot; | &quot;has_wifi&quot; | &quot;has_pool&quot; | &quot;has_air_conditioning&quot; | &quot;has_views&quot; | &quot;has_hot_tub&quot; | &quot;has_parking&quot; | &quot;has_patio_or_balcony&quot; | &quot;has_kitchen&quot; | &quot;nightly_price&quot; |                      &quot;name&quot;                      |                                                  &quot;main_image_url&quot;                                                   | &quot;recently_active&quot; |<br>+----------------------+------------------+------------------+------------------------------------------+-----------------+---------------------+--------------+------------------+---------------+----------+----------------+----------------+----------------+------------+--------------------+------------------+-------------------+----------------+-----------------------+------------+------------+------------------------+-------------+---------------+---------------+------------------------+---------------+-----------------+--------------------------------------------------+---------------------------------------------------------------------------------------------------------------------+-------------------+<br>| &quot;5985872&quot;            | 1.40467139384128 | 38.7359128252745 | POINT(1.40467139384128 38.7359128252745) | entire_home     | apartment           |            2 |                1 |             4 |    100.0 |              2 | false          | true           | false      | false              | true             | true              | false          | false                 | true       | true       | true                   | false       | true          | true          | false                  | true          |                 | Velero Moskito Valiente                          |                                                                                                                     | false             |<br>| &quot;4291324&quot;            | 1.40649931655283 | 38.7297219993439 | POINT(1.40649931655283 38.7297219993439) | private_room    |                     |            1 |                1 |             2 |          |              0 | false          | false          | false      | false              | true             | true              | false          | false                 | true       | true       | true                   | false       | true          | true          | false                  | true          |                 | Primera Linea!  Entre MAR y LAGO!                |                                                                                                                     | false             |<br>| &quot;7565940&quot;            | 1.40906888012791 | 38.7252687105131 | POINT(1.40906888012791 38.7252687105131) | entire_home     | boat                |            1 |                1 |             2 |     90.0 |              5 | true           | false          | false      | false              | false            | false             | false          | false                 | false      | false      | false                  | false       | false         | false         | false                  | true          |                 | Velero 2 pax en Formentera                       |                                                                                                                     | false             |<br>| &quot;10826946&quot;           | 1.40385555799523 | 38.7293076206739 | POINT(1.40385555799523 38.7293076206739) | private_room    | boat                |            1 |                2 |             4 |          |              0 | false          | false          | false      | false              | false            | false             | false          | false                 | false      | false      | false                  | false       | false         | false         | false                  | false         |                 | Formentera on Santippe                           |                                                                                                                     | false             |<br>| &quot;17984038&quot;           | 1.40778079793859 | 38.7269515269832 | POINT(1.40778079793859 38.7269515269832) | entire_home     | boat                |            1 |                0 |             2 |          |              1 | true           | false          | false      | false              | false            | false             | false          | false                 | false      | false      | false                  | false       | false         | false         | false                  | false         |                 | Duerme y navega con patrón en velero para 2      |                                                                                                                     | false             |<br>| &quot;4005484&quot;            | 1.40979974019137 | 38.7278542479708 | POINT(1.40979974019137 38.7278542479708) | entire_home     | boat                |            1 |                0 |             2 |     90.0 |             22 | true           | false          | false      | false              | true             | false             | false          | false                 | false      | false      | false                  | false       | false         | false         | false                  | false         |                 | Velero en Formentera. Stay on board 2 pax.       |                                                                                                                     | false             |<br>| &quot;35179794&quot;           |          1.40003 |          38.7256 | POINT(1.40003 38.7256)                   | entire_home     | villa               |            5 |                3 |            10 |          |              0 | true           | false          | false      | false              | false            | true              | false          | false                 | true       | false      | true                   | false       | false         | true          | false                  | true          |                 | Villa Sa Voliaina - Estany des Peix - Formentera |                                                                                                                     | false             |<br>| &quot;19896852&quot;           |          1.40374 |         38.72435 | POINT(1.40374 38.72435)                  | entire_home     | house               |            3 |                2 |             6 |    100.0 |             13 | false          | false          | false      | false              | false            | true              | false          | false                 | true       | false      | true                   | false       | false         | true          | false                  | true          |                 | House with terraces in the lake  ET 0502         |                                                                                                                     | false             |<br>| &quot;35252525&quot;           |          1.40257 |         38.72596 | POINT(1.40257 38.72596)                  | entire_home     | villa               |            5 |                3 |            10 |     80.0 |              4 | true           | false          | false      | true               | false            | true              | true           | true                  | true       | false      | true                   | false       | false         | true          | true                   | true          |             323 | Villa Sa Voliaina - Estany des Peix              | https://a0.muscache.com/im/pictures/prohost-api/Hosting-35252525/original/c20d1747-f620-428b-a5ab-7c3a49fd8c6d.jpeg | true              |<br>| &quot;861235572893488501&quot; |        1.4104147 |       38.7306989 | POINT(1.4104147 38.7306989)              | entire_home     | boat                |            2 |                2 |             4 |          |              0 | false          | false          | false      | false              | false            | false             | false          | false                 | false      | false      | false                  | false       | false         | false         | false                  | true          |             859 | Preciós veler de 14 metres                       | https://a0.muscache.com/im/pictures/4cdadb30-65a9-45e1-af2f-4d15d5714542.jpg                                        | true              |<br>+----------------------+------------------+------------------+------------------------------------------+-----------------+---------------------+--------------+------------------+---------------+----------+----------------+----------------+----------------+------------+--------------------+------------------+-------------------+----------------+-----------------------+------------+------------+------------------------+-------------+---------------+---------------+------------------------+---------------+-----------------+--------------------------------------------------+---------------------------------------------------------------------------------------------------------------------+-------------------+</pre><p>The Postgres start up process will then load in the data and create indexes on the tables so its ready for the FastAPI service to query.</p><p>In total, our docker-compose file will look like this:</p><pre>services:<br>  postgres:<br>    profiles: [&quot;dev&quot;]<br>    image: postgis/postgis:16-3.4-alpine<br>    restart: always<br>    healthcheck:<br>      test:<br>        - CMD-SHELL<br>        - pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB<br>      interval: 5s<br>      timeout: 5s<br>      retries: 5<br>    env_file: &quot;.env&quot;<br>    ports:<br>      - 5432:5432<br>    expose:<br>      - 5432<br>    volumes:<br>      - ./postgres/initdb.d/:/docker-entrypoint-initdb.d/<br>      - pgdata-dev:/var/lib/postgresql/data<br>    networks:<br>      - dev<br><br>  app:<br>    profiles: [&quot;dev&quot;]<br>    build:<br>      context: .<br>    command: &gt;<br>      bash -c &quot;<br>        gunicorn snippets.server:app --config ./snippets/gunicorn_config.py&quot;<br>    env_file: &quot;.env&quot;<br>    environment:<br>      - POSTGRES_HOST=postgres<br>    volumes:<br>      - ./:/code<br>    ports:<br>      - 8000:8000<br>    expose:<br>      - 8000<br>    depends_on:<br>      postgres:<br>        condition: service_healthy<br>    networks:<br>      - dev<br><br>volumes:<br>  pgdata-dev:<br><br>networks:<br>  dev:</pre><h3>PostGIS and the Tile Query</h3><p>To fetch vector tiles from the listing data we require a few PostGIS functions:</p><ul><li><a href="https://postgis.net/docs/ST_TileEnvelope.html">ST_TileEnvelope(z, x, y)</a> to generate the bounding box of a specific tile at zoom level z and coordinates x and y. This returns a geometry in Web Mercator SRID 3857.</li><li><a href="https://postgis.net/docs/ST_Transform.html">ST_Transform(geometry, SRID)</a>to transform the tile envelope to SRID 4326, and to later transform the listing geometries to SRID 3857 as this is the standard for vector tiles.</li><li><a href="https://postgis.net/docs/ST_Intersects.html">ST_Intersects(geometry_a, geometry_b)</a>to filter the listings that intersect the tile envelope.</li><li><a href="https://postgis.net/docs/ST_AsMVTGeom.html">ST_AsMVTGeom(geometry, bounds_geometry)</a> to create the vector tile geometry from the listing geometries by clipping the geometries to the tile envelope, simplifying the geometries that will not be visible at the tile resolution, and translate from cartesian (geometry coordinates) to image coordinates (tile coordinates)</li><li><a href="https://postgis.net/docs/ST_AsMVT.html">ST_AsMVT(rows)</a> to create the Mapbox Vector Tile from the clipped and simplified geometries, along with any attributes we want to include in the tile, returning the tile as bytes.</li></ul><p>Using these functions we can create a generate SQL query to turn our listing table into tile for (z, x, y) triplets:</p><pre>With tile_bounds_cte AS (<br>  -- work out the bounds of the tile in 3857 and 4326<br>  SELECT<br>    ST_TileEnvelope(:z, :x, :y) AS geom_3857,<br>    ST_Transform(ST_TileEnvelope(:z, :x, :y), 4326) AS geom_4326<br>), mvt_table_cte AS (<br>  -- process each listing in the tile bounds<br>  SELECT<br>    ST_AsMVTGeom(<br>        ST_Transform(listing.geometry, 3857), tile_bounds_cte.geom_3857<br>    ) AS geom,<br>    listing.listing_id,<br>    listing.longitude,<br>    listing.latitude,<br>    listing.property_type,<br>    -- other attribute columns ...<br>  FROM<br>    tile_bounds_cte,<br>    properties<br>  WHERE<br>    ST_Intersects(listing.geometry, tile_bounds_cte.geom_4326)<br>)<br>-- package all the listings in the tile into a single MVT<br>SELECT<br>  ST_AsMVT(mvt_table_cte.*) AS mvt<br>FROM<br>  mvt_table_cte;</pre><p>This query will return a single row with a single column that contains the vector tile as bytes and includes all the listing attributes within the tile so that we can dynamically use them in the client to style and filter.</p><h3>Serving the Tiles with FastAPI</h3><p>To server the vector tiles we’ll use FastAPI and Async SQLAlchemy.</p><p>Firstly, let’s install the dependencies:</p><pre>sqlalchemy==2.0.31<br>geoalchemy2==0.15.2<br>psycopg2-binary==2.9.9<br>asyncpg==0.29.0<br>pydantic==2.8.2<br>pydantic-settings==2.3.4<br>fastapi==0.111.1<br>uvicorn==0.30.1<br>gunicorn==22.0.0<br>jinja2==3.1.4<br>orjson==3.10.5<br>aiocache==0.12.2</pre><p>Next, define the SQLAlchemy models using GeoAlchemy2:</p><pre>from typing import Any<br><br>from geoalchemy2 import Geometry<br>from sqlalchemy import Computed, Index<br>from sqlalchemy.orm import Mapped, mapped_column<br><br>from snippets.db import Base<br><br><br>class Listing(Base):<br>    __tablename__ = &quot;listing&quot;<br>    __table_args__ = (Index(None, &quot;geometry&quot;, postgresql_using=&quot;gist&quot;),)<br><br>    listing_id: Mapped[str] = mapped_column(primary_key=True)<br>    longitude: Mapped[float] = mapped_column(nullable=True)<br>    latitude: Mapped[float] = mapped_column(nullable=True)<br>    geometry: Mapped[Any] = mapped_column(<br>        Geometry(<br>            &quot;POINT&quot;,<br>            srid=4326,<br>            spatial_index=False,<br>            from_text=&quot;ST_GeogFromText&quot;,<br>            name=&quot;geometry&quot;,<br>        ),<br>        Computed(<br>            &quot;&quot;&quot;<br>                public.geometry(point, 4326) GENERATED ALWAYS AS (<br>                    st_setsrid(st_makepoint(longitude, latitude), 4326)<br>                )<br>            &quot;&quot;&quot;,<br>            persisted=True,<br>        ),<br>        nullable=True,<br>    )<br>    property_type: Mapped[str] = mapped_column(nullable=True, index=True)<br>    # other attribute columns ...</pre><p>We now next to translate the SQL query from above into a Python function to fetch the tile bytes:</p><pre>from aiocache import Cache, cached<br>from aiocache.serializers import PickleSerializer<br>from geoalchemy2.functions import (<br>    ST_AsMVT,<br>    ST_AsMVTGeom,<br>    ST_Intersects,<br>    ST_TileEnvelope,<br>    ST_Transform,<br>)<br>from sqlalchemy import and_, select, text<br>from sqlalchemy.ext.asyncio import AsyncSession<br>from sqlalchemy.sql.expression import literal<br><br>from snippets.models import Listing<br><br><br>@cached(<br>    ttl=600,<br>    cache=Cache.MEMORY,<br>    serializer=PickleSerializer(),<br>)<br>async def get_listing_tiles_bytes(<br>    session: AsyncSession,<br>    z: int,<br>    x: int,<br>    y: int,<br>    recently_active: bool | None = True,<br>) -&gt; bytes | None:<br>    tile_bounds_cte = select(<br>        ST_TileEnvelope(z, x, y).label(&quot;geom_3857&quot;),<br>        ST_Transform(ST_TileEnvelope(z, x, y), 4326).label(&quot;geom_4326&quot;),<br>    ).cte(&quot;tile_bounds_cte&quot;)<br><br>    mvt_table_cte = (<br>        select(<br>            ST_AsMVTGeom(<br>                ST_Transform(Listing.geometry, 3857), tile_bounds_cte.c.geom_3857<br>            ).label(&quot;geom&quot;),<br>            Listing.listing_id,<br>            Listing.longitude,<br>            Listing.latitude,<br>            Listing.property_type,<br>            # other attribute columns ...<br>        )<br>        .select_from(Listing)<br>        .join(tile_bounds_cte, literal(True))  # cross join<br>        .filter(<br>            and_(<br>                Listing.geometry.is_not(None),<br>                ST_Intersects(Listing.geometry, tile_bounds_cte.c.geom_4326),<br>            )<br>        )<br>    )<br><br>    if recently_active is not None:<br>        mvt_table_cte = mvt_table_cte.filter(<br>            Listing.recently_active == recently_active<br>        )<br><br>    mvt_table_cte = mvt_table_cte.cte(&quot;mvt_table_cte&quot;)<br>    stmt = select(ST_AsMVT(text(&quot;mvt_table_cte.*&quot;))).select_from(mvt_table_cte)<br>    result = await session.execute(stmt)<br>    return result.scalar()</pre><p>You can see here how easily it is to cache the results of the query using <a href="https://github.com/aio-libs/aiocache">aiocache</a>. Here we are just using a simple in-memory cache, but you could easily use Redis cache to be shared across multiple instances of the FastAPI service.</p><p>Finally, we can define the FastAPI endpoint to serve the vector tiles:</p><pre>import gzip<br><br>from fastapi import Depends, FastAPI, Path, Request, Response, status<br>from fastapi.responses import HTMLResponse<br>from fastapi.templating import Jinja2Templates<br>from sqlalchemy.ext.asyncio import AsyncSession<br><br>from snippets.config import config<br>from snippets.crud import get_listing_tiles_bytes<br>from snippets.db import get_session<br><br>templates = Jinja2Templates(directory=&quot;./snippets/templates&quot;)<br><br><br>async def tile_args(<br>    z: int = Path(..., ge=0, le=24),<br>    x: int = Path(..., ge=0),<br>    y: int = Path(..., ge=0),<br>) -&gt; dict[str, str]:<br>    return dict(z=z, x=x, y=y)<br><br><br>app = FastAPI(title=config.PROJECT_NAME, version=config.VERSION)<br><br><br>@app.get(&quot;/&quot;, response_class=HTMLResponse)<br>async def homepage(request: Request):<br>    return templates.TemplateResponse(<br>        request=request,<br>        name=&quot;index.html&quot;,<br>        context={<br>            &quot;title&quot;: config.PROJECT_NAME,<br>            &quot;host&quot;: &quot;localhost&quot;,<br>            &quot;port&quot;: config.SNIPPETS_PORT,<br>            &quot;mapbox_access_token&quot;: config.MAPBOX_ACCESS_TOKEN,<br>        },<br>    )<br><br><br>@app.get(<br>    &quot;/listings/tiles/{z}/{x}/{y}.mvt&quot;,<br>    summary=&quot;Get listingtiles&quot;,<br>)<br>async def get_listing_tiles(<br>    tile: dict[str, int] = Depends(tile_args),<br>    session: AsyncSession = Depends(get_session),<br>) -&gt; Response:<br>    byte_tile = await get_listing_tiles_bytes(<br>        session=session, recently_active=True, **tile<br>    )<br>    byte_tile = b&quot;&quot; if byte_tile is None else byte_tile<br>    return Response(<br>        content=gzip.compress(byte_tile),<br>        media_type=&quot;application/vnd.mapbox-vector-tile&quot;,<br>        headers={&quot;Content-Encoding&quot;: &quot;gzip&quot;},<br>        status_code=status.HTTP_200_OK,<br>    )</pre><p>There are two routes here:</p><ul><li>/ to serve a HTML template with the Mapbox GL JS map to view the tiles. See below for the template.</li><li>/listings/tiles/{z}/{x}/{y}.mvt to serve the vector tiles, and is called by the template served on the / route. To help with network speed we also gzip compress the responses.</li></ul><h3>A Very Bad Frontend</h3><p>The template consists of a simple HTML page with Mapbox GL JS to display the vector tiles.</p><p>On the side of a page there is a simple slider that allows you to filter listings in the map by the nightly_rate attribute.</p><blockquote><em>THIS IS THE BEAUTY OF VECTOR TILES!</em> 😍</blockquote><p>Instead of having to query the server for new data, we can simply filter the data on the client side and only display the data we want.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot; /&gt;<br>    &lt;title&gt;{{ title }}&lt;/title&gt;<br>    &lt;meta<br>      name=&quot;viewport&quot;<br>      content=&quot;initial-scale=1,maximum-scale=1,user-scalable=no&quot;<br>    /&gt;<br>    &lt;script src=&quot;https://api.mapbox.com/mapbox-gl-js/v3.5.1/mapbox-gl.js&quot;&gt;&lt;/script&gt;<br>    &lt;link<br>      href=&quot;https://api.mapbox.com/mapbox-gl-js/v3.5.1/mapbox-gl.css&quot;<br>      rel=&quot;stylesheet&quot;<br>    /&gt;<br>    &lt;style&gt;<br>      /* lots of boring and bad CSS */<br>    &lt;/style&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;map&quot;&gt;&lt;/div&gt;<br>    &lt;div id=&quot;filterContainer&quot;&gt;<br>      &lt;h1&gt;Listing Filters&lt;/h1&gt;<br>      &lt;h2&gt;Max Price $&lt;/h2&gt;<br>      &lt;input<br>        type=&quot;range&quot;<br>        id=&quot;priceSlider&quot;<br>        min=&quot;10&quot;<br>        max=&quot;2000&quot;<br>        step=&quot;10&quot;<br>        value=&quot;2000&quot;<br>      /&gt;<br>      &lt;label for=&quot;priceSlider&quot;<br>        &gt;Nightly Price: &lt;span id=&quot;priceValue&quot;&gt;$2000&lt;/span&gt;&lt;/label<br>      &gt;<br>    &lt;/div&gt;<br>    &lt;script&gt;<br>      const host = &quot;{{ host }}&quot;;<br>      const port = &quot;{{ port }}&quot;;<br>      const tileEndpoint = `http://${host}:${port}`;<br><br>      // function to create the html for an Airbnb style listing card popup<br>      const createAirbnbCardPopup = (<br>        listing_id,<br>        imageUrl,<br>        name,<br>        propertyType,<br>        subPropertyType,<br>        beds,<br>        rating,<br>        reviewCount,<br>        price<br>      ) =&gt; {<br>        return `<br>          &lt;div class=&quot;listing-card&quot;&gt;<br>            &lt;a href=&quot;https://www.airbnb.com/rooms/${listing_id}&quot; target=&quot;_blank&quot;&gt;<br>              &lt;img src=&quot;${imageUrl}&quot; alt=&quot;${name}&quot; class=&quot;listing-image&quot; /&gt;<br>            &lt;/a&gt;<br>            &lt;div class=&quot;listing-details&quot;&gt;<br>              &lt;h3 class=&quot;listing-name&quot;&gt;${name}&lt;/h3&gt;<br>              &lt;p class=&quot;listing-type&quot;&gt;${propertyType} - ${subPropertyType}&lt;/p&gt;<br>              &lt;div class=&quot;listing-rating&quot;&gt;<br>                &lt;span class=&quot;rating&quot;&gt;${rating}&lt;/span&gt;<br>                &lt;span class=&quot;review-count&quot;&gt;(${reviewCount} reviews)&lt;/span&gt;<br>              &lt;/div&gt;<br>              &lt;div class=&quot;listing-price&quot;&gt;$${price} night&lt;/div&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        `;<br>      };<br><br>      // set the mapbox token and base map<br>      mapboxgl.accessToken = &quot;{{ mapbox_access_token }}&quot;;<br>      var map = new mapboxgl.Map({<br>        container: &quot;map&quot;,<br>        style: &quot;mapbox://styles/mapbox/streets-v11&quot;,<br>        zoom: 8,<br>        center: [2.4854125072596753, 39.36600687051655],<br>      });<br><br>      map.on(&quot;load&quot;, () =&gt; {<br>        // add the listingtile source from our FastAPI tile server<br>        const listingUrl = `${tileEndpoint}/listings/tiles/{z}/{x}/{y}.mvt`;<br>        map.addSource(&quot;listingTileSource&quot;, {<br>          type: &quot;vector&quot;,<br>          tiles: [listingUrl],<br>          minzoom: 8,<br>          maxzoom: 24,<br>        });<br><br>        // add a circle style layer for the listings<br>        map.addLayer({<br>          id: &quot;listingCircleLayer&quot;,<br>          type: &quot;circle&quot;,<br>          source: &quot;listingTileSource&quot;,<br>          &quot;source-layer&quot;: &quot;default&quot;,<br>          paint: {<br>            &quot;circle-color&quot;: &quot;#d6e6ff&quot;,<br>            &quot;circle-opacity&quot;: 0.9,<br>            &quot;circle-radius&quot;: 20,<br>            &quot;circle-stroke-color&quot;: &quot;#515459&quot;,<br>          },<br>          minzoom: 10,<br>          maxzoom: 24,<br>        });<br><br>        // add a text style layer for the nightly_rate of listings<br>        map.addLayer({<br>          id: &quot;listingTileLayer&quot;,<br>          type: &quot;symbol&quot;,<br>          source: &quot;listingTileSource&quot;,<br>          &quot;source-layer&quot;: &quot;default&quot;,<br>          layout: {<br>            &quot;text-field&quot;: [&quot;get&quot;, &quot;nightly_price&quot;],<br>            &quot;text-font&quot;: [&quot;Open Sans Bold&quot;, &quot;Arial Unicode MS Bold&quot;],<br>            &quot;text-size&quot;: 12,<br>            &quot;text-offset&quot;: [0, -0.5],<br>            &quot;text-anchor&quot;: &quot;top&quot;,<br>            &quot;icon-image&quot;: [&quot;get&quot;, &quot;marker-icon&quot;],<br>          },<br>          paint: {<br>            &quot;text-color&quot;: &quot;#000000&quot;,<br>            &quot;text-halo-color&quot;: &quot;#FFFFFF&quot;,<br>            &quot;text-halo-width&quot;: 2,<br>          },<br>          minzoom: 10,<br>          maxzoom: 24,<br>        });<br><br>        // add a Airbnb style listingcard popup<br>        map.on(&quot;click&quot;, &quot;listingCircleLayer&quot;, (e) =&gt; {<br>          map.flyTo({<br>            center: e.features[0].geometry.coordinates,<br>          });<br>          const markerData = e.features[0].properties;<br>          const popHtml = createAirbnbCardPopup(<br>            markerData.listing_id,<br>            markerData.main_image_url,<br>            markerData.name,<br>            markerData.property_type,<br>            markerData.property_sub_type,<br>            markerData.beds,<br>            markerData.rating,<br>            markerData.review_count,<br>            markerData.nightly_price<br>          );<br>          const popup = new mapboxgl.Popup({ offset: 25 })<br>            .setLngLat(e.features[0].geometry.coordinates)<br>            .setHTML(popHtml)<br>            .addTo(map);<br>        });<br>        map.on(&quot;mouseenter&quot;, &quot;listingCircleLayer&quot;, () =&gt; {<br>          map.getCanvas().style.cursor = &quot;pointer&quot;;<br>        });<br>        map.on(&quot;mouseleave&quot;, &quot;listingCircleLayer&quot;, () =&gt; {<br>          map.getCanvas().style.cursor = &quot;&quot;;<br>        });<br>      });<br><br>      map.addControl(new mapboxgl.NavigationControl());<br><br>      // here we add an event listener to filter the listings by price dynamically<br>      document<br>        .getElementById(&quot;priceSlider&quot;)<br>        .addEventListener(&quot;input&quot;, function (e) {<br>          const sliderValue = e.target.value;<br>          document.getElementById(&quot;priceValue&quot;).innerText = sliderValue;<br>          filterFeaturesByPrice(sliderValue);<br>        });<br><br>      function filterFeaturesByPrice(price) {<br>        map.setFilter(&quot;listingCircleLayer&quot;, [<br>          &quot;&lt;&quot;,<br>          [&quot;get&quot;, &quot;nightly_price&quot;],<br>          parseInt(price),<br>        ]);<br>        map.setFilter(&quot;listingTileLayer&quot;, [<br>          &quot;&lt;&quot;,<br>          [&quot;get&quot;, &quot;nightly_price&quot;],<br>          parseInt(price),<br>        ]);<br>      }<br>    &lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>As we are using Airbnb listings, the map is supposed to mimic the Airbnb website, but it’s a very bad copy. However, the functionality is there:</p><ul><li>as you zoom in and get to zoom level 10, you’ll see the listings appear on the map.</li><li>each listing contains all the attributes we queried from the Postgres database, and you can filter the listings by the nightly rate using the slider.</li><li>you can also use the attributes to style the listings on the map.</li><li>for example, each listing is represented by a circle with the nightly rate as the label.</li><li>if you click on a listing, you’ll get a popup with listing information, where the attributes are rendered dynamically into the HTML.</li></ul><h3>The Final Results</h3><p>To launch our Postgres database and FastAPI service, we can use the following script:</p><pre>#!/bin/bash<br><br>set -e<br><br>ENV=$1<br>shift<br>DOCKER_ARGS=&quot;$*&quot;<br><br>trap ctrl_c INT<br>trap ctrl_c SIGTERM<br><br>function ctrl_c() {<br>    echo &quot;Gracefully hutting down containers ...&quot;<br>    docker compose --profile $ENV down --volumes<br>    exit 0<br>}<br><br>docker compose --profile $ENV up $DOCKER_ARGS</pre><p>This will start the Postgres service, run all the scripts in ./postgres/initdb.d, and then start the FastAPI service once the Postgres service is healthy. To kill the service, simply hit ctrl+c and the script will gracefully shut down the containers and remove the data volume.</p><p>To run the script, use the following command:</p><pre>./scripts/run.sh dev</pre><p>To view the map, open a browser and navigate to <a href="http://localhost:8000/a">http://localhost:8000/</a> and <strong><em>Voila!</em></strong></p><p><em>Note the docker compose logs as you zoom and pan around the map, you’ll see the FastAPI service serving the vector tiles dynamically!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ZEQfDEmEKsHu-hd1kESBMg.gif" /></figure><h3>Extensions and Improvements</h3><p>This is a very basic implementation of a vector tile server, but there are many ways to improve and extend it:</p><ul><li><strong>Redis Cache</strong>: instead of using an in-memory cache, you could use Redis to cache the tiles across multiple instances of the FastAPI service.</li><li><strong>Dynamic Queries</strong>: say you run a business that has many clients, each with their own geospatial data. For example, you want to serve only the vector tiles for the data that belongs to that client. To do this you could set up the route as http://localhost:8000/{client_uuid}/listings/tiles/{z}/{x}/{y}.mvt and filter the data on the server before returning it to the client.</li><li>You could <strong>further filter</strong> the data on the client side by adding query string parameters to the tile endpoint, for example <a href="http://localhost:8000/listings/tiles%7Bz%7D/%7Bx%7D/%7By%7D.mvt?price_max=500&amp;beds=2`">http://localhost:8000/listings/tiles{z}/{x}/{y}.mvt?price_max=500&amp;beds=2</a> and pushing the filters down to the SQL query.</li><li>The SQL query is just that, a SQL query. So feel free to do joins, filters, group by, partition the tables, … <strong><em>You wrote the entire code so you can do want you want with it!</em></strong></li></ul><p>If you enjoyed this article or have any feedback please feel free to clap/follow and check out the original source code <a href="https://github.com/LTMullineux/fastapi-snippets">GitHub</a>.</p><p>Thanks for reading!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F16250404&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fits-fine-dog-fine-dog-fire-meme-gif-16250404&amp;image=https%3A%2F%2Fmedia.tenor.com%2F5ety3Lx3QccAAAAN%2Fits-fine-dog-fine.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f4ca59323a6257f3fd7225def6cdbe7/href">https://medium.com/media/3f4ca59323a6257f3fd7225def6cdbe7/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8514c95267c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Factory and Repository Pattern with SQLAlchemy and Pydantic]]></title>
            <link>https://medium.com/@lawsontaylor/the-factory-and-repository-pattern-with-sqlalchemy-and-pydantic-33cea9ae14e0?source=rss-e8f32cb44ad2------2</link>
            <guid isPermaLink="false">https://medium.com/p/33cea9ae14e0</guid>
            <category><![CDATA[sqlalchemy]]></category>
            <category><![CDATA[crud]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pydantic]]></category>
            <category><![CDATA[software-patterns]]></category>
            <dc:creator><![CDATA[Lawson Taylor]]></dc:creator>
            <pubDate>Sun, 04 Feb 2024 21:00:44 GMT</pubDate>
            <atom:updated>2024-02-04T21:00:44.379Z</atom:updated>
            <content:encoded><![CDATA[<h4>Implementing the factory and repository pattern in a SQLAlchemy and Pydantic application to simplify everything.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_xXpIuk3xljPMA4V" /><figcaption>Photo by <a href="https://unsplash.com/@klalit?utm_source=medium&amp;utm_medium=referral">Lalit Kumar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>Feeling the fatigue of endlessly repeating CRUD code in your projects? 😫</p><p>Are you done with the mystery of installing packages from maintainers who’ve jumped ship? 😒</p><p>What if I told you there’s a simpler way to amp up your CRUD operations in Python without sacrificing elegance? 😎</p><p>Hold tight, because in this article, we’re venturing into the realm of Python, SQLAlchemy, and Pydantic to unveil the magic of the Factory and Repository Patterns.</p><p><strong>Our mission</strong>: Cook up a sleek CRUD (Create, Read, Update, Delete) application, seasoned with savvy design patterns.</p><p>Say goodbye to the mundane and embrace a codebase that’s not just functional but a joy to manage on your own. Ready for the ride? 🚀</p><p>All the code, plus step-by-step tests showcasing how to wield this coding magic, are ready and waiting for you in this <a href="https://github.com/LTMullineux/fastapi-snippets/tree/main/01-sqlalchemy-pydantic-crud-factory-pattern">GitHub repository</a>. Please feel free to copy and paste as much as your heart desires.</p><h4>But Why the Design Patterns?</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgifs.com%2Fiembed%2FoVNMVY&amp;display_name=http%3A%2F%2Fgifs.com&amp;url=https%3A%2F%2Fgifs.com%2Fgif%2Fbunny-factory-oVNMVY&amp;image=https%3A%2F%2Fj.gifs.com%2FoVNMVY.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gifs" width="480" height="270" frameborder="0" scrolling="no"><a href="https://medium.com/media/2645455eda7027695ff892d1901c34de/href">https://medium.com/media/2645455eda7027695ff892d1901c34de/href</a></iframe><p><strong>Imagine this</strong>: a world where business logic and database details stay in their own lanes. That’s where the Factory and Repository Patterns come into play.</p><p>Before we dive in, let’s nail down the basics.</p><p><strong><em>The Factory Pattern</em></strong>, a design trick, crafts objects without the fuss of revealing their origins.</p><p>For us that means having a factory function take a database model class and return a new class that has all the CRUD functionality we need attached to it.</p><p>The perks include:</p><ul><li><strong>Standardizing </strong>CRUD operations across models.</li><li><strong>Centralizing </strong>CRUD operations — do it once, and attach it to the model.</li><li><strong>Unravelling business logic</strong> from database intricacies.</li><li>Smoothly expanding CRUD operations with new methods or giving them a facelift in child classes.</li></ul><p>Now, meet it’s cousin the <strong><em>Repository Pattern,</em></strong> a design maestro simplifying the logic of retrieving and storing data. Perks include:</p><ul><li><strong>Isolating </strong>query logic.</li><li><strong>Standardizing </strong>the database <strong>interface</strong>.</li><li><strong>Abstracting </strong>up database access — the rest of the application blissfully unaware of the data storage details.</li><li>The freedom to switch data sources without causing chaos in the rest of your application.</li></ul><blockquote>So the <strong>repository pattern</strong> lets us have a access layer for a <strong>single</strong> model, and the <strong>factory pattern</strong> lets us create an access layer for <strong>any </strong>model.</blockquote><h4>The Application Tools</h4><p>To showcase the Factory and Repository Pattern in action, we’re gearing up to build a straightforward CRUD application using some trusted Python tools:</p><ul><li><strong>Python 3.12</strong>: The go-to language for its simplicity, readability, and versatility across a range of applications.</li><li><strong>SQLAlchemy</strong>: An open-source SQL toolkit and Object-Relational Mapping (ORM) library, providing a high-level API for smooth interactions with relational databases.</li><li><strong>AsyncPG</strong>: An asynchronous PostgreSQL driver for Python, tailored for PostgreSQL databases and designed with the asynchronous programming paradigm in mind.</li><li><strong>Pydantic</strong>: A powerhouse for data validation and settings management using Python type annotations. It lets you define data schemas and ensures data aligns with those schemas. <em>Note: Version 2.0.0 or higher is powered by Rust for a speed boost.</em></li></ul><p>Assuming you have a basic grasp of these tools, we’ll straight into the action. If you need a refresher or want to explore more about them, check out the Medium article below for an in-depth guide and tips on setting up the perfect project.</p><p><a href="https://medium.com/@lawsontaylor/the-ultimate-fastapi-project-setup-fastapi-async-postgres-sqlmodel-pytest-and-docker-ed0c6afea11b">The Ultimate FastAPI Project Setup: FastAPI, Async Postgres, SQLModel, Pytest and Docker.</a></p><p>Let’s get started!</p><h4>Finally, the Application</h4><p>Let’s dive into crafting a straightforward CRUD application designed for handling posts and users. First, let’s explore the models that set the stage for our application:</p><pre>from datetime import datetime<br>from typing import TypeAlias<br>from uuid import UUID as UuidType<br><br>from pydantic import BaseModel<br>from sqlalchemy import DateTime, Text<br>from sqlalchemy.dialects.postgresql import UUID as UuidColumn<br>from sqlalchemy.ext.compiler import compiles<br>from sqlalchemy.orm import Mapped, mapped_column<br>from sqlalchemy.sql.expression import FunctionElement<br>from uuid6 import uuid7<br><br>from snippets.database import Base<br><br># Some generic types for the SQLAlchemy and Pydantic models<br>SnippetModel: TypeAlias = Base<br>SnippetSchema: TypeAlias = BaseModel<br><br><br># some mixins to make our life easier<br>class UuidMixin:<br>    uuid: Mapped[UuidType] = mapped_column(<br>        &quot;uuid&quot;,<br>        UuidColumn(as_uuid=True),<br>        primary_key=True,<br>        default=uuid7,<br>        nullable=False,<br>        sort_order=-1000,<br>    )<br><br><br>class UuidMixinSchema(BaseModel):<br>    uuid: UuidType = None<br><br><br>class utcnow(FunctionElement):<br>    type = DateTime()<br>    inherit_cache = True<br><br><br>@compiles(utcnow, &quot;postgresql&quot;)<br>def pg_utcnow(element, compiler, **kw):<br>    return &quot;TIMEZONE(&#39;utc&#39;, CURRENT_TIMESTAMP)&quot;<br><br><br>class TimestampMixin:<br>    created_at: Mapped[datetime] = mapped_column(<br>        DateTime,<br>        nullable=False,<br>        server_default=utcnow(),<br>        sort_order=9999,<br>    )<br>    updated_at: Mapped[datetime] = mapped_column(<br>        DateTime,<br>        nullable=True,<br>        index=True,<br>        server_default=utcnow(),<br>        server_onupdate=utcnow(),<br>        sort_order=10000,<br>    )<br><br><br>class TimestampMixinSchema(BaseModel):<br>    created_at: datetime | None = None<br>    updated_at: datetime | None = None<br><br><br># now the real models<br># first posts<br>class Post(Base, UuidMixin, TimestampMixin):<br>    __tablename__ = &quot;post&quot;<br><br>    title: Mapped[str] = mapped_column(nullable=False, unique=True)<br>    content: Mapped[str] = mapped_column(Text, nullable=False)<br>    published: Mapped[bool] = mapped_column(nullable=False, server_default=&quot;False&quot;)<br>    views: Mapped[int] = mapped_column(nullable=False, server_default=&quot;0&quot;)<br><br><br>class PostSchema(UuidMixinSchema, TimestampMixinSchema):<br>    title: str<br>    content: str<br>    published: bool = False<br>    views: int = 0<br><br><br>class PostUpdateSchema(BaseModel):<br>    title: str | None = None<br>    content: str | None = None<br>    published: bool | None = None<br>    views: int | None = None<br><br><br># now the users<br>class User(Base, UuidMixin, TimestampMixin):<br>    __tablename__ = &quot;user&quot;<br><br>    username: Mapped[str] = mapped_column(nullable=False, unique=True, index=True)<br>    email: Mapped[str] = mapped_column(unique=True, index=True, nullable=False)<br>    hashed_password: Mapped[str] = mapped_column(nullable=False)<br>    is_active: Mapped[bool] = mapped_column(default=True, server_default=&quot;TRUE&quot;)<br><br><br>class UserBaseSchema(BaseModel):<br>    username: str<br>    email: str<br>    is_active: bool = True<br><br><br>class UserSchema(UserBaseSchema, UuidMixinSchema, TimestampMixinSchema):<br>    hashed_password: str<br><br><br>class UserInSchema(UserBaseSchema):<br>    password: str<br><br><br>class UserUpdateSchema(BaseModel):<br>    username: str | None = None<br>    email: str | None = None<br>    password: str | None = None<br>    is_active: bool | None = None</pre><p>In this snippet, you’ll find the Post and User database models.</p><p>We’ve added some nifty mixins for features like a UUID primary key, along with created_atand updated_at fields.</p><p>Not stopping there, we’ve also set up Pydantic schemas for these models. These schemas pull double duty: validating data before it hits the database and shaping data for a smooth journey back to the client.</p><p>When it comes to users, we’ve got distinct schemas for what’s headed into the database versus what’s making a triumphant exit.</p><p><em>Why the separation?</em></p><p>Because we’re adding a touch of magic — hashing the password before storing it. Okay, for demo purposes, we’re keeping it simple and saying the hashed password is just the reverse of the original (a big no-no in real applications, of course).</p><p>Now let’s check out the factory and repository patterns in action😯</p><p><strong>The Factory and Repository Pattern for CRUD Operations</strong></p><p>Rather than crafting a repository for each model, let’s spice things up by employing the Factory Pattern. We’ll whip up a generic repository capable of handling any model.</p><p>This abstract repository will feature methods for the usual suspects: creating, reading, updating, and deleting data from the database.</p><p>Now, here’s the code for this abstract repository (copy and paste it and use it at your leisure 😃)</p><pre>from uuid import UUID<br><br>from sqlalchemy import delete, select<br>from sqlalchemy.exc import IntegrityError<br>from sqlalchemy.ext.asyncio import AsyncSession<br><br>from snippets.models import (<br>    SnippetModel,<br>    SnippetSchema,<br>    User,<br>    UserInSchema,<br>    UserSchema,<br>    UserUpdateSchema,<br>)<br><br><br>class SnippetException(Exception):<br>    pass<br><br><br>class IntegrityConflictException(Exception):<br>    pass<br><br><br>class NotFoundException(Exception):<br>    pass<br><br><br>def CrudFactory(model: SnippetModel):<br>    class AsyncCrud:<br>        @classmethod<br>        async def create(<br>            cls,<br>            session: AsyncSession,<br>            data: SnippetSchema,<br>        ) -&gt; SnippetModel:<br>            &quot;&quot;&quot;Accepts a Pydantic model, creates a new record in the database, catches<br>            any integrity errors, and returns the record.<br><br>            Args:<br>                session (AsyncSession): SQLAlchemy async session<br>                data (SnippetSchema): Pydantic model<br><br>            Raises:<br>                IntegrityConflictException: if creation conflicts with existing data<br>                SnippetException: if an unknown error occurs<br><br>            Returns:<br>                SnippetModel: created SQLAlchemy model<br>            &quot;&quot;&quot;<br>            try:<br>                db_model = model(**data.model_dump())<br>                session.add(db_model)<br>                await session.commit()<br>                await session.refresh(db_model)<br>                return db_model<br>            except IntegrityError:<br>                raise IntegrityConflictException(<br>                    f&quot;{model.__tablename__} conflicts with existing data.&quot;,<br>                )<br>            except Exception as e:<br>                raise SnippetException(f&quot;Unknown error occurred: {e}&quot;) from e<br><br>        @classmethod<br>        async def create_many(<br>            cls,<br>            session: AsyncSession,<br>            data: list[SnippetSchema],<br>            return_models: bool = False,<br>        ) -&gt; list[SnippetModel] | bool:<br>            &quot;&quot;&quot;_summary_<br><br>            Args:<br>                session (AsyncSession): SQLAlchemy async session<br>                data (list[SnippetSchema]): list of Pydantic models<br>                return_models (bool, optional): Should the created models be returned<br>                    or a boolean indicating they have been created. Defaults to False.<br><br>            Raises:<br>                IntegrityConflictException: if creation conflicts with existing data<br>                SnippetException: if an unknown error occurs<br><br>            Returns:<br>                list[SnippetModel] | bool: list of created SQLAlchemy models or boolean<br>            &quot;&quot;&quot;<br>            db_models = [model(**d.model_dump()) for d in data]<br>            try:<br>                session.add_all(db_models)<br>                await session.commit()<br>            except IntegrityError:<br>                raise IntegrityConflictException(<br>                    f&quot;{model.__tablename__} conflict with existing data.&quot;,<br>                )<br>            except Exception as e:<br>                raise SnippetException(f&quot;Unknown error occurred: {e}&quot;) from e<br><br>            if not return_models:<br>                return True<br><br>            for m in db_models:<br>                await session.refresh(m)<br><br>            return db_models<br><br>        @classmethod<br>        async def get_one_by_id(<br>            cls,<br>            session: AsyncSession,<br>            id_: str | UUID,<br>            column: str = &quot;uuid&quot;,<br>            with_for_update: bool = False,<br>        ) -&gt; SnippetModel:<br>            &quot;&quot;&quot;Fetches one record from the database based on a column value and returns<br>            it, or returns None if it does not exist. Raises an exception if the column<br>            doesn&#39;t exist.<br><br>            Args:<br>                session (AsyncSession): SQLAlchemy async session<br>                id_ (str | UUID): value to search for in `column`.<br>                column (str, optional): the column name in which to search.<br>                    Defaults to &quot;uuid&quot;.<br>                with_for_update (bool, optional): Should the returned row be locked<br>                    during the lifetime of the current open transactions.<br>                    Defaults to False.<br><br>            Raises:<br>                SnippetException: if the column does not exist on the model<br><br>            Returns:<br>                SnippetModel: SQLAlchemy model or None<br>            &quot;&quot;&quot;<br>            try:<br>                q = select(model).where(getattr(model, column) == id_)<br>            except AttributeError:<br>                raise SnippetException(<br>                    f&quot;Column {column} not found on {model.__tablename__}.&quot;,<br>                )<br><br>            if with_for_update:<br>                q = q.with_for_update()<br><br>            results = await session.execute(q)<br>            return results.unique().scalar_one_or_none()<br><br>        @classmethod<br>        async def get_many_by_ids(<br>            cls,<br>            session: AsyncSession,<br>            ids: list[str | UUID] = None,<br>            column: str = &quot;uuid&quot;,<br>            with_for_update: bool = False,<br>        ) -&gt; list[SnippetModel]:<br>            &quot;&quot;&quot;Fetches multiple records from the database based on a column value and<br>            returns them. Raises an exception if the column doesn&#39;t exist.<br><br>            Args:<br>                session (AsyncSession): SQLAlchemy async session<br>                ids (list[str  |  UUID], optional): list of values to search for in<br>                    `column`. Defaults to None.<br>                column (str, optional): the column name in which to search<br>                    Defaults to &quot;uuid&quot;.<br>                with_for_update (bool, optional): Should the returned rows be locked<br>                    during the lifetime of the current open transactions.<br>                    Defaults to False.<br><br>            Raises:<br>                SnippetException: if the column does not exist on the model<br><br>            Returns:<br>                list[SnippetModel]: list of SQLAlchemy models<br>            &quot;&quot;&quot;<br>            q = select(model)<br>            if ids:<br>                try:<br>                    q = q.where(getattr(model, column).in_(ids))<br>                except AttributeError:<br>                    raise SnippetException(<br>                        f&quot;Column {column} not found on {model.__tablename__}.&quot;,<br>                    )<br><br>            if with_for_update:<br>                q = q.with_for_update()<br><br>            rows = await session.execute(q)<br>            return rows.unique().scalars().all()<br><br>        @classmethod<br>        async def update_by_id(<br>            cls,<br>            session: AsyncSession,<br>            data: SnippetSchema,<br>            id_: str | UUID,<br>            column: str = &quot;uuid&quot;,<br>        ) -&gt; SnippetModel:<br>            &quot;&quot;&quot;Updates a record in the database based on a column value and returns the<br>            updated record. Raises an exception if the record isn&#39;t found or if the<br>            column doesn&#39;t exist.<br><br>            Args:<br>                session (AsyncSession): SQLAlchemy async session<br>                data (SnippetSchema): Pydantic schema for the updated data.<br>                id_ (str | UUID): value to search for in `column`<br>                column (str, optional): the column name in which to search<br>                    Defaults to &quot;uuid&quot;.<br>            Raises:<br>                NotFoundException: if the record isn&#39;t found<br>                IntegrityConflictException: if the update conflicts with existing data<br><br>            Returns:<br>                SnippetModel: updated SQLAlchemy model<br>            &quot;&quot;&quot;<br>            db_model = await cls.get_one_by_id(<br>                session, id_, column=column, with_for_update=True<br>            )<br>            if not db_model:<br>                raise NotFoundException(<br>                    f&quot;{model.__tablename__} {column}={id_} not found.&quot;,<br>                )<br><br>            values = data.model_dump(exclude_unset=True)<br>            for k, v in values.items():<br>                setattr(db_model, k, v)<br><br>            try:<br>                await session.commit()<br>                await session.refresh(db_model)<br>                return db_model<br>            except IntegrityError:<br>                raise IntegrityConflictException(<br>                    f&quot;{model.__tablename__} {column}={id_} conflict with existing data.&quot;,<br>                )<br><br>        @classmethod<br>        async def update_many_by_ids(<br>            cls,<br>            session: AsyncSession,<br>            updates: dict[str | UUID, SnippetSchema],<br>            column: str = &quot;uuid&quot;,<br>            return_models: bool = False,<br>        ) -&gt; list[SnippetModel] | bool:<br>            &quot;&quot;&quot;Updates multiple records in the database based on a column value and<br>            returns the updated records. Raises an exception if the column doesn&#39;t<br>            exist.<br><br>            Args:<br>                session (AsyncSession): SQLAlchemy async session<br>                updates (dict[str  |  UUID, SnippetSchema]): dictionary of id_ to<br>                    Pydantic update schema<br>                column (str, optional): the column name in which to search.<br>                    Defaults to &quot;uuid&quot;.<br>                return_models (bool, optional): Should the created models be returned<br>                    or a boolean indicating they have been created. Defaults to False.<br>                    Defaults to False.<br><br>            Raises:<br>                IntegrityConflictException: if the update conflicts with existing data<br><br>            Returns:<br>                list[SnippetModel] | bool: list of updated SQLAlchemy models or boolean<br>            &quot;&quot;&quot;<br>            updates = {str(id): update for id, update in updates.items() if update}<br>            ids = list(updates.keys())<br>            db_models = await cls.get_many_by_ids(<br>                session, ids=ids, column=column, with_for_update=True<br>            )<br><br>            for db_model in db_models:<br>                values = updates[str(getattr(db_model, column))].model_dump(<br>                    exclude_unset=True<br>                )<br>                for k, v in values.items():<br>                    setattr(db_model, k, v)<br>                session.add(db_model)<br><br>            try:<br>                await session.commit()<br>            except IntegrityError:<br>                raise IntegrityConflictException(<br>                    f&quot;{model.__tablename__} conflict with existing data.&quot;,<br>                )<br><br>            if not return_models:<br>                return True<br><br>            for db_model in db_models:<br>                await session.refresh(db_model)<br><br>            return db_models<br><br>        @classmethod<br>        async def remove_by_id(<br>            cls,<br>            session: AsyncSession,<br>            id_: str | UUID,<br>            column: str = &quot;uuid&quot;,<br>        ) -&gt; int:<br>            &quot;&quot;&quot;Removes a record from the database based on a column value. Raises an<br>            exception if the column doesn&#39;t exist.<br><br>            Args:<br>                session (AsyncSession): SQLAlchemy async session<br>                id (str | UUID): value to search for in `column` and delete<br>                column (str, optional): the column name in which to search.<br>                    Defaults to &quot;uuid&quot;.<br><br>            Raises:<br>                SnippetException: if the column does not exist on the model<br><br>            Returns:<br>                int: number of rows removed, 1 if successful, 0 if not. Can be greater<br>                    than 1 if id_ is not unique in the column.<br>            &quot;&quot;&quot;<br>            try:<br>                query = delete(model).where(getattr(model, column) == id_)<br>            except AttributeError:<br>                raise SnippetException(<br>                    f&quot;Column {column} not found on {model.__tablename__}.&quot;,<br>                )<br><br>            rows = await session.execute(query)<br>            await session.commit()<br>            return rows.rowcount<br><br>        @classmethod<br>        async def remove_many_by_ids(<br>            cls,<br>            session: AsyncSession,<br>            ids: list[str | UUID],<br>            column: str = &quot;uuid&quot;,<br>        ) -&gt; int:<br>            &quot;&quot;&quot;Removes multiple records from the database based on a column value.<br>            Raises an exception if the column doesn&#39;t exist.<br><br>            Args:<br>                session (AsyncSession): SQLAlchemy async session<br>                ids (list[str  |  UUID]): list of values to search for in `column` and<br>                column (str, optional): the column name in which to search.<br>                    Defaults to &quot;uuid&quot;.<br><br>            Raises:<br>                SnippetException: if ids is empty to stop deleting an entire table<br>                SnippetException: if column does not exist on the model<br><br>            Returns:<br>                int: _description_<br>            &quot;&quot;&quot;<br>            if not ids:<br>                raise SnippetException(&quot;No ids provided.&quot;)<br><br>            try:<br>                query = delete(model).where(getattr(model, column).in_(ids))<br>            except AttributeError:<br>                raise SnippetException(<br>                    f&quot;Column {column} not found on {model.__tablename__}.&quot;,<br>                )<br><br>            rows = await session.execute(query)<br>            await session.commit()<br>            return rows.rowcount<br><br>    AsyncCrud.model = model<br>    return AsyncCrud</pre><p><strong>Check it out</strong>: the function takes a model class, creates an abstract class featuring standard CRUD operations, each bound to the model class and then returns the class.</p><p>So to use the factory all we have to do is pass in a SQLAlchemy model and we have a class that provides 99% of the crud operations we’ll ever need!</p><p>Witness the Factory Pattern in action:</p><pre>from snippets.crud import CrudFactory<br>from snippets.database import create_async_engine, create_pg_url_from_env<br>from snippets.models import Post<br><br>engine = create_async_engine(create_pg_url_from_env())<br><br>SessionLocal = async_sessionmaker(<br>    bind=engine,<br>    autoflush=False,<br>    expire_on_commit=False,<br>    autocommit=False,<br>)<br><br>PostCrud = Crudfactory(Post)<br><br>async with SessionLocal() as session:<br>    post = await PostCrud.get_one_by_id(<br>        session=session,<br>        column=&quot;title&quot;,<br>        id_=&quot;The Factory and Repository Pattern with SQLAlchemy and Pydantic&quot;,<br>    )<br>    post.published = True<br>    await session.commit()<br>  </pre><p><strong>Notice the flexibility:</strong> we don’t tie ourselves to performing CRUD operations solely on the primary key. Any column in the table can be the star of the show.</p><p><strong>This is handy</strong> — <em>think usernames or emails that are unique across the table, so why do we want to create separate methods for them …</em></p><p>Let’s bring it to life with some slick unit tests:</p><pre>import pytest<br>from snippets.crud import CrudFactory, IntegrityConflictException<br>from snippets.models import Post, PostSchema, PostUpdateSchema<br><br>PostCrud = CrudFactory(Post)<br><br><br>@pytest.mark.asyncio<br>class TestPostCrud:<br>    async def test_create_post(self, session):<br>        post_create = PostSchema(title=&quot;my first post&quot;, content=&quot;hello world&quot;)<br>        post = await PostCrud.create(session, post_create)<br>        assert post.uuid is not None<br>        assert post.created_at is not None<br>        assert post.updated_at is not None<br>        assert post.title == &quot;my first post&quot;<br>        assert post.content == &quot;hello world&quot;<br><br>    async def test_get_many_by_ids(self, session):<br>        posts_create = [<br>            PostSchema(title=&quot;1: my first post&quot;, content=&quot;hello world&quot;),<br>            PostSchema(title=&quot;2: my second post&quot;, content=&quot;hello world again&quot;),<br>            PostSchema(title=&quot;3: my third post&quot;, content=&quot;foo bar baz&quot;),<br>        ]<br>        posts = await PostCrud.create_many(session, posts_create, return_models=True)<br>        posts = sorted(posts, key=lambda x: x.title)<br><br>        posts_selected = await PostCrud.get_many_by_ids(<br>            session, [posts[0].uuid, posts[2].uuid]<br>        )<br>        posts_selected = sorted(posts_selected, key=lambda x: x.title)<br><br>        assert posts_selected[0].title == &quot;1: my first post&quot;<br>        assert posts_selected[1].title == &quot;3: my third post&quot;<br><br>    async def test_update_by_id(self, session):<br>        posts_create = [<br>            PostSchema(title=&quot;1: my first post&quot;, content=&quot;hello world&quot;),<br>            PostSchema(title=&quot;2: my second post&quot;, content=&quot;hello world again&quot;),<br>        ]<br>        posts = await PostCrud.create_many(session, posts_create, return_models=True)<br>        posts = sorted(posts, key=lambda x: x.title)<br><br>        post_update = PostUpdateSchema(content=&quot;i changed my mind&quot;)<br>        post1 = await PostCrud.update_by_id(session, posts[0].uuid, post_update)<br>        assert post1.content == &quot;i changed my mind&quot;<br><br>    async def test_remove_by_id(self, session):<br>        posts_create = [<br>            PostSchema(title=&quot;1: my first post&quot;, content=&quot;hello world&quot;),<br>            PostSchema(title=&quot;2: my second post&quot;, content=&quot;hello world again&quot;),<br>        ]<br>        posts = await PostCrud.create_many(session, posts_create, return_models=True)<br>        posts = sorted(posts, key=lambda x: x.title)<br><br>        row_count = await PostCrud.remove_by_id(session, posts[0].uuid)<br>        assert row_count == 1<br><br>        all_posts = await PostCrud.get_many_by_ids(<br>            session, [posts[0].uuid, posts[1].uuid]<br>        )<br>        assert len(all_posts) == 1<br><br>        row_count = await PostCrud.remove_by_id(session, posts[0].uuid)<br>        assert row_count == 0</pre><p>You can now see that this factory/repository combo allows us to greater simplify and abstract out the data access layer of the application, giving a simple and repeatable interface for all models.</p><blockquote>Just take the factory function, pass in a SQLAlchemy model, and bam!</blockquote><h4>Expanding a Repository</h4><p>The beauty of the Factory Pattern shines as we extend our repository effortlessly.</p><p>Simply create a new class that inherits from the abstract repository and tweak the methods as needed.</p><p>This flexibility allows us to add new methods or modify existing ones with ease.</p><p><strong>Consider this</strong>: our User repository requires the ability to take a password in plain text, hash it, and then gracefully store it in the database.</p><p>Achieving this is a breeze with a new class that inherits from the abstract repository, wherein we override the create and update_by_id methods.</p><pre>class UserCrud(CrudFactory(User)):<br><br>    @classmethod<br>    async def create_many(cls, *args, **kwargs) -&gt; list[User]:<br>        raise NotImplementedError(&quot;Create many not implemented for users.&quot;)<br><br>    @classmethod<br>    async def update_many_by_ids(cls, *args, **kwargs) -&gt; list[User] | bool:<br>        raise NotImplementedError(&quot;Update many not implemented for users.&quot;)<br><br>    @classmethod<br>    def format_user_with_password(cls, user: UserInSchema) -&gt; UserSchema:<br>        &quot;&quot;&quot;Take a Pydantic UserInSchema and return a UserSchema with the password<br>        hashed.<br><br>        Args:<br>            user (UserInSchema): Pydantic UserInSchema holding the user information<br><br>        Returns:<br>            UserSchema: Pydantic UserSchema with the password hashed<br>        &quot;&quot;&quot;<br>        user_data = user.model_dump()<br>        password = user_data.pop(&quot;password&quot;)<br>        db_user = UserSchema(<br>            **user_data, hashed_password=cls.get_password_hash(password)<br>        )<br>        return db_user<br><br>    @classmethod<br>    def get_password_hash(cls, password: str) -&gt; str:<br>        &quot;&quot;&quot;Perform hashing of passwords. This is a simple example and should not be used<br>        in production. A simple example:<br><br>            ```python<br>            from passlib.context import CryptContext<br>            pwd_context = CryptContext(schemes=[&quot;bcrypt&quot;], deprecated=&quot;auto&quot;)<br><br>            def verify_password(plain_password: str, hashed_password: str) -&gt; bool:<br>                return pwd_context.verify(plain_password, hashed_password)<br><br>            def get_password_hash(password: str) -&gt; str:<br>                return pwd_context.hash(password)<br>            ```<br><br>        Args:<br>            password (str): user&#39;s password<br><br>        Returns:<br>            str: user&#39;s hashed password<br>        &quot;&quot;&quot;<br>        # NOTE: do not ever do this in production<br>        return password[::-1]<br><br>    @classmethod<br>    async def create(cls, session: AsyncSession, data: UserInSchema) -&gt; User:<br>        &quot;&quot;&quot;Create a user in the database. This method is overridden to hash the password<br>        and then calls the parent create method, with the hashed password.<br><br>        Args:<br>            session (AsyncSession): SQLAlchemy async session<br>            data (UserInSchema): Pydantic UserInSchema holding the user information<br><br>        Returns:<br>            User: SQLAlchemy User model<br>        &quot;&quot;&quot;<br>        db_user = cls.format_user_with_password(data)<br>        return await super(cls, cls).create(session, data=db_user)<br><br>    @classmethod<br>    async def update_by_id(<br>        cls,<br>        session: AsyncSession,<br>        data: UserUpdateSchema,<br>        id_: str | UUID,<br>        column: str = &quot;uuid&quot;,<br>    ) -&gt; User:<br>        &quot;&quot;&quot;Updates a user in the database based on a column value and returns the<br>        updated user. Raises an exception if the user isn&#39;t found or if the column<br>        doesn&#39;t exist.<br><br>        Overrides the parent method to hash the password if it is included in the<br>        update.<br><br>        Args:<br>            session (AsyncSession): SQLAlchemy async session<br>            data (UserUpdateSchema): Pydantic schema for the updated data.<br>            id_ (str | UUID): value to search for in `column`<br>            column (str, optional): the column name in which to search.<br>                Defaults to &quot;uuid&quot;.<br><br>        Raises:<br>            NotFoundException: user not found in database given id_ and column<br>            IntegrityConflictException: update conflicts with existing data<br><br>        Returns:<br>            User: updated SQLAlchemy model<br>        &quot;&quot;&quot;<br>        db_model = await cls.get_one_by_id(<br>            session, id_, column=column, with_for_update=True<br>        )<br>        if not db_model:<br>            raise NotFoundException(<br>                f&quot;{User.__tablename__} id={id_} not found.&quot;,<br>            )<br><br>        values = data.model_dump(exclude_unset=True, exclude={&quot;password&quot;})<br>        for k, v in values.items():<br>            setattr(db_model, k, v)<br><br>        if data.password is not None:<br>            db_model.hashed_password = cls.get_password_hash(data.password)<br><br>        try:<br>            await session.commit()<br>            await session.refresh(db_model)<br>            return db_model<br>        except IntegrityError as e:<br>            raise IntegrityConflictException(<br>                f&quot;{User.__tablename__} {column}={id_} conflict with existing data.&quot;,<br>            ) from e</pre><p>In the create method override, we hash the password before calling the original create method to securely store the user in the database.</p><p>For the update_by_id method we rewrite the original method to include the logic to handle hashing the password if it exists in the update, maintaining the security of our stored data. The Factory and Repository Pattern’s power in action again! 👊</p><p>Again some simple unit tests to show the User repository in action:</p><pre>import pytest<br>from snippets.crud import IntegrityConflictException, UserCrud<br>from snippets.models import UserInSchema, UserUpdateSchema<br><br><br>@pytest.mark.asyncio<br>class TestUserCrud:<br>    async def test_create_user(self, session):<br>        user_create = UserInSchema(<br>            username=&quot;test&quot;,<br>            email=&quot;test@test.com&quot;,<br>            password=&quot;password&quot;,<br>        )<br>        user = await UserCrud.create(session, user_create)<br>        assert user.uuid is not None<br>        assert user.created_at is not None<br>        assert user.updated_at is not None<br>        assert user.username == &quot;test&quot;<br>        assert user.email == &quot;test@test.com&quot;<br>        assert user.is_active is True<br>        assert user.hashed_password == &quot;drowssap&quot;<br><br>    async def test_create_user_conflict_username(self, session):<br>        user_create = UserInSchema(<br>            username=&quot;test&quot;,<br>            email=&quot;test@test.com&quot;,<br>            password=&quot;password&quot;,<br>        )<br>        _ = await UserCrud.create(session, user_create)<br><br>        user_conflict = UserInSchema(<br>            username=&quot;test&quot;,<br>            email=&quot;test1@test.com&quot;,<br>            password=&quot;password&quot;,<br>        )<br>        with pytest.raises(IntegrityConflictException):<br>            _ = await UserCrud.create(session, user_conflict)<br><br>    async def test_update_user(self, session):<br>        user_create = UserInSchema(<br>            username=&quot;test&quot;,<br>            email=&quot;test@test.com&quot;,<br>            password=&quot;password&quot;,<br>        )<br>        user = await UserCrud.create(session, user_create)<br><br>        user_update = await UserCrud.update_by_id(<br>            session, id_=user.uuid, data=UserUpdateSchema(password=&quot;new_password&quot;)<br>        )<br>        assert user_update.username == &quot;test&quot;<br>        assert user_update.email == &quot;test@test.com&quot;<br>        assert user_update.hashed_password == &quot;drowssap_wen&quot;<br><br>    async def test_update_user_conflict(self, session):<br>        _ = await UserCrud.create(<br>            session,<br>            UserInSchema(<br>                username=&quot;test&quot;,<br>                email=&quot;test@test.com&quot;,<br>                password=&quot;password&quot;,<br>            ),<br>        )<br>        _ = await UserCrud.create(<br>            session,<br>            UserInSchema(<br>                username=&quot;test1&quot;,<br>                email=&quot;test1@test.com&quot;,<br>                password=&quot;password&quot;,<br>            ),<br>        )<br><br>        with pytest.raises(IntegrityConflictException):<br>            _ = await UserCrud.update_by_id(<br>                session,<br>                id_=&quot;test1&quot;,<br>                column=&quot;username&quot;,<br>                data=UserUpdateSchema(email=&quot;test@test.com&quot;),<br>            )</pre><p><strong>Conclusion</strong></p><p>In our journey building a Python CRUD app with SQLAlchemy and Pydantic, the Factory and Repository Patterns stood out for their elegance and adaptability.</p><p>The Factory Pattern crafted a generic repository, easily extendable for any model. Meanwhile, the Repository Pattern abstracted data logic, providing flexibility in data source choices.</p><p>The Factory Pattern also showcased its flexibility as we effortlessly extended the repository, like adding password hashing to the User repository.</p><p>In essence, these patterns turned data management into an art, making our code not just functional but also effortlessly maintainable and extensible. Whether it’s a simple CRUD app or a larger project, consider these design patterns for a harmonious codebase. 🚀</p><p>If you enjoyed this article or have any feedback please feel free to clap/follow and check out the original source code <a href="https://github.com/LTMullineux/fastapi-snippets/tree/main">GitHub</a>.</p><p>Thanks for reading!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F16250404&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fits-fine-dog-fine-dog-fire-meme-gif-16250404&amp;image=https%3A%2F%2Fmedia.tenor.com%2F5ety3Lx3QccAAAAF%2Fits-fine-dog-fine.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/b807c6a7452573c5f5a470415cdb7eb5/href">https://medium.com/media/b807c6a7452573c5f5a470415cdb7eb5/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33cea9ae14e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ultimate FastAPI Project Setup: FastAPI, Async Postgres, SQLModel, Pytest and Docker.]]></title>
            <link>https://medium.com/@lawsontaylor/the-ultimate-fastapi-project-setup-fastapi-async-postgres-sqlmodel-pytest-and-docker-ed0c6afea11b?source=rss-e8f32cb44ad2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed0c6afea11b</guid>
            <category><![CDATA[sqlalchemy]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Lawson Taylor]]></dc:creator>
            <pubDate>Tue, 25 Jul 2023 10:07:15 GMT</pubDate>
            <atom:updated>2023-07-25T10:07:15.724Z</atom:updated>
            <content:encoded><![CDATA[<h3>FastAPI Project Setup: The Ultimate Guide with Async Postgres, SQLModel, Pytest, &amp; Docker</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*blsS_lM51bPEIeg3" /><figcaption>Photo by <a href="https://unsplash.com/@marcojodoin?utm_source=medium&amp;utm_medium=referral">Marc-Olivier Jodoin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If like me, you love working with frameworks that are intuitive, extensible, and a joy to use, then you need to give FastAPI a go!</p><p><a href="https://www.techempower.com/benchmarks/#section=test&amp;runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&amp;hw=ph&amp;test=composite&amp;l=zijzen-7">FastAPI is an exceptionally fast</a> and user-friendly web framework tailored for creating APIs with Python. Its seamless integration with <a href="https://docs.pydantic.dev/latest/">Pydantic</a>, a data validation library, enables impressive functionalities like automatic data validation and documentation generation.</p><p>As a result, you can effortlessly develop a well-organized, thoroughly documented, and blazingly fast API. 🚀</p><p><em>So what’s the catch?</em></p><p>One of the main drawbacks of FastAPI is that it is relatively new compared to competitors like Flask and Django. Some say this means that the developer community and availability of online materials are too small.</p><p><strong><em>But don’t let this deter you.</em></strong></p><p>In just a few easy-to-follow steps, you’ll learn how to set up the ultimate environment for development using FastAPI.</p><p>Although we won’t explore all the possibilities of FastAPI in this article, by the end of it you‘ll have a solid base project that embraces asynchronous operations and maintains a clean and scalable code structure.</p><h3>Tools and Python Packages Needed for Async FastAPI Project Setup</h3><p>Before diving into the FastAPI project setup, let’s take a look at the tools and libraries used to make the development of FastAPI applications clean, easy, and repeatable.</p><p><a href="https://fastapi.tiangolo.com/"><strong>FastAPI</strong></a><strong> — </strong>is an advanced web framework designed specifically for creating APIs using Python. It prioritizes high performance and developer productivity. Built on top of the asynchronous framework <a href="https://www.starlette.io/">Starlette</a>, FastAPI takes advantage of Python-type hints to automatically validate data and generate amazing documentation.</p><p><a href="https://docs.docker.com/compose/"><strong>Docker and Docker Compose</strong></a> — Docker helps you package and deploy applications easily, while Docker Compose manages more complex applications with multiple Docker containers. Both tools make it simple to work with containers and streamline the deployment and management of applications.</p><p><a href="https://www.postgresql.org/"><strong>Postgres</strong></a><strong> — </strong>Known for its reliability, robustness, and extensive feature set, Postgres is a powerful and open-source relational database.</p><p><a href="https://sqlmodel.tiangolo.com/"><strong>SQLModel</strong></a><strong> — </strong>This Python library simplifies interactions with SQL databases using a combination <a href="https://www.sqlalchemy.org/">SQLAlchemy</a> and <a href="https://docs.pydantic.dev/latest/">Pydantic</a>. It provides a modern, type-safe, and Pythonic interface for defining database models using Python classes and type annotations, eliminating the need for explicit SQL statements.</p><p><a href="https://github.com/MagicStack/asyncpg"><strong>Asynchronous Postgres Connections</strong></a><strong> — </strong>To connect to Postgres, you’ll use <a href="https://github.com/MagicStack/asyncpg">asyncpg</a>, a library for asynchronous PostgreSQL database access in Python. It boasts impressive performance, includes connection pooling for optimized resource utilization, facilitates seamless transaction management, supports advanced data types, and seamlessly integrates with SQLAlchemy.</p><p><a href="https://docs.pytest.org/en/7.4.x/"><strong>Pytest</strong></a><strong> — </strong>a simple and intuitive way to write tests for your Python code. It has easy test discovery, beautifully expressive syntax, extensive fixture support, and with some little tricks, it can test async code effortlessly.</p><h3>Creating a Basic Project Structure</h3><p>First and foremost, let’s create a basic project structure to keep your code clean and scalable. This crucial initial step will save you a lot of time (and trouble) when you want to extend your project and collaborate with other developers.</p><p>The project setup will resemble the directory structure found below — and the entire code for this project can be found on <a href="https://github.com/LTMullineux/fastapi-snippets/tree/main/00-ultimate-fastapi-project-setup">GitHub</a>, along with other great FastAPI snippets:</p><pre><br># https://github.com/LTMullineux/fastapi-snippets/tree/main/00-ultimate-fastapi-project-setup<br>./<br>  docker-compose.yml<br>  .dockerignore<br>  -&gt; /app<br>      __init__.py<br>      .env.local<br>      requirements.txt<br>      requirements-dev.txt<br>      Dockerfile<br>      pytest.ini<br>      -&gt; /api<br>          __init__.py<br>          gunircorn_config.py<br>          server.py<br>          -&gt; /routes<br>              __init__.py<br>              -&gt; /v1<br>                  __init__.py<br>                  user.py<br>      -&gt; /core<br>          __init__.py<br>          config.py<br>      -&gt; /crud<br>          __init__.py<br>          user.py<br>      -&gt; /db<br>          __init__.py<br>          session.py<br>      -&gt; /models<br>          __init__.py<br>          base.py<br>          user.py<br>      -&gt; /tests<br>          __init__.py<br>          conftest.py<br>          -&gt; /crud<br>              __init__.py<br>              test_user.py<br>          -&gt; /routes<br>              __init__.py<br>              conftest.py<br>              -&gt; /v1<br>                  __init__.py<br>                  test_user.py<br>      <br>  -&gt; /postgres<br>      -&gt; /docker-entrypoint-initdb.d<br>  -&gt; /scipts<br>      run-dev.sh<br>      run-test.sh</pre><p>With the basic project structure set up, you’re now ready to jump into the development environment!</p><p>We’ll go through all of the parts of this directory structure so that you can learn how the modules work together to enable a seamless developer experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DCeTPNx-zVSND_jT" /><figcaption>Photo by <a href="https://unsplash.com/@carrier_lost?utm_source=medium&amp;utm_medium=referral">Ian Taylor</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Building the Development Environment with Docker Compose</h3><p>To begin setting up the development environment, you’ll use Docker and Docker Compose to allow for isolated and repeatable tests and easy development.</p><p>This will prevent you from falling into <em>dependency hell</em> and avoid hearing this common phrase, “<em>Well, it works on my machine!</em>” 😡</p><p>Follow these 4 steps to create a streamlined development environment:</p><ol><li>Defining the Shared Environment Variables</li><li>Writing the Docker Compose Configuration with YAML anchors</li><li>Writing a Multi-Stage Python Dockerfile</li><li>Creating Helper Scripts for Running Tests and the Development Environment</li></ol><h4>Defining the Shared Environment Variables</h4><p>When using Docker Compose services, having a shared environment for both the test and development environments can be beneficial to streamline the building process and promote consistency between the two environments.</p><p>Create an environment file ./app/.env.local like the one below:</p><pre># ./app/.env.local<br>APP_HOST=&quot;0.0.0.0&quot;<br>APP_PORT=&quot;8000&quot;<br>POSTGRES_USER=&quot;postgres&quot;<br>POSTGRES_PASSWORD=&quot;postgres&quot;<br>POSTGRES_DB=&quot;postgres&quot;<br>POSTGRES_PORT=&quot;5432&quot;<br>POSTGRES_ECHO=&quot;false&quot;<br>POSTGRES_POOL_SIZE=&quot;5&quot;</pre><p>From here, any additional environment variables will be injected directly into the compose file to configure our specific services.</p><h4>Writing the Docker Compose Configuration</h4><p>To keep the Docker Compose file as clean as possible, make use of <a href="https://medium.com/@kinghuang/docker-compose-anchors-aliases-extensions-a1e4105d70bd">YAML anchors</a>. These allow you to define configurations once in YAML files and then use them as many times as needed.</p><p>Perfect for a DRY (<em>don’t repeat yourself</em>) Docker Compose file! 🚱</p><p>You’ll use anchors for 2 services:</p><ul><li>Postgres database x-postgres-base</li><li>FastAPI App x-app-base</li></ul><p>Using these, you can set up identical environments for testing and development, injecting any extra functionality as needed. These can even be further reused if you happen to be running staging, benchmarking, or production environments with the same Docker configurations.</p><p>Additionally, you’ll use <a href="https://docs.docker.com/compose/profiles/">Docker Compose profiles</a> to link services for the same function to easily spin up and down environments. In the compose file below, we have two profiles:</p><p>The test profile:</p><ul><li>Consisting of a Postgres container and an app container.</li><li>Both of these receive the environment file. The host for the Postgres container will be the name of the service postgres-test, which is why we set the environment variable POSTGRES_HOST=postgres-test in the app-test service.</li><li>Both share the same named network test so the testing environment is completely isolated from the other services.</li><li>Along with this, no external ports are mapped. We can have the dev services up and running while still being able to run the tests at the same time without interference between the two environments.</li><li>The postgres-test service does not have any volumes mounted. When we test, we want to spin up the containers, run tests, and shut them down — we don’t need to persist any data.</li><li>The app-test service has a volume bound to the ./app so that tests can be run without having to rebuild the app image every time.</li><li>The app-test service also has a depends_on to allow the postgres-test service to become healthy before we start running the tests via the command sh -c &quot;python -m pytest -s -vv&quot;</li></ul><p>The dev profile:</p><ul><li>The dev environment is very similar to the test one (hence the templating with YAML anchors 😃)</li><li>Again, give the services a named network dev so they can only communicate with each other.</li><li>This time though we map the ports and expose them so we can interact with the application from our local machine.</li><li>The postgres-dev service has one volume mount ./postgres/docker-entrypoint-initdb.d/:/docker-entrypoint-initdb.d/ so that we can place scripts or Postgres dumps in this directory that will be run when the service starts up, see <em>Initialization scripts</em> in the Postgres Docker documentation <a href="https://hub.docker.com/_/postgres">here</a>.</li><li>It also gets a named volume pgdata-dev that maps to the Postgres data directory to allow you to persist the data in the service. With this, the scripts and dumps in ./postgres/docker-entrypoint-initdb.d don’t have to run every time the service starts.</li><li>For the app-dev container, the main change is the command. This time, you start a FastAPI app with <a href="https://www.uvicorn.org/">Uvicorn</a> and expose it to localhost on port 8000. In production, you’ll want this running behind something more substantial like <a href="https://gunicorn.org/">Gunicorn</a>.</li></ul><p>Taking into account the above, your./docker-compose.yml file should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/318dc0b7936557f109a8fe317d907343/href">https://medium.com/media/318dc0b7936557f109a8fe317d907343/href</a></iframe><h4>Writing a Multi-Stage Python Dockerfile</h4><p>To keep the size of your FastAPI Dockerfile to a minimum, use a multi-stage build.</p><p>Multi-stage Docker builds are great because it reduces the number of dependencies and unnecessary packages in the image, hence reducing the size of the final image.</p><p>And smaller images mean faster transfer and start-up times when you run the application, especially when running applications in the cloud🚀.</p><p>In the builder image, you’ll pull the slim Python image, install the requirements, and optionally install the development requirements if the build argument ENV=&quot;test&quot; is passed.</p><p>Once the builder image is made, you can use it as the base for the main image, copy over the compiled Python libraries, and finally copy the actual application code into the main image.</p><p>The multi-stage Dockerfile in ./app/Dockerfile should look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a88a9e06763b9ee84e754f9970a11896/href">https://medium.com/media/a88a9e06763b9ee84e754f9970a11896/href</a></iframe><p>To save space on any production images, don’t install development and testing dependencies into them. In the image definition, only install the development dependencies when the Docker build argument ENV=test is passed, which you do in the Docker Compose file for app-test.</p><p>The separate requirements files for production (./app/requirements.txt) and development (./app/requirements-dev.txt) should look like this:</p><pre># ./app/requirements.txt<br>fastapi<br>pydantic[email]<br>uvicorn[standard]<br>sqlmodel<br>gunicorn<br>asyncpg<br>SQLAlchemy<br>uuid7</pre><pre>#./app/requirements-dev.txt<br># formatting<br>ruff<br>black<br>isort<br><br># testing<br>httpx<br>pytest<br>pytest-asyncio<br>pytest-timeout</pre><h4>Creating Helper Scripts for Running Development and Tests</h4><p>To save time on the command line, create two helper scripts.</p><p>The first /scripts/run-tests.sh will start the app-test service in the Docker Compose file and run the Pytest command.</p><p>The Docker Compose process will automatically spin up the postgres-test image first because of the depends_on flag and wait for it to be healthy before running the tests.</p><p>Once the tests have run, the script calls down on all the services in the test profile and removes the volumes created during the testing process. This keeps everything nice and clean.</p><pre># ./scripts/run-tests.sh<br>pytest_args=$*<br>docker compose -f docker-compose.yml run --rm app-test $pytest_args<br>docker compose -f docker-compose.yml --profile test down --volumes</pre><p>The second ./scripts/run-dev.sh is very simple — just a little helper to fire up the dev environment.</p><pre># ./scripts/run-dev.sh<br>docker compose -f docker-compose.yml --profile dev up &quot;$@&quot;</pre><p>Any additional arguments for Docker Compose can be passed through on the command line when you run this script.</p><p>For example, if you need to only start the development database in detached mode, you can run the following from the command line:</p><pre>bash scripts/run-dev.sh postgres-dev -d</pre><p>At this point, you’ve successfully set up our Docker Compose environment with your code correctly mounted and environments configured.</p><p>Now, it’s time to start building out our FastAPI application!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_IZdgLwiF5t5OWUR" /><figcaption>Photo by <a href="https://unsplash.com/@badgerblack?utm_source=medium&amp;utm_medium=referral">Kaur Kristjan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Defining Global Application Settings</h3><p>Pydantic allows you to ensure your application settings are defined in one place and one place only (<em>stay DRY!</em>).</p><p>Therefore, in ./app/core/config.py, create a class that inherits from Pydantic’s <a href="https://docs.pydantic.dev/latest/usage/pydantic_settings/#usage">BaseSettings</a> that can parse out environment variables using strict types.</p><p>If you want to access the application settings anywhere in the app, all you have to do is import the settings from config.py.</p><p>You’ll also be able to generate the ASYNC_POSTGRES_URI on the fly using the handy Pydantic validator decorator and <a href="https://docs.pydantic.dev/latest/api/networks/#pydantic.networks.PostgresDsn">use strict type checking on it</a>.</p><p>Below is how your file should look:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/985fb9c43684526c8c0df2e19619cd95/href">https://medium.com/media/985fb9c43684526c8c0df2e19619cd95/href</a></iframe><h3>Creating Async SQLAlchemy Database Sessions</h3><p>To take full advantage of the speed of FastAPI, you have to make it as asynchronous as possible so that incoming requests aren’t blocked by hanging database calls.</p><p>To allow the app to talk to Postgres asynchronously, create an async <a href="https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html">SQLAlchemy engine</a> with the async driver, asyncpg, which was already installed as part of the requirements.</p><p>In SQLAlchemy, the engine is responsible for establishing and managing the connection pool, executing SQL statements directly, and handling the low-level details of database interaction.</p><p>For good measure, create an async engine and define a pool size of connections, with a minimum of 5 connections, for your project.</p><p>Additionally, a session represents a transactional unit of work within the application. The session provides a higher-level abstraction compared to the engine, as it abstracts away the database connection management and provides a more object-oriented approach to working with data.</p><p>Your engine and session handlers are defined in ./app/db/session.py and should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf3e07bf51cf6b763c0deaf6729c848a/href">https://medium.com/media/cf3e07bf51cf6b763c0deaf6729c848a/href</a></iframe><p>Furthermore, you’ll need to create a <a href="https://fastapi.tiangolo.com/tutorial/dependencies/">FastAPI dependency</a> that will open and close database transactions to use the session. This way, you can separate requests into a single unit of work that are isolated from each other.</p><p>To do this, async def get_session() is used to create an async session on one of the connections of your engine and yield it to another function as a dependency. Once the function is finished, it will yield back and the session is closed.</p><h3>Testing FastAPI with Pytest</h3><p>Pytest is the go-to library for testing any Python project, and FastAPI applications are no different. It’s simple to use, flexible, and has a great fixture system as well as a wide community of developers.</p><p>To guide our tests and add some more color to them we will use a ./app/pytest.ini to customize the Pytest configuration and output — just one of the many great things about Pytest! 👌</p><pre>[pytest]<br>testpaths = tests<br>python_files = test_*.py<br>asyncio_mode = auto<br>timeout = 3<br>addopts = -vv --disable-warnings --durations=10 --durations-min=1.0</pre><p>The key highlights from the file are:</p><ul><li>asyncio_mode = auto tells Pytest to run the async test functions and methods we define.</li><li>timeout = 100 tells Pytest to stop with a test after 3 seconds have passed, useful to quickly catch hanging tests.</li><li>adopts = ... allows you to pass some more CLI arguments to Pytest, such as disabling warnings and showing the top 10 tests that take more than 1 second to run.</li></ul><h4>Transactional Async Database Unit Tests with SQLAlchemy</h4><p>Because of the asynchronous nature of your application, it’s necessary to set up an asynchronous testing infrastructure.</p><p>Additionally, there are a number of other reasons to create transactional database unit tests:</p><ul><li><strong>Isolation </strong>— Transactions allow tests to run in isolation.</li><li><strong>Consistency and Clean-Up </strong>— Because tests run in transactions, you can easily roll them back in the Pytest fixtures regardless of whether the test passes or fails. This ensures that the database remains unchanged after the test, avoiding the need for explicit test clean-up.</li><li><strong>Testing in Parallel </strong>— Because each unit test is done in isolation from any other test, you can even run them in parallel with this approach if needed, without worrying about data collision issues.</li><li><strong>Faster Speed —</strong> Transactions are generally faster than traditional approaches, such as recreating the database for each test. Starting a new transaction for each test is a lightweight and efficient process, reducing the overhead of setting up and tearing down the database.</li></ul><p>To allow asynchronous unit testing with SQLAlchemy, Pytest, and Postgres, you’ll need the following three Pytest fixtures:</p><ul><li>The event_loop fixture is scoped to the entire testing session and allows Pytest to only have one active event loop for the entirety of the test run. The built-in event loop fixture with pytest-asyncio is function-scoped by default and using it will cause Pytest to error with lots of <em>loop closed/open errors</em>.</li><li>The engine fixture will drop and create the entire database and yield the created engine. This is scoped to the class level. This offers the best trade-off between testing speed and lines of code in the tests, but this could be scoped differently depending on your needs.</li><li>The final fixture session is maybe the most important. This connects the engine to Postgres, starts a transaction, then binds that connection to a session with a nested transaction. Nesting the transaction allows for the isolation mentioned above by allowing us to commit changes in the inner transaction so it’s only visible to the tests it is working with, but doesn’t fully commit data to the database as the outer transaction will never be committed.</li></ul><p>These fixtures are placed in ./app/tests/conftest.py:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9148efbbbce4636060ef92ea9d4a84ab/href">https://medium.com/media/9148efbbbce4636060ef92ea9d4a84ab/href</a></iframe><h4>Creating a FastAPI Testing Client</h4><p>To test the FastAPI endpoints, use of the httpx Python library that ships with an asynchronous client. With this client, you’re going to mount a FastAPI router that will be defined in the following sections.</p><p>The beauty of Pytest’s <a href="https://docs.pytest.org/en/6.2.x/fixture.html#conftest-py-sharing-fixtures-across-multiple-files">conftests is that they are scoped</a>, so they are only visible to testing files in or below it in the directory structure.</p><p>With this in mind, create a separate ./app/tests/routes/conftest.py that will hold a testing router to test the app’s endpoints.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2913b53d51c2383bb9209d3bdf0db018/href">https://medium.com/media/2913b53d51c2383bb9209d3bdf0db018/href</a></iframe><p>Using a class here will allow you to easily test a single router by subclassing this test class and attaching the router as a class attribute. You’ll be able to access the client fixture in all the test class methods efficiently and cleanly. It’ll also allow you to test one router at a time in isolation 👍.</p><p>Additionally, you can <a href="https://fastapi.tiangolo.com/advanced/testing-dependencies/">override the </a><a href="https://fastapi.tiangolo.com/advanced/testing-dependencies/">get_session dependency</a> with the testing session fixture from ./app/tests/conftest.py to get your beautiful transactional async tests.</p><p>No need to import anything from conftest files, Pytest does this automatically for you. 🙌</p><h3>Creating Schemas and Database Models with SQLModel</h3><p>Now that you’ve gained an understanding of the testing infrastructure, you can start to define your database tables and data schemas to build out a specific FastAPI application.</p><p>Let’s start with a bare-bones application with only one database model, a User.</p><p>Before adding the model, you’ll first learn how to segment the SQLModel logic into an extensible and composable format. Generally, you’ll want to have shared logic and configurations defined only once in a shared location (<em>DRY DRY DRY</em>).</p><p>In this simple application, you’ll create shared code using mixins. A mixin is used to extend the functionality of a class by “mixing in” or composing additional behavior from another class without using traditional inheritance, which might lead to a complex class hierarchy.</p><p>For this project, you’ll have two mixins and in ./app/models/base.py for a primary key id column and created_at and updated_at timestamp columns:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e10be2c26a22ce6e2f7f7734dc05e7e/href">https://medium.com/media/6e10be2c26a22ce6e2f7f7734dc05e7e/href</a></iframe><h4>Using UUID7 as a Primary Key in SQLModel and Postgres</h4><p>Looking closely at the data type of the id column above, you can find the uuid7 data type. As far as cool UUIDs go, this is the coolest — and it gives some special properties. See these references for more details:</p><ul><li><a href="https://www.toomanyafterthoughts.com/uuids-are-bad-for-database-index-performance-uuid7/">UUIDs Are Bad for Database Index Performance, enter UUID7</a></li><li><a href="https://www.cybertec-postgresql.com/en/unexpected-downsides-of-uuid-keys-in-postgresql/">Unexpected Downsides of UUID Keys in Postgresql</a></li></ul><h4>Defining User Models for Creation, Update, and API Responses</h4><p>Now, let’s create a simple collection of User models.</p><p>In SQLModel, when defining a model, there is a flag table. Setting this to false (as the default) will define a Pydantic-only model, but when it’s true it will define both a Pydantic and SQLAlchemy model.</p><p>The main benefits of SQLModel include lots of code saved and no need to worry about maintaining a separate models and schemas setup like you would if you used plain SQLAlchemy and Pydantic. 😍</p><p>First, create a UserBase that will be shared between the create data schema and the database table model, with a unique and indexed email field, first and last names, and an active flag.</p><p>You’ll also want to create a separate model for updating a User where all the fields are optional, so that users of the API can update a subset of the fields of the User model.</p><p>The UserResponse model takes the User and includes all columns from the database. This is the desired functionality in this example project, but you can imagine when it might be necessary that some columns shouldn’t be returned from the API (think passwords ⛔️).</p><p>Your model file ./app/models/user.py should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33a5fa47402a98f3b086ba4729a31835/href">https://medium.com/media/33a5fa47402a98f3b086ba4729a31835/href</a></iframe><p>All of your models should be Pydantic only with the exception of User — which includes the database-generated columns: id, created_at, and updated_at.</p><h3>CRUD: Create, Read, Update, and Delete</h3><p>In general, when building API applications you want to abstract the data access layer from the database and the application&#39;s business logic.</p><p>To keep things simple for this application, write some CRUD functions that perform the simple create, read, update, and delete operations on the database for the User model.</p><p>In larger applications, you’ll want to separate these out using a <a href="https://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/infrastructure-persistence-layer-design">repository pattern</a>, so that the data access layer of the application is abstracted and functionality can be shared between different model repositories.</p><h4>CRUD Tests</h4><p>As responsible engineers (<em>most of the time</em>), it’s best practice to do some test-driven development (TDD) and start with unit tests for our CRUD operations.</p><p>In ./app/tests/crud/user.py, write unit tests for 5 functions that will be created later:</p><ul><li>create_user(...) will take a UserCreate model and save it to the database</li><li>get_user(...) will fetch a user from the database via an id</li><li>get_user_by_email(...) will fetch a user from the database via an email</li><li>update_user(...) will take a UserUpdate model and update an existing user in the database with the fields from this model</li><li>delete_user(...) will delete a user via an id</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf6097a4b12e2e0e9904d864305a58c0/href">https://medium.com/media/bf6097a4b12e2e0e9904d864305a58c0/href</a></iframe><p>Now, let&#39;s run the tests via your helper script bash scripts/run-tests.sh. Because there are no functions yet, all of the tests should fail. ❌</p><p>No problem, let’s write the code for the functions!</p><h4>CRUD Functions</h4><p>The CRUD functions for this application are going to be very simple. In ./app.crud/user.py, add the five functions described in the previous section:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fa7a24714c7ae56030e6a2b57760479/href">https://medium.com/media/3fa7a24714c7ae56030e6a2b57760479/href</a></iframe><p>To maintain your performant application, all of your functions should be asynchronous.</p><p>Note: You have to explicitly commit all of your changes. In both the testing and production sessions dependency functions, we don’t have implicit committing in this application.</p><p>Now run tests again, and you should see that all test cases now pass. ✅</p><h3>Define API Routes</h3><p>So far we’ve set up the data models and CRUD functions. You can now begin to define your API endpoints with <a href="https://fastapi.tiangolo.com/tutorial/bigger-applications/">FastAPI’s APIRouter class</a>.</p><p>The advantages of using API routers include:</p><ul><li><strong>Modular Code Organization</strong> — API routers enable modular code organization by grouping API endpoints into separate logical units, representing specific features, resources, or related endpoints.</li><li><strong>Namespace Management </strong>— By defining namespaces for API endpoints, routers provide clarity and explicitness in understanding the relationships between different parts of our API with routing prefixes.</li><li><strong>Testing Isolation</strong> — API routers permit independent testing of each router’s endpoints, simplifying the creation of focused and dependable unit tests tailored to specific sections of your application.</li><li>Much much more like <em>horizontal scaling</em>, <em>easy team collaboration</em>, <em>documentation</em>, and <em>code maintainability</em>, …</li></ul><h4>FastAPI Routing and File Structure</h4><p>For your API endpoints, mirror the URL structure in the ./app/api/:</p><ul><li>All your endpoint logic is going to be at the directory path ./app/api and in the URL path {hostname}/api</li><li>It is good practice to use <a href="https://www.linkedin.com/advice/0/how-do-you-evaluate-impact-feedback-your-api-versioning#:~:text=Versioning%20your%20API%20allows%20you,developers%2C%20partners%2C%20or%20customers.">API versioning</a>, so start with version 1 at the directory path ./app/api/v1 that corresponds to the URL path {hostname}/api/v1. Later, if version 2 is needed, you can easily extend the directory structure to include ./app/api/v2/.</li><li>Finally, add our User resource to the directory path ./app/api/v1/user and the corresponding URL path {hostname}/api/v1/users</li></ul><p>To start, we create the base API application in ./app/api/server.py that contains the FastAPI application and attaches the main API endpoint router in ./app/api/routes (see below).</p><p>Add some extra pieces — such as a basic health check — and ensure that all the database tables created and mapped in SQLModel are present when the application starts up:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b9b62e133022046e481b4a51c47f8d0/href">https://medium.com/media/2b9b62e133022046e481b4a51c47f8d0/href</a></iframe><p>If any other global functionality such as CORS, API key security, etc. is required then it can also be added here.</p><p>Next, in ./app/api/routes/__init__.py, create an <a href="https://fastapi.tiangolo.com/tutorial/bigger-applications/#apirouter">APIRouter</a> and attach the version 1 router (<em>that will be created in the next step</em>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5db0aca9f40a837d0cbda85c7d990d90/href">https://medium.com/media/5db0aca9f40a837d0cbda85c7d990d90/href</a></iframe><p>The version 1 router is prefixed with/v1.</p><p>To this router, you will dynamically import all of the Python files in ./app/api/routes/v1/ listed in the routes tuple and attach the router from the imported file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3f75c55def451121abcf34eb4e23455/href">https://medium.com/media/c3f75c55def451121abcf34eb4e23455/href</a></iframe><p>When new resources are needed, just create a new resource Python file with its own router and add it to the routes tuple and it will be available in your endpoints.</p><h4>Defining the HTTP Methods for the Users Endpoint</h4><p>Up next is defining the endpoints for your User resource that will be found at the URL {hostname}/api/v1/users/.</p><p>In the file ./app/api/v1/user.py, create another APIRouter and attach your endpoint functions — these will be called:</p><ul><li>POST {hostname}/api/v1/users/create a user</li><li>GET {hostname}/api/v1/users/{id} get a user by ID</li><li>PATCH {hostname}/api/v1/users/{id} update a user by ID</li><li>DELETE {hostname}/api/v1/users/{id} delete a user by ID</li></ul><p>Using FastAPI’s dependency injection, accessing your database session is easily done by using the function get_session() function and the FastAPI helper function <a href="https://fastapi.tiangolo.com/tutorial/dependencies/">Depends</a>!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aefc9176030bf38f7904675fdb8b85f0/href">https://medium.com/media/aefc9176030bf38f7904675fdb8b85f0/href</a></iframe><h4>How to Test FastAPI Routes using Pytest and HTTPX</h4><p>Again, as responsible developers, let’s unit test your endpoints. The component parts have already been set up:</p><ul><li>Transactional async units tests against our Postgres database in ./app/tests/conftest.py</li><li>A base class testing router BaseTestRouter in ./app/tests/routes/conftest.py</li></ul><p>In ./app/tests/routes/v1/test_user.py, subclass the BaseTestRouter, import your router from ./app/api/routes/v1/users.py and attach it as the class attribute BaseTestRouter.router.</p><p>When Pytest instantiates the class for testing, any router attached via the class attribute will be available as a fixture to all test methods in the class.</p><p>The tests themselves are pretty simple — just making sure the endpoints do what is expected of them:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d7c8562b02fb8e4c1e7e203d1f58c96/href">https://medium.com/media/3d7c8562b02fb8e4c1e7e203d1f58c96/href</a></iframe><p>Finally, let’s run our tests again with our helper script:</p><pre>clear; bash scripts/run-tests.sh</pre><p>All of our CRUD and API route tests should pass with flying colors! 🎆</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hQ3SgCCJnD68mAZv" /><figcaption>Photo by <a href="https://unsplash.com/@glen_rushton?utm_source=medium&amp;utm_medium=referral">Glen Rushton</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Summary and Next Steps for Setting Up Your First FastAPI Project</h3><p>If you’ve made it this far, you’re ready to set up your first FastAPI project!</p><p>While this setup is by no means perfect, it should help you see how easy and extensible the framework can be.</p><p>As a reminder, with this setup, you’ll you get:</p><ul><li>The full benefits of a completely async FastAPI application ✅</li><li>Completely identical but isolated testing and development environments ✅</li><li>Scalable project structure; adding new models, CRUD, and routes is straightforward ✅</li><li>Asynchronous and transactional unit tests ✅</li></ul><p>On top of this, you can easily include:</p><ul><li>Linting, formatting, and static type checking using <a href="https://flake8.pycqa.org/en/latest/">flake8</a>, <a href="https://black.readthedocs.io/en/stable/">black</a>, <a href="https://pycqa.github.io/isort/">isort</a>, <a href="https://beta.ruff.rs/">ruff</a>, and <a href="https://mypy-lang.org/">mypy</a>.</li><li>Create staging, benchmarking and production deployments using the templates in Docker Compose.</li><li>Run CI tests in your favorite tool of choice as the tests are completely isolated thanks to our Docker Compose environments</li></ul><p>The complete code for this project, along with other FastAPI snippets and use cases can be found on <a href="https://github.com/LTMullineux/fastapi-snippets/tree/main/00-ultimate-fastapi-project-setup">Github</a>, feel free to drop a issue or a merge request in there.</p><p>I would love to hear any feedback you have or thoughts on what you’d do differently. Thank you for reading and happy developing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed0c6afea11b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>