<?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 Fedor GNETKOV on Medium]]></title>
        <description><![CDATA[Stories by Fedor GNETKOV on Medium]]></description>
        <link>https://medium.com/@gnetkov?source=rss-bd9eb418040f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Y0Ig4lYoYIgk7XmXpA773w.png</url>
            <title>Stories by Fedor GNETKOV on Medium</title>
            <link>https://medium.com/@gnetkov?source=rss-bd9eb418040f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:06:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gnetkov/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[Django ORM vs SQLAlchemy: A Practical Comparison with Real SQL Examples]]></title>
            <link>https://medium.com/@gnetkov/django-orm-vs-sqlalchemy-a-practical-comparison-with-real-sql-examples-9110dba91c56?source=rss-bd9eb418040f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9110dba91c56</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[sqlalchemy]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Fedor GNETKOV]]></dc:creator>
            <pubDate>Fri, 20 Feb 2026 07:58:54 GMT</pubDate>
            <atom:updated>2026-02-20T07:58:54.335Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s compare two of the most popular ORM libraries in Python: SQLAlchemy and Django ORM.</p><blockquote>The goal of this article is to compare how the same SQL query is written using <strong>SQLAlchemy</strong> and <strong>Django ORM</strong>, and then to compare how these two ORMs express that query.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o9gp0tIj3OKVCBXsU1F6QA.png" /></figure><p>ORM stands for Object Relational Mapper. In other words, it is a utility that allows you to work with programming language objects instead of writing raw SQL queries.</p><p>Django ORM is the default ORM of one of the most popular Python frameworks, Django.<br> SQLAlchemy is not just an ORM, but a full-featured SQL toolkit. The ORM in SQLAlchemy is only one of its layers, and the library is often used in projects based on FastAPI and Flask.</p><p>In this article, I will not touch on performance or speed. <strong>I will focus only on code, ease of use, and code readability of these two ORMs.</strong></p><h3>Test database</h3><p>Let’s create a small test database that we will use for the queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W5Av_VmZ95BOR61iMUz97A.png" /></figure><p>Four simple tables.</p><ul><li><strong>company</strong> — companies, user always belongs to a company (foreign key user.company_id). Additionally, each company has an admin user (foreign key company.user_admin_id).</li><li><strong>user</strong> — users, application users with basic fields such as email and a reference to the company they belong to.</li><li><strong>order</strong> — orders, a table that represents a many-to-many relationship between users and items.</li><li><strong>item</strong> — items, for example products that users can order.</li></ul><p>I created the database and populated it with some test data.<br>Now let’s write the same raw SQL queries using different ORMs.</p><h3>Example 1</h3><p>Users with no orders.</p><p>Django ORM:</p><pre>queryset = (<br>  User.objects.filter(orders__isnull=True)<br>  .values(&quot;id&quot;, &quot;email&quot;, &quot;company__name&quot;)<br>  .order_by(&quot;id&quot;)<br>)</pre><p>SQLAlchemy:</p><pre>stmt = (<br>    select(<br>        User.id,<br>        User.email,<br>        Company.name.label(&quot;company__name&quot;),<br>    )<br>    .select_from(User)<br>    .outerjoin(Order, User.id == Order.user_id)<br>    .outerjoin(Company, User.company_id == Company.id)<br>    .where(Order.id.is_(None))<br>    .order_by(User.id.asc())<br>)</pre><p>These queries generate the same raw SQL query:</p><pre>SELECT user.id, user.email, company.name AS company__name<br>FROM user<br>LEFT OUTER JOIN order ON user.id = order.user_id<br>LEFT OUTER JOIN company ON user.company_id = company.id<br>WHERE order.id IS NULL<br>ORDER BY user.id ASC</pre><p>Django ORM uses positional ordering (ORDER BY 1), which is valid from a SQL perspective but can be less convenient when reading raw queries during debugging.</p><p>Now let’s compare the ORM expressions.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fyqk96%2F2%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fyqk96%2F2%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fyqk96%2Fplain-s.png%3Fv%3D2&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="740" frameborder="0" scrolling="no"><a href="https://medium.com/media/b765893222cd296afc1d93680852c279/href">https://medium.com/media/b765893222cd296afc1d93680852c279/href</a></iframe><h3>Example 2</h3><p>Items ordered, with order count and latest order time.</p><p>Django ORM:</p><pre>queryset = (<br>    Item.objects<br>    .values(&quot;id&quot;, &quot;name&quot;)<br>    .annotate(<br>        order_count=Count(&quot;orders&quot;),<br>        last_order_at=Max(&quot;orders__created_at&quot;),<br>    )<br>    .filter(order_count__gt=0)<br>    .order_by(&quot;-order_count&quot;, &quot;id&quot;)<br>)</pre><p>SQLAlchemy:</p><pre>order_count = func.count(Order.id)<br><br>stmt = (<br>    select(<br>        Item.id,<br>        Item.name,<br>        order_count.label(&quot;order_count&quot;),<br>        func.max(Order.created_at).label(&quot;last_order_at&quot;),<br>    )<br>    .select_from(Item)<br>    .outerjoin(Order, Item.id == Order.item_id)<br>    .group_by(Item.id, Item.name)<br>    .having(order_count &gt; 0)<br>    .order_by(order_count.desc(), Item.id)<br>)</pre><p>These queries generate the same raw SQL query:</p><pre>SELECT<br>    item.id,<br>    item.name,<br>    COUNT(&quot;order&quot;.id) AS order_count,<br>    MAX(&quot;order&quot;.created_at) AS last_order_at<br>FROM item<br>LEFT OUTER JOIN &quot;order&quot;<br>    ON item.id = &quot;order&quot;.item_id<br>GROUP BY<br>    item.id,<br>    item.name<br>HAVING<br>    COUNT(&quot;order&quot;.id) &gt; 0<br>ORDER BY<br>    order_count DESC,<br>    item.id;</pre><p>Now let’s compare the ORM expressions.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FuVjwc%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FuVjwc%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FuVjwc%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="710" frameborder="0" scrolling="no"><a href="https://medium.com/media/54cdbafc4c1043b1b566b23ceaeafd71/href">https://medium.com/media/54cdbafc4c1043b1b566b23ceaeafd71/href</a></iframe><h3>Example 3</h3><p>Company stats: users, orders, and revenue from ordered items.</p><p>Django ORM:</p><pre>queryset = (<br>    Company.objects<br>    .values(&quot;id&quot;, &quot;name&quot;)<br>    .annotate(<br>        user_count=Count(&quot;users&quot;, distinct=True),<br>        order_count=Count(&quot;users__orders&quot;, distinct=True),<br>        total_revenue=Sum(&quot;users__orders__item__price&quot;),<br>    )<br>    .order_by(&quot;id&quot;)<br>)</pre><p>SQLAlchemy:</p><pre>stmt = (<br>    select(<br>        Company.id,<br>        Company.name,<br>        func.count(distinct(User.id)).label(&quot;user_count&quot;),<br>        func.count(distinct(Order.id)).label(&quot;order_count&quot;),<br>        func.sum(Item.price).label(&quot;total_revenue&quot;),<br>    )<br>    .select_from(Company)<br>    .outerjoin(User, Company.id == User.company_id)<br>    .outerjoin(Order, User.id == Order.user_id)<br>    .outerjoin(Item, Order.item_id == Item.id)<br>    .group_by(<br>        Company.id,<br>        Company.name,<br>    )<br>    .order_by(Company.id)<br>)</pre><p>Now let’s compare the ORM expressions.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FG231Y%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FG231Y%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FG231Y%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="638" frameborder="0" scrolling="no"><a href="https://medium.com/media/32340291030d3acfd4c7a1926f9d64c9/href">https://medium.com/media/32340291030d3acfd4c7a1926f9d64c9/href</a></iframe><h3><strong>Conclusion</strong></h3><p>I compared Django ORM and SQLAlchemy. Here are the key takeaways:</p><ul><li>Django ORM code is usually <strong>shorter</strong> than SQLAlchemy code.</li><li>Django ORM relies heavily on <strong>strings and runtime checks</strong>, whereas SQLAlchemy (especially in the 2.0 style) integrates <strong>much better with static analysis and typing.</strong></li><li>SQLAlchemy code is <strong>very close to plain SQL</strong>, while Django ORM has its own syntax and rules. This is a major advantage for <strong>SQLAlchemy: if you know SQL, SQLAlchemy code is much easier to read and reason about.</strong></li><li>In SQLAlchemy, the developer <strong>explicitly specifies the join type</strong>, whereas in Django ORM the join is <strong>derived implicitly according to ORM rules.</strong> In my experience with Django ORM, I’ve encountered unpleasant cases where a small change in method order silently changed an OUTER JOIN into an INNER JOIN.</li><li>Overall, Django ORM involves more “<em>magic”</em> and implicit behavior, while <strong>SQLAlchemy stays much closer to explicit SQL semantics.</strong></li></ul><p>So, which one is better: Django ORM or SQLAlchemy? There’s no universal answer — it’s a matter of personal preference and project needs. <strong>What do you prefer?</strong></p><h3>Links</h3><ol><li><a href="https://docs.djangoproject.com/">https://docs.djangoproject.com/</a> — Official documentation Django.</li><li><a href="https://www.sqlalchemy.org/">https://www.sqlalchemy.org/</a> — Official site of SQLAlchemy.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9110dba91c56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pandas: Key Methods You Need to Know]]></title>
            <link>https://medium.com/@gnetkov/pandas-cheat-sheet-key-methods-you-need-to-know-f3cf2db503e4?source=rss-bd9eb418040f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3cf2db503e4</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Fedor GNETKOV]]></dc:creator>
            <pubDate>Thu, 15 May 2025 07:09:32 GMT</pubDate>
            <atom:updated>2025-05-16T18:32:38.948Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Pandas is the most popular Python library for data processing and analysis.</strong> In this article, I have tried to gather the most commonly used methods when working with pandas, creating something like a pandas cheat sheet. Save it to not lose it.</p><h3>Main features of pandas:</h3><ul><li><strong>Data loading and saving:</strong> Support for CSV, Excel, SQL, JSON, and other formats.</li><li><strong>Data processing:</strong> Filtering, sorting, grouping, aggregation.</li><li><strong>Data cleaning:</strong> Removing missing values, replacing values.</li><li><strong>Data analysis:</strong> Statistical calculations and pivot tables.</li></ul><p>In this article, <strong>we will discuss</strong>:</p><ul><li>Loading and saving data</li><li>Quick DataFrame overview</li><li>Data filtering and selection</li><li>Sorting</li><li>Creating and modifying columns</li><li>Aggregations and groupings</li><li>Handling missing values</li><li>Removing duplicates</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kQRT9XEhPqS_ZuVzJbYgcg.png" /></figure><p>Before we start, let’s remember the two main data structures in pandas.</p><p><strong>Main data structures of pandas:</strong></p><ul><li><strong>DataFrame</strong> — A two-dimensional labeled data structure (similar to an Excel table).</li><li><strong>Series</strong> — A one-dimensional labeled array (similar to a row in a table).</li></ul><h3>Loading and saving data</h3><p>Reading/writing a CSV file:</p><pre>import pandas as pd<br><br>df: pd.DataFrame = pd.read_csv(&quot;input_file.csv&quot;, sep=&quot;;&quot;)<br>df.to_csv(&#39;output_file.csv&#39;, sep=&#39;;&#39;, index=False)</pre><p>This reads/writes a CSV file with a semicolon delimiter and without the row index (i.e., without the first column containing the row number).</p><p>Pandas cannot handle datasets larger than available memory, so it may be <strong>useful to read the file in chunks</strong>.</p><pre>chunk: pd.DataFrame<br>for chunk in pd.read_csv(&quot;input_file.csv&quot;, chunksize=1000):<br>    print(f&quot;Processed a chunk with {len(chunk)} rows&quot;)</pre><p>It is useful to specify column types immediately <strong>to save memory and reduce execution time</strong>.</p><pre>dtype_spec: dict = {<br>    &quot;name&quot;: &quot;string&quot;,<br>    &quot;price&quot;: &quot;int16&quot;,<br>    &quot;quantity&quot;: &quot;int16&quot;,<br>}<br>df: pd.DataFrame = pd.read_csv(&quot;input_file.csv&quot;, sep=&quot;,&quot;, dtype=dtype_spec)</pre><p>Reading/writing an Excel file:</p><pre>df: pd.DataFrame = pd.read_excel(&quot;input.xlsx&quot;, sheet_name=&quot;Sheet_name_1&quot;)<br>df.to_excel(&quot;output_file.xlsx&quot;, sheet_name=&#39;Sheet_name_1&#39;, index=False)</pre><p>Reading/writing a Parquet file:</p><pre>df: pd.DataFrame = pd.read_parquet(&quot;input_file.parquet&quot;)<br>df.to_parquet(&quot;output_file.parquet&quot;)</pre><p>Reading/writing JSON:</p><pre># Read a json string<br>df: pd.DataFrame = pd.read_json(StringIO(&#39;{&quot;A&quot;: [1, 3], &quot;B&quot;: [2, 4]}&#39;))<br># Read a json file<br>df = pd.read_json(&quot;input_file.json&quot;)<br>df.to_json(&quot;output_file.json&quot;)</pre><p>Here, input.json and output.json have the following format:</p><pre>{<br>  &quot;name&quot;: {&quot;0&quot;: &quot;apple&quot;, &quot;1&quot;: &quot;orange&quot;, &quot;2&quot;: &quot;bread&quot;},<br>  &quot;price&quot;: {&quot;0&quot;: &quot;2500&quot;, &quot;1&quot;: &quot;2000_invalid_int&quot;, &quot;2&quot;: &quot;2700&quot;},<br>  &quot;quantity&quot;: {&quot;0&quot;: 2, &quot;1&quot;: 100, &quot;2&quot;: 50}<br>}</pre><h4>Quick DataFrame overview</h4><p>First/last 5 rows:</p><pre>print(df.head())<br>print(df.tail())<br><br>&quot;&quot;&quot;<br>Output:<br>     name  price  quantity<br>0   apple   2500         2<br>1  orange   2000       100<br>2   bread   2700        50<br>&quot;&quot;&quot;</pre><p>Table size (rows, columns):</p><pre>print(df.shape)<br>&quot;&quot;&quot;<br>Output:<br>(4, 3)<br>&quot;&quot;&quot;</pre><p>Column types, null count, memory usage:</p><pre>print(df.info())<br><br>&quot;&quot;&quot;<br>Output:<br>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 4 entries, 0 to 3<br>Data columns (total 3 columns):<br> #   Column    Non-Null Count  Dtype <br>---  ------    --------------  ----- <br> 0   name      4 non-null      string<br> 1   price     4 non-null      int16 <br> 2   quantity  4 non-null      int16 <br>dtypes: int16(2), string(1)<br>memory usage: 180.0 bytes<br>None<br>&quot;&quot;&quot;<br></pre><p>Basic statistics (count number of non-NA/null observations, maximum and minimum of the values, mean of the values, standard deviation):</p><pre>print(df.describe())<br>&quot;&quot;&quot;<br>Output:<br>             price    quantity<br>count     4.000000    4.000000<br>mean   2425.000000   38.500000<br>std     298.607881   46.829478<br>min    2000.000000    2.000000<br>25%    2375.000000    2.000000<br>50%    2500.000000   26.000000<br>75%    2550.000000   62.500000<br>max    2700.000000  100.000000<br>&quot;&quot;&quot;<br></pre><h4>Data filtering and selection</h4><p>Access a group of rows and columns by index:</p><pre>s: pd.Series = df.loc[1]<br>df: pd.DataFrame = df.loc[[1, 2]]<br>df: pd.DataFrame = df.loc[0:2]</pre><p>In this example with loc method, the index is not the row position in the array; <strong>it can also be a string</strong>.</p><p>Integer-location based indexing:</p><pre>s: pd.Series = df.iloc[1]<br>df: pd.DataFrame = df.iloc[[1, 2]]<br>df: pd.DataFrame = df.iloc[0:2]</pre><p>Unlike loc, iloc is used for selecting a series or DataFrame <strong>by integer-location.</strong></p><p>Boolean filter:</p><pre>new_df: pd.DataFrame = df[df[&quot;price&quot;] &gt; 2100]</pre><p>This selects only rows where the price is greater than 2100.</p><p>Notice the type of filter: <strong>the comparison condition returns a Series</strong>, which is a<strong> vector of boolean values</strong>. Each boolean value indicates whether the corresponding row satisfies the condition or not.</p><pre>filter: pd.Series = df[&quot;price&quot;] &gt; 2100<br>print(filter)<br>&quot;&quot;&quot;<br>Output:<br>0     True<br>2    False<br>3     True<br>Name: price, dtype: bool<br>&quot;&quot;&quot;<br></pre><p>SQL-like filter:</p><pre>new_df: pd.DataFrame = df.query(&quot;price &gt; 2100 and name == &#39;apple&#39;&quot;)</pre><p>Select only rows where the price is greater than 2100 and the name is “apple”.</p><p>Filter IN:</p><pre>df = df[df[&quot;name&quot;].isin([&quot;apple&quot;, &quot;orange&quot;])]</pre><p>Filter BETWEEN:</p><pre>df = df[df[&quot;price&quot;].between(2100, 2600)]</pre><p>It is important to remember that filters return a Series, <strong>which can be used to perform logical operations</strong>: &amp; for &quot;and&quot;, | for &quot;or&quot;, ~ for &quot;not&quot;.</p><h4>Sorting</h4><pre>df.sort_values([&quot;name&quot;, &quot;price&quot;], ascending=[True, True], inplace=True)</pre><p>First, sort by price, then by name.</p><h4>Creating and modifying columns</h4><p>Creating columns:</p><pre>df[&quot;total&quot;] = df[&quot;price&quot;] * df[&quot;quantity&quot;]<br>df = df.assign(vat=lambda x: x.price * 0.2)<br>df[&quot;type&quot;] = &quot;FRUIT&quot;</pre><p>Updating a column with condition:</p><pre># Multiple conditions with logical AND<br>condition: pd.Series = (<br>    (df[&quot;name&quot;] == &quot;apple&quot;) &amp; <br>    (df[&quot;price&quot;] &lt; 2600)<br>)<br># Multiple conditions with logical OR<br>condition: pd.Series = (<br>    (df[&quot;name&quot;] == &quot;apple&quot;) | <br>    (df[&quot;name&quot;].isin([&quot;orange&quot;]))<br>)<br># Update values in column where condition is True<br>df.loc[condition, &#39;price&#39;] = 3000</pre><p>Updating a column using iterating on dataframe (less efficient then vectorized approach, so not recommended):</p><pre>for idx, row in df.iterrows():<br>    if row[&quot;name&quot;] == &quot;apple&quot;:<br>        df.loc[idx, &quot;price&quot;] = 3000</pre><p>Renaming a column:</p><pre>df.rename(columns={&quot;price&quot;: &quot;price_without_vat&quot;}, inplace=True)</pre><p>Deleting a column:</p><pre>df.drop(columns=[&quot;quantity&quot;], inplace=True)</pre><h4>Aggregations and grouping:</h4><p>Grouping:</p><pre>df.groupby(&quot;type&quot;)[&quot;price&quot;].sum()</pre><p>Merging two DataFrames:</p><pre>pd.merge(users, orders, on=&quot;user_id&quot;, how=&quot;left&quot;)<br># Or<br>df1.join(df2, on=&quot;key&quot;)</pre><h4>Handling missing values</h4><p>Count NaN values per column:</p><pre>series: pd.Series = df.isna().sum()</pre><p>Total NaN count:</p><pre>number: numpy.int64 = df.isna().sum().sum()</pre><p>Filling NA/NaN values:</p><pre>df[&quot;col&quot;].fillna(0, inplace=True)</pre><h4>Removing duplicates</h4><p>Delete duplicates:</p><pre>df.drop_duplicates(subset=[&quot;name&quot;], keep=&quot;last&quot;, inplace=True)</pre><h3>Conclusion</h3><p>This was a brief overview of the basic and most frequently used pandas functions. You can find more information and complete documentation on the official package website.</p><p><strong>Useful links:</strong></p><ol><li><a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/10min.html">User guide “10 minutes to pandas”</a></li><li><a href="https://pandas.pydata.org/pandas-docs/stable/reference/index.html">Official API reference of Pandas</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3cf2db503e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boost Your Python Code Quality with Pydantic Validation]]></title>
            <link>https://medium.com/@gnetkov/boost-your-python-code-quality-with-pydantic-validation-e418001192ec?source=rss-bd9eb418040f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e418001192ec</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[pydantic]]></category>
            <dc:creator><![CDATA[Fedor GNETKOV]]></dc:creator>
            <pubDate>Sun, 16 Feb 2025 13:27:57 GMT</pubDate>
            <atom:updated>2025-02-16T13:27:57.814Z</atom:updated>
            <content:encoded><![CDATA[<p>Python is a dynamically typed programming language. Dynamic typing has its advantages, such as ease of development, but also drawbacks, like the <strong>unpredictability of variable types</strong>. How can we ensure variable types and formats? By using static code analyzers and validating data.</p><p>In many applications, it is necessary to validate both variable types and values. There are numerous Python packages for this purpose, including Pydantic, Marshmallow, Cerberus, Voluptuous, Schematics, and others.</p><blockquote>In this article, we will focus on the most popular package — Pydantic.</blockquote><p>Pydantic is a Python library that simplifies data validation and transformation by leveraging Python type hints.</p><h3>Why has this library become so popular, and why do I recommend using it?</h3><ul><li>It utilizes Python type hints.</li><li>It is used in popular backend frameworks such as <a href="https://fastapi.tiangolo.com/">FastAPI </a>and <a href="https://django-ninja.dev/">Django Ninja</a>.</li><li>It allows the creation of complex custom data validators.</li><li>It provides detailed error messages when validation fails. When data does not meet the expected schema (due to incorrect type, format, or other constraints), Pydantic raises a ValidationError with clear and informative details about the issue.</li><li>It supports nested models, enabling the creation of complex structures (e.g., List[AnotherModel], nested models, dictionaries, etc.), with Pydantic recursively validating all components.</li></ul><p>I have tried to compile <strong>the most useful and frequently used features of Pydantic based on my experience</strong> in this article. However, this is not a comprehensive review of all Pydantic’s capabilities; you can find the full functionality in the <a href="https://docs.pydantic.dev/latest/">official documentation</a>.</p><h4>In this article, we will explore following examples of using Pydantic:</h4><ul><li>Input data validation in FastAPI.</li><li>Input data validation in FastAPI with request body.</li><li>Output data validation in FastAPI.</li><li>Creating a response from an SQLAlchemy model.</li><li>Creating a response from an SQLAlchemy model with a parent relationship.</li><li>CSV file data validation.</li><li>Creating and reusing a custom validator.</li><li>Other Validation Methods in Pydantic.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5kTdqwfaZnCO3uJGW2RPbA.png" /><figcaption>Image generated by AI.</figcaption></figure><h3>Input Data Validation in FastAPI</h3><blockquote>The FastAPI framework uses Pydantic for input data validation.</blockquote><p>Moreover, FastAPI will generate Swagger documentation based on the Pydantic models.</p><pre>from fastapi import FastAPI<br><br>app = FastAPI()<br><br>@app.get(&quot;/items/{item_id}&quot;)<br>def read_item(item_id: int, q: str | None = None):<br>    return {&quot;item_id&quot;: item_id, &quot;q&quot;: q}</pre><p>In this example, we use Python type hints to validate the path parameter item_id and the query parameter q.</p><ul><li>item_id must be an integer.</li><li>q is an optional parameter that can be either a string or None, with None as the default value.</li></ul><p>For instance, if I make a request with item_id=aa (a string instead of an integer), I will receive a response with a 422 status code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1N4Q7UhDti-b3t7j" /><figcaption>Swagger. Request with invalid data returns HTTP status code 422.</figcaption></figure><p>Thus, FastAPI, by using Pydantic for input data validation, ensures that variables have the exact types expected in the application code.</p><h3>Input Data Validation in FastAPI with Request Body</h3><p>Sometimes, an endpoint requires a large amount of input data and/or a complex, multi-level data structure. In such cases, it is convenient to use BaseModel to define the schema and move it to a separate module (e.g., schemas or dto).</p><pre>from fastapi import FastAPI<br>from pydantic import BaseModel<br><br>app = FastAPI()<br><br>class ItemCreateSchemaIn(BaseModel):<br>    name: str<br>    price: int<br>    quantity: int<br>    code: str<br><br>@app.post(&quot;/items/&quot;)<br>def create_item(body: ItemCreateSchemaIn):<br>    return body.model_dump()</pre><p>We have defined the request body for a POST request using the BaseModel class. Now, let&#39;s check Swagger UI to see how we can make this request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SSVNqz8l3TeQ-22l" /><figcaption>Swagger: Automatically generated example request body based on the Pydantic schema.</figcaption></figure><p>Let’s test it and verify that we receive the expected response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BnY4J35bvKTbmN5p" /><figcaption>Swagger: POST request with valid data receives the expected response with HTTP status code 200.</figcaption></figure><p>If any value does not match the expected type, we will again receive a response with a 422 status code.</p><blockquote>Using the BaseModel class in this way allows us to separate API definitions from data schemas.</blockquote><p>Additionally, it enables the use of custom validators and more complex validation logic, which we will explore later.</p><h3>Output Data Validation in FastAPI</h3><blockquote>FastAPI allows using Pydantic both to define the response schema for Swagger and to validate the actual response.</blockquote><p><strong>This ensures that API consumers receive exactly the data they expect.</strong></p><pre>from fastapi import FastAPI<br>from pydantic import BaseModel<br><br>app = FastAPI()<br>class ItemSchemaOut(BaseModel):<br>    name: str<br>    price: int<br>    quantity: int<br>    code: str<br><br>@app.get(&quot;/items/&quot;, response_model=list[ItemSchemaOut])<br>def get_items():<br>    return [<br>        {&quot;name&quot;:&quot;apple&quot;, &quot;price&quot;:300, &quot;quantity&quot;:10, &quot;code&quot;:&quot;req1&quot;},<br>        {&quot;name&quot;: &quot;orange&quot;, &quot;price&quot;: 250, &quot;quantity&quot;: 111, &quot;code&quot;: &quot;req2&quot;},<br>    ]</pre><p>Here, I added the argument response_model=list[ItemSchemaOut], which enables output data validation. In this case, the response data is a list of ItemSchemaOut objects, which will ultimately be transformed into JSON. This creates the following transformation chain:</p><p>list[dict] -&gt; list[ItemSchemaOut] -&gt; JSON.</p><p>In this specific example, I return list[dict], but it&#39;s also possible to return list[ItemSchemaOut].</p><h3>Creating a Response from an SQLAlchemy Model</h3><p>FastAPI provides a convenient way to convert SQLAlchemy models into API responses using Pydantic. <strong>This means that I can simply define the output schema using </strong><strong>BaseModel and return an instance of an SQLAlchemy model from an endpoint function.</strong></p><blockquote>FastAPI will then generate a response based on the Pydantic schema from the SQLAlchemy model.</blockquote><pre>from fastapi import FastAPI<br>from pydantic import BaseModel<br>from sqlalchemy import Column, Integer, String<br>from sqlalchemy.ext.declarative import declarative_base<br><br>app = FastAPI()<br>Base = declarative_base()<br><br>class Item(Base):<br>    __tablename__ = &quot;items&quot;<br>   <br>    id = Column(Integer, primary_key=True, index=True)<br>    name = Column(String, index=True)<br>    price = Column(Integer)<br>    quantity = Column(Integer)<br>    code = Column(String, unique=True, index=True)<br><br>class ItemSchemaV2Out(BaseModel):<br>    class Config:<br>        orm_mode=True<br>   <br>    name: str<br>    price: int<br><br>@app.get(&quot;/v2/items&quot;, response_model=list[ItemSchemaV2Out])<br>def get_v2_items():<br>    return [<br>        Item(name=&quot;Bread&quot;, price=2500, quantity=1, code=&quot;req3&quot;)<br>    ]</pre><p>In this example, I created the SQLAlchemy model class Item and defined the output schema ItemSchemaV2Out.</p><p>The output schema includes only name and price, excluding quantity, code, and id.</p><p>Note the class Config inside the Pydantic model—this is what enables FastAPI to generate a response from the SQLAlchemy model.</p><p>In this example, I return list[Item], but the response is automatically transformed into JSON based on the ItemSchemaV2Out schema.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eRh2OLlgACZ_HTqC" /><figcaption>Swagger: Received items information based on the ItemSchemaV2Out.</figcaption></figure><h3>Creating a response from an SQLAlchemy model with a parent relationship</h3><p>Pydantic and SQLAlchemy provide another convenient feature. SQLAlchemy can automatically query the database to retrieve data about a model’s parent or child.</p><p>Let’s create a small application with two SQLAlchemy models: Item and Seller, with a <strong>Many-to-One</strong> relationship—many Item records belong to one Seller.</p><pre>from fastapi import FastAPI<br>from pydantic import BaseModel<br>from sqlalchemy import Column, ForeignKey, Integer, String<br>from sqlalchemy.ext.declarative import declarative_base<br>from sqlalchemy.orm import relationship<br><br>app = FastAPI()<br>Base = declarative_base()<br><br>class Item(Base):<br>    __tablename__ = &quot;items&quot;<br><br>    id = Column(Integer, primary_key=True, index=True)<br>    name = Column(String, index=True)<br>    price = Column(Integer)<br>    quantity = Column(Integer)<br>    code = Column(String, unique=True, index=True)<br>    seller_id = Column(Integer, ForeignKey(&quot;sellers.id&quot;))<br><br>    seller = relationship(&quot;Seller&quot;, back_populates=&quot;items&quot;)<br><br>class Seller(Base):<br>    __tablename__ = &quot;sellers&quot;<br><br>    id = Column(Integer, primary_key=True, index=True)<br>    name = Column(String, index=True)<br>    items = relationship(&quot;Item&quot;, back_populates=&quot;seller&quot;)<br><br>class SellerSchemaV2Out(BaseModel):<br>    class Config:<br>        orm_mode = True<br><br>    name: str<br><br>class ItemSchemaV2Out(BaseModel):<br>    class Config:<br>        orm_mode = True<br><br>    name: str<br>    price: int<br>    seller: SellerSchemaV2Out<br><br>@app.get(&quot;/v2/items&quot;, response_model=list[ItemSchemaV2Out])<br>def get_v2_items():<br>    seller: Seller = Seller(name=&quot;Karefour&quot;)<br>    item: Item = Item(<br>        name=&quot;Orange&quot;, price=3400, quantity=10, code=&quot;req4&quot;, seller=seller<br>    )<br>    return [item]</pre><p>In the get_v2_items method, I create an Item with a Seller and return a list of items. FastAPI then generates a response based on the defined schema, including parent information.</p><p>This approach reduces boilerplate code and allows developers to focus on business logic.</p><p><strong>However, caution is needed when using this functionality. </strong>Poorly optimized queries can significantly impact performance by generating too many database requests.</p><p>For example, consider the following query, which retrieves the first 100 Item records and returns them using list[ItemSchemaV2Out] for serialization:</p><pre>@app.get(&quot;/v2/items&quot;, response_model=list[ItemSchemaV2Out])<br>def get_v2_items():<br>    items: list[Item] = session.query(Item).limit(100).all()<br>    return items</pre><p>In this case, SQLAlchemy does not prefetch the Seller data for each Item. As a result, FastAPI will trigger <strong>one additional query per item</strong>, leading to <strong>101 queries instead of just 1</strong>—one query to fetch the items and 100 additional queries to fetch sellers individually.</p><p>To prevent this, we can use <strong>SQLAlchemy’s </strong><strong>joinedload</strong> to eager-load the related Seller model in a single query:</p><pre>items: list[Item] = session.query(Item).options(joinedload(Item.seller)).limit(100).all()</pre><blockquote>This ensures that all necessary data is retrieved in <strong>one query instead of 101</strong>, significantly improving performance.</blockquote><h3>CSV file data validation</h3><p>Pydantic is a standalone library and is not limited to FastAPI.</p><blockquote>Let’s see how we can use Pydantic to validate data from a CSV file.</blockquote><p>CSV is a widely used format for storing tabular data. Python provides powerful tools for analyzing and extracting data from CSV files. A common task when working with CSV files is ensuring that all data follows the expected format. Pydantic is an excellent tool for this.</p><p>For example, let’s validate the data from the following CSV file:</p><pre>name,price,quantity<br>apple,2500,2<br>orange,2000,100<br>bread,2700,50</pre><pre>import csv<br>from pydantic import BaseModel, ValidationError<br><br>class ItemSchema(BaseModel):<br>    name: str<br>    price: int<br>    quantity: int<br><br>def validate_csv_file(filename: str):<br>    with open(filename, mode=&quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>        csv_reader = csv.DictReader(f, fieldnames=[&quot;name&quot;, &quot;price&quot;, &quot;quantity&quot;])<br>        next(csv_reader, None)<br>        for line_num, row in enumerate(csv_reader, start=1):<br>            try:<br>                item = ItemSchema(**row)<br>                print(f&quot;Row {line_num} is valid: {item}&quot;)<br>            except ValidationError as e:<br>                print(f&quot;Validation error in row {line_num}: {e}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    validate_csv_file(&quot;items.csv&quot;)</pre><p>Let’s execute this script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OWsyyKrABEt7_NBu" /><figcaption>Script executed successfully with valid data.</figcaption></figure><p>Now, I will change the price value for orange to 2000_invalid_int.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H4lBOdqhrV7EZbK7" /><figcaption>Script execution failed due to invalid data in the second row.</figcaption></figure><p>As a result, we receive a response with detailed error information, indicating that the value does not match the expected integer type.</p><h3>Creating and Reusing a Custom Validator</h3><p>Custom validators are often needed when validation logic is more complex than simple type checks. Additionally, <strong>the same validator may need to be applied to multiple fields.</strong></p><p>Let’s see how to achieve this using the <strong>Annotated pattern </strong>in Pydantic.</p><pre>from datetime import datetime<br>from typing import Annotated<br>from pydantic import BaseModel, BeforeValidator<br><br>def validate_string_date(value: str) -&gt; str:<br>    try:<br>        datetime.strptime(value, &quot;%Y.%m.%d&quot;).date()<br>        return value<br>    except ValueError:<br>        raise ValueError(<br>            f&quot;Invalid date format &#39;{value}&#39;. Expected YYYY.MM.DD.&quot;<br>        )<br><br>class Item(BaseModel):<br>    creation_date: Annotated[str, BeforeValidator(validate_string_date)]<br>    update_date: Annotated[str, BeforeValidator(validate_string_date)]<br>   <br>if __name__ == &quot;__main__&quot;:<br>    print(Item(creation_date=&quot;2025.11.01&quot;, update_date=&quot;2025.10.01&quot;))</pre><p>In this example, I implemented date validation in the format <strong>“YYYY.MM.DD”</strong> for two arguments: creation_date and update_date, using the BeforeValidator class. This class applies the validate_string_date function <strong>before</strong> Pydantic&#39;s type validation. In the example above, the types of creation_date and update_date remain the same: <strong>string</strong>.</p><p>A custom validator can be used to change the variable type, for example, from <strong>string to date</strong>. Take a look at the example below.</p><pre>from datetime import datetime, date<br>from typing import Annotated<br>from pydantic import BaseModel, BeforeValidator<br><br><br>def parse_date(value: str) -&gt; date:<br>    try:<br>        return datetime.strptime(value, &quot;%Y.%m.%d&quot;).date()<br>    except ValueError:<br>        raise ValueError(<br>            f&quot;Invalid date format &#39;{value}&#39;. Expected YYYY.MM.DD.&quot;<br>        )<br><br><br>class Item(BaseModel):<br>    creation_date: Annotated[date, BeforeValidator(parse_date)]<br>    update_date: Annotated[date, BeforeValidator(parse_date)]<br>    <br>if __name__ == &quot;__main__&quot;:<br>    print(Item(creation_date=&quot;2025.11.01&quot;, update_date=&quot;2025.10.01&quot;))</pre><h3>Other Validation Methods in Pydantic</h3><p>We’ve explored some ways to use Pydantic, but it’s a <strong>comprehensive</strong> library with various built-in validation methods. Let’s take a look at a few more.</p><pre>from uuid import uuid4<br>from pydantic import BaseModel, EmailStr, Field<br>from enum import StrEnum<br><br>class UserRolesEnum(StrEnum):<br>    CUSTOMER=&quot;CUSTOMER&quot;<br>    ADMIN=&quot;ADMIN&quot;<br><br>class User(BaseModel):<br>    uuid: str = Field(default_factory=lambda: uuid4().hex)<br>    email: EmailStr<br>    first_name: str = Field(min_length=2, max_length=100)<br>    team: str = Field(pattern=r&quot;^(a|b|c)$&quot;)<br>    age: int = Field(gt=0, lt=150)<br>    role: UserRolesEnum<br>    is_email_confirmed: bool = False<br>   <br>if __name__ == &quot;__main__&quot;:<br>    print(User(email=&quot;test@test.com&quot;, first_name=&quot;Salvador&quot;, team=&quot;a&quot;, age=20, role=UserRolesEnum.ADMIN))</pre><p>I created a User schema with the following validations:</p><ul><li><strong>uuid</strong> – Automatically generated using uuid4 upon initialization.</li><li><strong>email</strong> – A string that must follow a valid email format.</li><li><strong>first_name</strong> – A string with a minimum length of 2 characters and a maximum of 100 characters.</li><li><strong>team</strong> – A string that must match a specified regex pattern.</li><li><strong>age</strong> – An integer greater than 0 and less than 150.</li><li><strong>role</strong> – A value that must be one of the predefined options in the UserRolesEnum enum.</li><li><strong>is_mail_confirmed</strong> – An optional boolean with a default value of False.</li></ul><h3>Conclusion</h3><p>We explored several use cases for <strong>Pydantic</strong> in data validation. Combined with <strong>static code analyzers</strong> like mypy, Pydantic helps prevent runtime errors related to incorrect types or formats, making Python applications more <strong>stable</strong> and <strong>predictable</strong>.</p><p>Even though Python is a <strong>dynamically typed</strong> language, I strongly recommend using <strong>Pydantic</strong> for type validation.</p><h3>Useful Links</h3><ol><li><a href="https://docs.pydantic.dev/"><strong>Pydantic Documentation</strong></a> — Official Pydantic documentation.</li><li><a href="https://fastapi.tiangolo.com/"><strong>FastAPI Documentation</strong></a> — Official FastAPI documentation.</li><li><a href="https://medium.com/@gnetkov/automating-code-quality-control-with-pre-commit-hooks-fdbc1ec5cfea"><strong>Automating Code Quality Control with Pre-commit Hooks</strong></a> — Make your code better by adding quality control.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e418001192ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guide to S3 File Management: FastAPI and S3 Service in Docker Compose]]></title>
            <link>https://medium.com/@gnetkov/guide-to-s3-file-management-fastapi-and-s3-service-in-docker-compose-1d26900f67cc?source=rss-bd9eb418040f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d26900f67cc</guid>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[minio]]></category>
            <dc:creator><![CDATA[Fedor GNETKOV]]></dc:creator>
            <pubDate>Mon, 13 Jan 2025 07:09:44 GMT</pubDate>
            <atom:updated>2025-01-13T07:09:44.052Z</atom:updated>
            <content:encoded><![CDATA[<p>When building applications, storing and managing files is a common task. <strong>S3-compatible storage</strong> has become a popular method for storing files in web and mobile applications, <strong>establishing itself as the de facto standard</strong>.</p><blockquote>In this article, we will explore how to use S3 in a Python application (FastAPI) and create an S3 service using Docker Compose and MinIO.</blockquote><p>Specifically, we will:</p><ul><li>Create a Docker Compose file with two services: a python application built with FastAPI and an S3-compatible service based on MinIO.</li><li>Implement an S3Service class with methods for interacting with S3.</li><li>Develop endpoints to demonstrate the usage of S3Service.</li></ul><p>As always, the complete application code is available on GitLab: <a href="https://gitlab.com/FedorGN/fastapi-s3-example">https://gitlab.com/FedorGN/fastapi-s3-example</a>. It’s very easy to run the project on local computer. Just clone, copy .env.exampl and run the project using a only one command: docker compose up.</p><h4>Why Use MinIO in Docker Compose?</h4><p>To have a local S3 service without incurring costs for paid S3 services. Why pay for the S3 service when you can create a local S3 service using Docker Compose?</p><blockquote>While a real S3 solution is ideal for production, a local S3 service is often sufficient for development purposes.</blockquote><h4>How We Will Use S3:</h4><ul><li><strong>Upload a file directly from the backend to S3:</strong> The backend generates a file and uploads it to S3 for storage.</li><li><strong>Download a file from S3 to the backend:</strong> This is a common use case when the backend needs to retrieve a file from S3 for processing.</li><li><strong>Generate presigned download links:</strong> For security, it is not recommended to provide users with a permanent direct link to an S3 object. Instead, it’s recommended to generate a temporary link that is valid for a specific time.</li><li><strong>Generate presigned upload links:</strong> Sometimes, uploading a file to the backend is unnecessary. If users want to upload a document, a presigned upload link allows the frontend to upload the file directly to S3 storage. The backend is then notified of the upload’s completion.</li><li><strong>Delete a file from S3 storage:</strong> When freeing up space by removing unnecessary files from S3.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x7DW0yFmMqkHOWY1Ksh2Zg.png" /></figure><h3>Containerization with Docker Compose</h3><p>First, let’s create a docker-compose.yml file, defining two services: backend and minio.</p><p>File: docker-compose.yml</p><pre>x-linux-container-environment:<br> &amp;common-linux-container-environment-variables<br> TZ: &quot;Europe/Paris&quot;<br>ytt<br>services:<br> # FastAPI backend<br> backend:<br>   build:<br>     dockerfile: ./backend/Dockerfile<br>   volumes:<br>     - ./backend/:/code/app/:z<br>   image: &quot;backend:latest&quot;<br>   ports:<br>     - ${BACKEND_EXTERNAL_PORT}:${BACKEND_INTERNAL_PORT}<br>   user: &quot;${UID}:${GID}&quot;<br>   environment:<br>     &lt;&lt;: *common-linux-container-environment-variables<br>     S3_INTERNAL_PORT: ${S3_INTERNAL_PORT}<br>     S3_EXTERNAL_PORT: ${S3_EXTERNAL_PORT}<br>     S3_BUCKET_NAME: ${S3_BUCKET_NAME}<br>     S3_ACCESS_KEY: ${S3_ACCESS_KEY}<br>     S3_SECRET_KEY: ${S3_SECRET_KEY}<br>     S3_REGION: ${S3_REGION}<br>     S3_REQUIRE_TLS: ${S3_REQUIRE_TLS}<br>     IS_PROXY_REQUIRED: ${IS_PROXY_REQUIRED}<br>     S3_EXTERNAL_HOST: ${S3_EXTERNAL_HOST}<br>     S3_INTERNAL_URL: ${S3_INTERNAL_URL}<br>   command: uvicorn main:app --host 0.0.0.0 --port ${BACKEND_INTERNAL_PORT} --reload<br>   restart: unless-stopped<br><br> # S3 compatible storage<br> minio:<br>   image: quay.io/minio/minio:latest<br>   ports:<br>     - ${S3_EXTERNAL_PORT}:${S3_INTERNAL_PORT}<br>     - ${MINIO_CONSOLE_EXTERNAL_PORT}:${MINIO_CONSOLE_INTERNAL_PORT}<br>   environment:<br>     MINIO_ROOT_USER: ${S3_ACCESS_KEY}<br>     MINIO_ROOT_PASSWORD: ${S3_SECRET_KEY}<br>   volumes:<br>     - minio-data:/data<br>     - minio-config:/root/.minio<br>   command: server /data --console-address &quot;:${MINIO_CONSOLE_INTERNAL_PORT}&quot;<br>   restart: unless-stopped<br><br>volumes:<br> minio-data:<br> minio-config:</pre><p>Note that all configuration is done using environment variables. These variables should be stored in a .env file. The .env file is included in .gitignore to prevent accidentally committing secrets to the repository. However, the repository includes a .env.example file that should be copied and modified as needed.</p><p>For running MinIO, I used one of the official images. It’s important to bind volumes to ensure that data persists in storage even after the container is restarted.</p><p>File backend/Dockerfile:</p><pre>FROM python:3.12<br>ENV PYTHONDONTWRITEBYTECODE 1<br>WORKDIR /code/app<br>COPY backend/requirements.txt /code/requirements.txt<br>RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt<br>COPY . /code/app/.<br>ENV PYTHONPATH &quot;/code/app&quot;</pre><p>This is a simple Dockerfile to create the backend image.</p><p>Let’s run Docker Compose with command:</p><pre>docker compose up</pre><p>Then open the MinIO Console at <a href="http://localhost:9001/">http://localhost:9001/</a>.<br>The login and password for MinIO Console are the values of the environment variables S3_ACCESS_KEY and S3_SECRET_KEY.</p><p>This will give you access to the graphical interface for managing S3. It’s very convenient, intuitive, and packed with many useful features. Highly recommended! 🙂</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FaR_fav3EV3vhruD" /><figcaption>MiniIO Console at http://localhost:9001/</figcaption></figure><p>Let’s create a bucket named <strong>“my-bucket”</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OCTOnOn7pH8F2D51" /><figcaption>MiniIO Console at <a href="http://localhost:9001/">http://localhost:9001/</a></figcaption></figure><p>The S3 service is ready! Quick and easy!</p><h3>Python application</h3><p>Now, let’s move on to writing the Python code.</p><p>In this project, I will implement:</p><ul><li>A S3Service class with methods for interacting with S3.</li><li>Endpoints to demonstrate how to work with S3.</li></ul><p>File backend/services/minio_s3_service.py:</p><pre>import os<br>import uuid<br>from datetime import datetime<br>from datetime import timedelta<br><br>from minio import Minio<br>from minio import S3Error<br>from pydantic import BaseModel<br>from urllib3 import ProxyManager<br><br>from exceptions.s3 import S3ObjectDoesntExistException<br>from config import app_config<br><br><br>class S3ServiceSettings(BaseModel):<br>   &quot;&quot;&quot;<br>   S3 client settings<br>   &quot;&quot;&quot;<br>   S3_BUCKET_NAME: str = app_config.S3_BUCKET_NAME<br>   # External S3 endpoint<br>   S3_ENDPOINT: str = app_config.S3_EXTERNAL_HOST<br>   S3_ACCESS_KEY: str = app_config.S3_ACCESS_KEY<br>   S3_SECRET_KEY: str = app_config.S3_SECRET_KEY<br>   S3_REGION: str = app_config.S3_REGION<br>   S3_REQUIRE_TLS: bool = app_config.S3_REQUIRE_TLS<br>   # Proxy is required in local environment with docker compose<br>   IS_PROXY_REQUIRED: bool = app_config.IS_PROXY_REQUIRED<br>   # Internal docker URL. To set if IS_PROXY_REQUIRED=True<br>   S3_INTERNAL_URL: str = app_config.S3_INTERNAL_URL<br><br><br>class S3Service:<br>   &quot;&quot;&quot;<br>   Class that provides a façade for application to access the underlying S3 storage.<br>   &quot;&quot;&quot;<br>   storage_configuration: S3ServiceSettings<br>   minio_client: Minio<br>   tmp_path: str<br><br>   def __init__(self, storage_configuration: S3ServiceSettings | None = None):<br>       if storage_configuration is None:<br>           storage_configuration = S3ServiceSettings()<br>       self.storage_configuration = storage_configuration<br>       self.minio_client = Minio(<br>           self.storage_configuration.S3_ENDPOINT,<br>           access_key=self.storage_configuration.S3_ACCESS_KEY,<br>           secret_key=self.storage_configuration.S3_SECRET_KEY,<br>           region=self.storage_configuration.S3_REGION,<br>           secure=self.storage_configuration.S3_REQUIRE_TLS,<br>           http_client=ProxyManager(self.storage_configuration.S3_INTERNAL_URL)<br>           if self.storage_configuration.IS_PROXY_REQUIRED<br>           else None,<br>       )<br>       self.tmp_path: str = &quot;./tmp&quot;<br><br><br>   def __generate_upload_path(self) -&gt; str:<br>       &quot;&quot;&quot;<br>       Generate a directory path based on the current date.<br><br>       Returns:<br>       - str: A string representing the directory path in the format &quot;YYYY/MM/DD/&quot;.<br>       &quot;&quot;&quot;<br>       current_yyyy_mm_dd: str = datetime.now().strftime(&quot;%Y/%m/%d&quot;)<br>       path: str = current_yyyy_mm_dd + &quot;/&quot;<br>       return path<br><br>   def __generate_upload_path_with_file_name(self) -&gt; str:<br>       &quot;&quot;&quot;<br>       Generate a unique S3 object path with a file name.<br><br>       Combines the current date directory path with a UUID as the file name.<br><br>       Returns:<br>       - str: A string representing the full S3 object path in the format &quot;YYYY/MM/DD/&lt;UUID&gt;&quot;.<br>       &quot;&quot;&quot;<br>       s3_object_file_name: str = str(uuid.uuid4())<br>       s3_object_path = f&quot;{self.__generate_upload_path()}{s3_object_file_name}&quot;<br>       return s3_object_path<br><br>   def __validate_object_existance(self, s3_object_path: str) -&gt; None:<br>       &quot;&quot;&quot;<br>       Validate the existence of an object in the S3 bucket.<br><br>       Checks if the object with the given path exists in the configured S3 bucket.<br>       If the object does not exist, raises an `S3ObjectDoesntExistException`.<br><br>       Parameters:<br>       - s3_object_path (str): The path of the object in the S3 bucket to validate.<br><br>       Raises:<br>       - S3ObjectDoesntExistException: If the object does not exist in the S3 bucket.<br>       - S3Error: For other S3-related errors.<br>       &quot;&quot;&quot;<br>       try:<br>           self.minio_client.stat_object(<br>               self.storage_configuration.S3_BUCKET_NAME, s3_object_path<br>           )<br>       except S3Error as e:<br>           if e.code == &quot;NoSuchKey&quot;:<br>               raise S3ObjectDoesntExistException(<br>                   f&quot;The S3 object with path=&#39;{s3_object_path}&#39; does not exist in the bucket.&quot;<br>               ) from e<br>           raise<br><br>   def remove_digital_object(self, s3_object_path: str) -&gt; None:<br>       &quot;&quot;&quot;<br>       Removes a digital object from the S3 bucket.<br><br>       Parameters:<br>       - s3_object_path (str): The path of the digital object to be removed in the S3 bucket.<br><br>       Raises:<br>       - FileNotFoundError: If the specified object does not exist in the bucket.<br>       - S3Error: If there is an issue with the S3-compatible storage service.<br>       &quot;&quot;&quot;<br>       self.__validate_object_existance(s3_object_path=s3_object_path)<br>       self.minio_client.remove_object(<br>           self.storage_configuration.S3_BUCKET_NAME, s3_object_path<br>       )<br><br>   def upload(self, file_name: str) -&gt; str:<br>       &quot;&quot;&quot;<br>       Upload file to S3 storage.<br><br>       Parameters:<br>       - file_name (str): relative path to file to upload<br>       &quot;&quot;&quot;<br>       s3_object_path: str = self.__generate_upload_path_with_file_name()<br>       self.minio_client.fput_object(<br>           self.storage_configuration.S3_BUCKET_NAME, s3_object_path, file_name<br>       )<br>       return s3_object_path<br><br>   def download(self, s3_object_path: str, local_file_name: str | None = None) -&gt; str:<br>       &quot;&quot;&quot;<br>       Download a file from S3 storage to the tmp directory.<br><br>       Parameters:<br>       - object_name (str): The path of the object in the S3 store (including file name).<br>       - local_file_name (str, optional): Name of the local file to save. Defaults to the object&#39;s<br>         name.<br><br>       Returns:<br>       - str: The path to the downloaded file in the local tmp directory.<br>       &quot;&quot;&quot;<br>       self.__validate_object_existance(s3_object_path=s3_object_path)<br>       file_name_to_create: str = (<br>           local_file_name if local_file_name else os.path.basename(s3_object_path)<br>       )<br>       local_file_path: str = os.path.join(self.tmp_path, file_name_to_create)<br>       try:<br>           self.minio_client.fget_object(<br>               self.storage_configuration.S3_BUCKET_NAME,<br>               s3_object_path,<br>               local_file_path,<br>           )<br>           return local_file_path<br>       except Exception as e:<br>           raise RuntimeError(<br>               f&quot;Failed to download file &#39;{s3_object_path}&#39;: {str(e)}&quot;<br>           ) from e<br><br>   def generate_download_url(https://medium.com/%3Cbr%3E%20%20%20%20%20%20%20self,%3Cbr%3E%20%20%20%20%20%20%20s3_object_path:%20str,%3Cbr%3E%20%20%20%20%20%20%20desired_filename:%20str%20|%20None%20=%20None,%3Cbr%3E%20%20%20%20%20%20%20expiration_minutes:%20int%20=%20360,%3Cbr%3E) -&gt; str:<br>       &quot;&quot;&quot;<br>       Generate a pre-signed URL for downloading an object from S3 with a specific filename.<br><br>       Parameters:<br>       - s3_object_path (str): The path of the object in the S3 bucket.<br>       - desired_filename (str | None, optional): The filename the user should see when<br>         downloading the file.<br>       - expiration_minutes (int): The validity duration of the pre-signed URL in minutes.<br><br>       Returns:<br>       - (str): A pre-signed URL to download the object.<br>       &quot;&quot;&quot;<br>       self.__validate_object_existance(s3_object_path=s3_object_path)<br>       file_name: str = (<br>           desired_filename if desired_filename else os.path.basename(s3_object_path)<br>       )<br>       response_headers: dict[str, str] = {<br>           &quot;response-content-disposition&quot;: f&quot;attachment; filename={file_name}&quot;<br>       }<br>       try:<br>           presigned_url: str = self.minio_client.presigned_get_object(<br>               bucket_name=self.storage_configuration.S3_BUCKET_NAME,<br>               object_name=s3_object_path,<br>               expires=timedelta(minutes=expiration_minutes),<br>               response_headers=response_headers,  # type: ignore<br>           )<br>           return presigned_url<br>       except Exception as e:<br>           raise RuntimeError(f&quot;Failed to generate download link: {str(e)}&quot;) from e<br><br>   def generate_presigned_upload_url(https://medium.com/%3Cbr%3E%20%20%20%20%20%20%20self,%20s3_object_path:%20str%20|%20None%20=%20None,%20expiration_minutes:%20int%20=%20360%3Cbr%3E) -&gt; tuple[str, str]:<br>       &quot;&quot;&quot;<br>       Generate a pre-signed URL for uploading files directly from the frontend.<br><br>       Parameters:<br>       - s3_object_path (str, optional): The path of the object in S3 (including file name).<br>       - expiration_minutes (int): The number of minutes the pre-signed URL is valid for.<br><br>       Returns:<br>       - (tuple(str, str)): The pre-signed URL for file upload and s3_object_path<br>       &quot;&quot;&quot;<br>       if s3_object_path is None:<br>           s3_object_path = self.__generate_upload_path_with_file_name()<br>       try:<br>           presigned_url = self.minio_client.presigned_put_object(<br>               bucket_name=self.storage_configuration.S3_BUCKET_NAME,<br>               object_name=s3_object_path,<br>               expires=timedelta(minutes=expiration_minutes),<br>           )<br>           return presigned_url, s3_object_path<br>       except Exception as e:<br>           raise RuntimeError(f&quot;Failed to generate pre-signed URL: {str(e)}&quot;) from e</pre><p>The S3ServiceSettings class is used for configuration of S3Service. The parameters IS_PROXY_REQUIRED and S3_INTERNAL_URL are essential for development with Docker Compose. Since MinIO and the backend are in the same Docker Compose network, they can communicate with each other using hosts like minio:9000 or backend:8090.</p><p>However, if we use these hosts to generate links for users or the frontend, they won’t work because users do not have direct access to minio:9000. <strong>To solve this problem, we will use a proxy. </strong>Fortunately, the minio package supports this functionality.</p><p>During initialization, we create a ProxyManager only if IS_PROXY_REQUIRED == True. It is required in the local environment but not in production, where a cloud S3 service is used.</p><pre>http_client=ProxyManager(self.storage_configuration.S3_INTERNAL_URL)<br>           if self.storage_configuration.IS_PROXY_REQUIRED<br>           else None,</pre><p><strong>This approach enables generating links accessible to users and the frontend, such as links with the host </strong><strong>localhost:9000.</strong></p><p>The methods __generate_upload_path and __generate_upload_path_with_file_name generate a unique S3 object name in the format 2025/01/07/&lt;UUID4&gt;. This ensures files are organized by upload date, with the file name being a UUID. Why use a UUID for the file name? A user might upload the same file multiple times, which could create conflicts. Using a random UUID guarantees there are no conflicts.</p><p>The method __validate_object_existence is used to check if an object exists in storage. This prevents generating a link for a file that doesn&#39;t exist, even though the minio package allows this.</p><p>Descriptions of the other methods are provided in their docstrings.</p><p>I’ve created a custom exception, S3ObjectDoesntExistException, for the S3Service. This exception can be used to return a response with a 404 status code.</p><p>File: backend/exceptions/s3.py</p><pre>class S3ObjectDoesntExistException(Exception):<br>   pass</pre><p>Let’s create schemas for the API responses. File backend/schemas/s3.py:</p><pre>from pydantic import BaseModel<br><br>class DownloanLinkSchemaOut(BaseModel):<br>   download_link: str<br><br><br>class UploadTestFileSchemaOut(BaseModel):<br>   s3_object_path: str<br><br><br>class DownloadTestFileSchemaOut(BaseModel):<br>   downloaded_file_path: str<br><br><br>class UploadUrlSchemaOut(BaseModel):<br>   url: str<br>   s3_object_path: str</pre><p>File backend/schemas/common_responses.py:</p><pre>from pydantic import BaseModel<br><br><br>class MessageResponseSchemaOut(BaseModel):<br>   message: str</pre><p>Now let’s take a look at the APIs. File backend/apis/s3_api.py:</p><pre>from fastapi import APIRouter, HTTPException, Query, status<br><br>from schemas import MessageResponseSchemaOut<br>from schemas import (<br>   DownloadTestFileSchemaOut,<br>   DownloanLinkSchemaOut,<br>   UploadTestFileSchemaOut,<br>   UploadUrlSchemaOut,<br>)<br>from exceptions import S3ObjectDoesntExistException<br>from services.minio_s3_service import S3Service<br><br>router = APIRouter()<br><br>@router.post(&quot;/upload-test-file-to-s3/&quot;)<br>async def upload_test_file_to_s3() -&gt; UploadTestFileSchemaOut:<br>   &quot;&quot;&quot;<br>   Test route to upload a file ./test_upload_file.txt to S3. File must exist.<br>   ---<br>   Attention. This route is only for demonstration purposes. No need in such route in production<br>   application.<br>   &quot;&quot;&quot;<br>   s3_service: S3Service = S3Service()<br>   s3_object_path: str = s3_service.upload(&quot;test_upload_file.txt&quot;)<br>   return UploadTestFileSchemaOut(s3_object_path=s3_object_path)<br><br><br>@router.get(&quot;/download-file-from-s3/&quot;)<br>async def download_file_from_s3(<br>   s3_object_path: str = Query(..., example=&quot;2024/12/27/123.txt&quot;),<br>) -&gt; DownloadTestFileSchemaOut:<br>   &quot;&quot;&quot;<br>   Test route to download a file from S3.<br>   ---<br>   Attention. This route is only for demonstration purposes. No need in such route in production<br>   application.<br>   &quot;&quot;&quot;<br>   s3_service: S3Service = S3Service()<br>   try:<br>       downloaded_file_path: str = s3_service.download(s3_object_path)<br>   except S3ObjectDoesntExistException:<br>       raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)<br>   return DownloadTestFileSchemaOut(downloaded_file_path=downloaded_file_path)<br><br><br>@router.delete(&quot;/delete-file-from-s3/&quot;)<br>async def remove_file_from_s3(<br>   s3_object_path: str = Query(..., example=&quot;2024/12/27/123.txt&quot;),<br>) -&gt; MessageResponseSchemaOut:<br>   &quot;&quot;&quot;<br>   Test route to delete a file from S3 storage.<br>   ---<br>   Attention. This route is only for demonstration purposes. No need in such route in production<br>   application.<br>   &quot;&quot;&quot;<br>   s3_service: S3Service = S3Service()<br>   try:<br>       s3_service.remove_digital_object(s3_object_path)<br>   except S3ObjectDoesntExistException:<br>       raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)<br>   return MessageResponseSchemaOut(message=&quot;File deleted&quot;)<br><br><br>@router.get(&quot;/s3-upload-url&quot;)<br>async def generate_presigned_upload_url() -&gt; UploadUrlSchemaOut:<br>   &quot;&quot;&quot;Generate presigned url for file upload directly to S3 storage.&quot;&quot;&quot;<br>   s3_service: S3Service = S3Service()<br>   url, s3_object_path = s3_service.generate_presigned_upload_url()<br>   return UploadUrlSchemaOut(url=url, s3_object_path=s3_object_path)<br><br><br>@router.get(&quot;/s3-download-url&quot;)<br>async def generate_download_url(https://medium.com/%3Cbr%3E%20%20%20file_path:%20str%20=%20Query(...,%20example=&quot;2024/12/27/123.txt&quot;),<br>) -&gt; DownloanLinkSchemaOut:<br>   &quot;&quot;&quot;Generate presigned url for file download from S3 storage.&quot;&quot;&quot;<br>   s3_service: S3Service = S3Service()<br>   try:<br>       download_link: str = s3_service.generate_download_url(https://medium.com/file_path)<br>   except S3ObjectDoesntExistException:<br>       raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)<br>   return DownloanLinkSchemaOut(download_link=download_link)</pre><p>Open the Swagger documentation at <a href="http://localhost:8090/docs#/">http://localhost:8090/docs#/</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nyxJhM9RGjNF46Ir" /><figcaption>Swagger documentation at <a href="http://localhost:8090/docs#/">http://localhost:8090/docs#/</a></figcaption></figure><p>Let’s now test a few routes. We’ll upload the test file test_upload_file.txt to the S3 storage using the route /s3/upload-test-file-to-s3. The file is located in the project: backend/test_upload_file.txt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6ZC7npQdN_sjuahB" /><figcaption>POST endpoint /s3/upload-test-file-to-s3</figcaption></figure><p>In response, we received the s3_object_path, which can be used to generate a presigned link for downloading. Note: This API is for development purposes. In a real application, it is not recommended to expose actual S3 object identifiers (s3_object_path) to users. Instead, users should only see temporary presigned links.</p><p>By opening the MinIO Console (<a href="http://localhost:9001/">http://localhost:9001</a>), I can confirm that the file has been successfully uploaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1wH9uVJ1S0Z5IdOE" /><figcaption>One file is uploaded to the bucket “my-bucket”</figcaption></figure><p>Now, with the file in S3, I can generate a download link for the file using the API /s3/s3-download-url.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JniX3JjmQvqE_Akx" /><figcaption>GET endpoint /s3/s3-download-url</figcaption></figure><p>By copying the link and pasting it into a browser, I successfully downloaded the file.</p><blockquote>So, I’ve just uploaded a file to S3 storage, generated a temporary link for it, and downloaded it using the temporary link.</blockquote><p>Now, let’s try generating a link for a non-existent file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bZWCRhrmOUxdwyNK" /><figcaption>404 response for not existing file. GET endpoint /s3/s3-download-url</figcaption></figure><p>We received the expected 404 response, indicating that the file does not exist.</p><p>Now, let’s upload an object using a presigned upload link. First, we’ll generate the URL for the upload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b4YogXF0sg_lTJug" /><figcaption>GET endpoint /s3/s3-upload-url</figcaption></figure><p>We received the URL, which is typically used for uploading files from the frontend to S3. However, we can also upload the file using a curl command, for example:</p><pre>curl -X PUT -T backend/test_upload_file.txt &quot;http://localhost:9000/my-bucket/2025/01/12/d207a189-ec40-425b-bd4d-24d47aba4af9?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Credential=user%2F20250112%2Fus-east-1%2Fs3%2Faws4_request&amp;X-Amz-Date=20250112T100036Z&amp;X-Amz-Expires=21600&amp;X-Amz-SignedHeaders=host&amp;X-Amz-Signature=549dd55cd4b795564c823719be7a7b6940ada5edb6f6196ec3754b33b625c0b6&quot;</pre><p>The command executed without errors. Now, let’s check the S3 storage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fWGCtGle1Wm6V5gX" /><figcaption>Two files are uploaded to the bucket “my-bucket”</figcaption></figure><p>Now there are two files in S3, which means the upload using curl was successful.</p><h3>Conclusion</h3><p>In this article, we demonstrated how to use S3-compatible storage with Python (FastAPI) and MinIO in a Docker Compose setup. Here’s a summary of what we achieved:</p><ol><li><strong>Set up MinIO locally with Docker Compose</strong>: We created a fully functional S3-compatible storage environment for development purposes, avoiding the need for paid S3 services during local development.</li><li><strong>Developed an S3 service in Python</strong>: Using FastAPI, we implemented an S3Service class to handle common operations like uploading, downloading, and generating presigned links.</li><li><strong>Built API endpoints</strong>: These endpoints showcased how to upload files directly to S3, retrieve files, generate temporary download/upload links, and delete files.</li><li><strong>Tested various use cases</strong>: We tested direct uploads from the backend, downloads using presigned links, and frontend-style uploads using presigned upload links.</li></ol><p>This approach is practical for local development and mirrors real-world workflows when working with S3. By leveraging MinIO, developers can test their applications effectively without incurring additional costs or dependencies on external cloud services.</p><p>With these tools and methods, you can integrate S3 functionality into your Python applications, whether for development or production environments. The complete source code is available on GitLab for reference. Happy coding! 🚀</p><h3>Useful links</h3><ol><li><a href="https://gitlab.com/FedorGN/fastapi-s3-example">https://gitlab.com/FedorGN/fastapi-s3-example</a> — repository with code of this article.</li><li><a href="https://min.io/docs/minio/container/index.html">https://min.io/docs/minio/container/index.html</a> — MinIO official documentation.</li><li><a href="https://min.io/docs/minio/linux/developers/python/minio-py.html">https://min.io/docs/minio/linux/developers/python/minio-py.html</a> — MinIO SDK documentation.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d26900f67cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Start Using UV Python Package Manager for Better Dependency Management]]></title>
            <link>https://medium.com/@gnetkov/start-using-uv-python-package-manager-for-better-dependency-management-183e7e428760?source=rss-bd9eb418040f------2</link>
            <guid isPermaLink="false">https://medium.com/p/183e7e428760</guid>
            <category><![CDATA[uv]]></category>
            <category><![CDATA[dependency-management]]></category>
            <category><![CDATA[poetry]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[virtual-environment]]></category>
            <dc:creator><![CDATA[Fedor GNETKOV]]></dc:creator>
            <pubDate>Sun, 08 Dec 2024 18:36:35 GMT</pubDate>
            <atom:updated>2025-01-04T15:06:01.883Z</atom:updated>
            <content:encoded><![CDATA[<p>Uv is a powerful and fast package manager, and you’ve probably heard of it. Released in February 2024, it quickly gained popularity. The main reasons for its success are its practicality and exceptional speed. The FastAPI team has already adopted Uv as the package manager for the FastAPI framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/0*dazVc5jL5KNhUxT7" /><figcaption><em>Image from official website of uv. Installing </em><a href="https://trio.readthedocs.io/"><em>Trio</em></a><em>’s dependencies with a warm cache.</em></figcaption></figure><h3>Key features:</h3><ul><li>It uses pyproject.toml and uv.lock, no more need for requirements.txt.</li><li>uv.lock ensures <strong>deterministic builds by freezing the exact versions </strong>of packages, guaranteeing reproducibility and stability in CI/CD pipelines and production environments.</li><li>All dependencies — production, development, and others — are consolidated into a <strong>single file, organized under separate groups</strong> for better management.</li><li><strong>It’s extremely fast.</strong> UV leverages an aggressive caching strategy to accelerate package management tasks.</li><li><strong>Virtual environments are handled automatically,</strong> so there’s no need to manually activate them — UV takes care of it for you.</li><li>It also manages the <strong>Python version</strong> for your project.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KJ0py4b_g003aJFdvIg-og.png" /><figcaption>Image generated with DALL·E</figcaption></figure><h3>Let’s Use It!</h3><p>Install astral-uv using the command:</p><pre>sudo snap install astral-uv --classic</pre><p>Check if uv is installed:</p><pre>uv --version</pre><p>Initialize a new project:</p><pre>uv init</pre><p>Uv created following files by running the init command:</p><pre>├── .gitignore         # Files and directories to ignore in Git<br>├── .python-version    # Python version management file<br>├── hello.py           # Hello world Python script<br>├── pyproject.toml     # Dependency and project configuration file<br>├── README.md          # Project documentation</pre><p>Let’s see the file pyproject.toml :</p><pre>[project]<br>name = &quot;uv-test&quot;<br>version = &quot;0.1.0&quot;<br>description = &quot;Add your description here&quot;<br>readme = &quot;README.md&quot;<br>requires-python = &quot;&gt;=3.12&quot;<br>dependencies = []</pre><p>As you can see it’s template file. There is no no dependencies yet.</p><p>Run a python script with uv:</p><pre>uv run hello.py</pre><p>This command created a python virtual environment .venv, installed all dependencies and run script using this environment.</p><p>Let’s add FastAPI framework:</p><pre>uv add fastapi[standard]</pre><p>Create a small Fastapi application in main.py file:</p><pre>from typing import Union<br>from fastapi import FastAPI<br><br>app = FastAPI()<br><br>@app.get(&quot;/&quot;)<br>def read_root():<br>    return {&quot;Hello&quot;: &quot;World&quot;}<br><br>@app.get(&quot;/items/{item_id}&quot;)<br>def read_item(item_id: int, q: Union[str, None] = None):<br>    return {&quot;item_id&quot;: item_id, &quot;q&quot;: q}</pre><p>Run the server:</p><pre>uv run uvicorn main:app --reload</pre><p>After starting the service, Swagger documentation will be available at: <a href="http://127.0.0.1:8000/docs#/">http://127.0.0.1:8000/docs#/</a></p><p>Let’s try to remove the virtual environment. Delete the .venv folder and run the project again. Uv will automatically create a new virtual environment and reinstall the dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JI-jA20xfLlSlnSc" /></figure><h4>Groups for dependencies</h4><p>Uv allows you to create groups for dependencies, which can be very useful when you want to separate them. This is especially beneficial for running applications in production with a minimal set of dependencies, reducing the risk of vulnerabilities.</p><p>For example, let’s add pytest to dev dependencies:</p><pre>uv add --dev pytest</pre><p>We can create groups named as we want. Let’s add ruff to lint group:</p><pre>uv add --group lint ruff</pre><p>After adding dependencies, pyproject.toml file will look like this:</p><pre>[project]<br>name = &quot;test-uv&quot;<br>version = &quot;0.1.0&quot;<br>description = &quot;Add your description here&quot;<br>readme = &quot;README.md&quot;<br>requires-python = &quot;&gt;=3.12&quot;<br>dependencies = [<br>    &quot;fastapi[standard]&gt;=0.115.6&quot;,<br>]<br>[dependency-groups]<br>dev = [<br>    &quot;pytest&gt;=8.3.4&quot;,<br>]<br>lint = [<br>    &quot;ruff&gt;=0.8.2&quot;,<br>]</pre><p>Here, pytest and ruff are added under separate dependency groups.</p><p>Uv ensures all dependency groups are compatible and resolves them together when creating the lockfile.</p><p>We can run the command to install dependencies from uv.lock file:</p><pre>uv sync</pre><p>By default, this command installs all dependency groups. To exclude specific groups, use the --no-group flag:</p><pre>uv sync --no-group dev --no-group lint</pre><h3>Cheat Sheet</h3><p>Initialize a project:</p><pre>uv init</pre><p>Add a dependency:</p><pre>uv add fastapi</pre><p>Add dependencies to a group:</p><pre>uv add --group lint ruff</pre><p>Remove a dependency:</p><pre>uv remove fastapi</pre><p>Install all packages from file uv.lock:</p><pre>uv sync</pre><p>Install packages from pyproject.toml without dev dependencies:</p><pre>uv install --no-group dev</pre><p>Upgrade a package:</p><pre>uv lock --upgrade-package requests</pre><p>View available and installed Python versions:</p><pre>uv python list</pre><p>Install a specific Python version:</p><pre>uv python install 3.12</pre><p>Install an alternative Python implementation, e.g. PyPy:</p><pre>uv python install pypy@3.10</pre><p>Normally Uv should be used as a replacement for pip. But if you want you can generate requirements.txt file from uv.lock :</p><pre>uv export --format requirements-txt &gt; requirements.txt</pre><h3>Conclusion</h3><p>Uv is a powerful and fast package manager for Python projects. I plan to use it in my future projects, and I highly recommend it! :)</p><h3>Useful links</h3><ol><li><a href="https://docs.astral.sh/uv/">https://docs.astral.sh/uv/</a> — Official documentation.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=183e7e428760" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Testing for Applications Built with the Gin Framework and Golang]]></title>
            <link>https://medium.com/@gnetkov/api-testing-for-applications-built-with-the-gin-framework-and-golang-16b187986bf4?source=rss-bd9eb418040f------2</link>
            <guid isPermaLink="false">https://medium.com/p/16b187986bf4</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Fedor GNETKOV]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 22:01:42 GMT</pubDate>
            <atom:updated>2024-12-03T19:56:42.568Z</atom:updated>
            <content:encoded><![CDATA[<h3>Testing Golang application Go+Gin+GORM</h3><p>Hey!</p><p>In the <a href="https://medium.com/@gnetkov/golang-application-template-gin-postgresql-mailhog-pgadmin-docker-compose-a243c29d0bee">previous article</a>, we created an service API using the Gin framework. <strong>In this article, we will add tests for the application.</strong> Let’s go!</p><h4>What we will do in this article:</h4><ul><li><strong>Set Up a Separate Test Database</strong>: We’ll configure a dedicated database specifically for running tests, ensuring test data is isolated and does not interfere with the local development database.</li><li><strong>Implement Data Factories</strong>: We’ll introduce factories to simplify test data creation. These factories will enable you to generate database records with a single line of code, streamlining the testing process.</li><li><strong>Build a Test Client</strong>: We’ll create a test client to simulate API requests. This client will also support authenticated requests, handling automatic authorization to mimic real-user interactions seamlessly.</li></ul><p>As always, <strong>the full application code with tests can be found on GitLab</strong>: <a href="https://gitlab.com/FedorGN/go-gin-test">https://gitlab.com/FedorGN/go-gin-test</a> . It’s dockerized, so you only need to run a single command to run the application: docker compose up .</p><blockquote>In this part, I will only focus on the topic of testing.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-goo784mkErw3guKKbWYKw.png" /><figcaption>Image generated by DALL·E.</figcaption></figure><p>File structure of tests:</p><pre>tests/<br>├── api_tests/                    // Test files for API controllers<br>│   ├── hello_controller_test.go  <br>│   ├── item_controller_test.go<br>│   └── main_test.go<br>├── clients/                      // Client-related utility files used in tests<br>│   └── api_clients.go<br>├── factories/                    // Factory for generating test data<br>│   ├── item_factory.go<br>│   └── user_factory.go<br>└── testutils/                    // Utility files to help with database and data handling in tests<br>    ├── data_test_helper.go<br>    └── db_test_helper.go</pre><p>Let’s start configuration of tests.</p><h3>Database configuration and initialization</h3><p>The main_test.go file is <strong>a special entry point for running tests</strong> in the project.</p><p>File main_test.go :</p><pre>package api_tests<br><br>import (<br> &quot;testing&quot;<br><br> &quot;simple-gin-backend/internal/tests/testutils&quot;<br>)<br><br>func TestMain(m *testing.M) {<br> // Initialize the test suite with the database<br> testutils.InitializeTestSuite(m)<br>}</pre><p>The TestMain function is a special function recognized by Go&#39;s testing framework. It takes a *testing.M argument, which represents the test suite, and its Run method is responsible for running all the tests.</p><p>The TestMain function in this file is executed <strong>once</strong> for the entire test suite before any test runs and after all tests complete. It is used to perform global setup (e.g., initializing a database, creating test data) and teardown logic (e.g., cleaning up resources). In our case, it executes the function <strong>testutils.InitializeTestSuite(m)</strong> where all of this is handled. <strong>Let’s take a look at this function</strong>.</p><p>File db_test_helper.go :</p><pre>package testutils<br><br>import (<br> &quot;database/sql&quot;<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;os&quot;<br> &quot;simple-gin-backend/internal/config&quot;<br> &quot;simple-gin-backend/internal/database&quot;<br> &quot;simple-gin-backend/internal/models&quot;<br> &quot;testing&quot;<br><br> &quot;gorm.io/driver/postgres&quot;<br> &quot;gorm.io/gorm&quot;<br><br> _ &quot;github.com/lib/pq&quot;<br>)<br><br>// Create a new test DB, if it doesn&#39;t exist<br>func createTestDB() {<br>   // Connect to the default database (e.g., postgres) to create the test DB<br>   config.LoadConfig()<br>   defaultDSN := fmt.Sprintf(<br>      &quot;host=%s user=%s password=%s dbname=%s port=%s sslmode=disable&quot;,<br>      config.AppConfig.PostgresHost,<br>      config.AppConfig.PostgresUser,<br>      config.AppConfig.PostgresPassword,<br>      &quot;postgres&quot;,<br>      config.AppConfig.PostgresPort,<br>   )<br>  <br>   db, err := sql.Open(&quot;postgres&quot;, defaultDSN)<br>   if err != nil {<br>      log.Fatalf(&quot;Failed to connect to default database: %v&quot;, err)<br>   }<br>   defer db.Close()<br>  <br>   // Test DB name<br>   testDBName := config.AppConfig.PostgresDb + &quot;_test&quot;<br>  <br>   // Terminate all connections to the test database<br>   _, err = db.Exec(fmt.Sprintf(`<br>    -- Terminate all connections to the test database<br>    SELECT pg_terminate_backend(pg_stat_activity.pid)<br>    FROM pg_stat_activity<br>    WHERE pg_stat_activity.datname = &#39;%s&#39;<br>    AND pid &lt;&gt; pg_backend_pid();<br>   `, testDBName))<br>  <br>   if err != nil {<br>      log.Fatalf(&quot;Failed to terminate connections to the test database %s: %v&quot;, testDBName, err)<br>   }<br>  <br>   // Drop the test database if it exists<br>   _, err = db.Exec(fmt.Sprintf(&quot;DROP DATABASE IF EXISTS %s&quot;, testDBName))<br>   if err != nil {<br>      log.Fatalf(&quot;Failed to drop test database %s: %v&quot;, testDBName, err)<br>   }<br>  <br>   // Create the test database<br>   _, err = db.Exec(fmt.Sprintf(&quot;CREATE DATABASE %s&quot;, testDBName))<br>   if err != nil {<br>    log.Fatalf(&quot;Failed to create test database %s: %v&quot;, testDBName, err)<br>   } else {<br>    log.Printf(&quot;Database %s created successfully&quot;, testDBName)<br>   }<br>}<br><br>// TestDB holds the test database connection<br>var TestDB *gorm.DB<br><br>// SetupTestDatabase sets up the test database connection and runs migrations<br>func SetupTestDatabase() {<br>   config.LoadConfig()<br>   createTestDB()<br>   dsn := fmt.Sprintf(<br>      &quot;host=%s user=%s password=%s dbname=%s port=%s sslmode=disable&quot;,<br>      config.AppConfig.PostgresHost,<br>      config.AppConfig.PostgresUser,<br>      config.AppConfig.PostgresPassword,<br>      config.AppConfig.PostgresDb+&quot;_test&quot;,<br>      config.AppConfig.PostgresPort,<br>   )<br>  <br>   var err error<br>   TestDB, err = gorm.Open(postgres.Open(dsn), &amp;gorm.Config{})<br>   if err != nil {<br>      log.Fatalf(&quot;Failed to connect to test database: %v&quot;, err)<br>   }<br>  <br>   // Run migrations (you can add your models here)<br>   TestDB.AutoMigrate(&amp;models.Item{}, &amp;models.User{})<br>}<br><br>// ResetTestDatabase resets the database after each test<br>func ResetTestDatabase() {<br>   TestDB.Exec(&quot;TRUNCATE TABLE items RESTART IDENTITY CASCADE&quot;)<br>}<br><br>// TearDownTestDatabase closes the database connection<br>func TearDownTestDatabase() {<br>   sqlDB, err := TestDB.DB()<br>   if err != nil {<br>      log.Fatalf(&quot;Failed to close the database: %v&quot;, err)<br>   }<br>   sqlDB.Close()<br>}<br><br>// PatchDatabase replaces the global database.DB with TestDB for testing<br>func PatchDatabase() {<br>   database.DB = TestDB<br>}<br><br>// UnpatchDatabase restores the original database.DB (if needed)<br>func UnpatchDatabase() {<br>   // Reset database.DB back to the development DB after testing<br>   database.InitDB()<br>}<br><br>// InitializeTestSuite sets up the test environment and patches the database connection<br>func InitializeTestSuite(m *testing.M) {<br>   // Initialize the test database<br>   SetupTestDatabase()<br>   // Patch the global database.DB to use the TestDB<br>   PatchDatabase()<br>   // Run all tests<br>   code := m.Run()<br>   // Teardown the database connection<br>   TearDownTestDatabase()<br>   // Unpatch the database<br>   UnpatchDatabase()<br>   // Exit with the test run status code<br>   os.Exit(code)<br>}</pre><p>What does the InitializeTestSuite function do:</p><ol><li>It initializes the test database using the <strong>SetupTestDatabase</strong> function. This function, just in case, checks if the test database exists, and if it doesn’t, it creates the database and runs migrations to set up the tables.</li><li>Patch the global database.DB to use the TestDB. <strong>PatchDatabase()</strong> overrides database.DB with the TestDB, which is specifically configured to use the test database. This ensures that any database calls made by the application during tests interact with the test database.</li><li><strong>Run all tests</strong>.</li><li><strong>Teardown the database connection.</strong> It closes the test database connection.</li><li><strong>Unpatch the database.</strong></li></ol><p>Great! This setup allows us to run tests with a test database without adding test data to the local database.</p><h3>Factories</h3><p>When writing tests, <strong>we often need to create objects in the database.</strong> To avoid repeating the object creation code in every test, we will create factories responsible for populating the database.</p><p>Let’s take a look at UserFactory. File user_factory.go :</p><pre>package factories<br><br>import (<br>   &quot;simple-gin-backend/internal/models&quot;<br>   &quot;simple-gin-backend/internal/tests/testutils&quot;<br>  <br>   &quot;golang.org/x/crypto/bcrypt&quot;<br>)<br><br>// CreateUserFactory generates a user and saves it to the test database<br>// Email: random, Password: &quot;password&quot;<br>func UserFactory() models.User {<br>   hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(&quot;password&quot;), bcrypt.DefaultCost)<br>   user := models.User{<br>      FirstName:    testutils.GenerateRandomString(10),<br>      LastName:     testutils.GenerateRandomString(10),<br>      Email:        testutils.GenerateRandomString(10) + &quot;@example.com&quot;,<br>      PasswordHash: string(hashedPassword),<br>   }<br>   testutils.TestDB.Create(&amp;user)<br>   testutils.TestDB.First(&amp;user, user.ID)<br>   return user<br>}</pre><p>This is a <strong>factory for creating a user in the database</strong>. The email is generated randomly, and the password is always “password”.</p><p>Let’s take a look at the factory for Item. File: item_factory.go.</p><pre>package factories<br><br>import (<br>   &quot;simple-gin-backend/internal/models&quot;<br>   &quot;simple-gin-backend/internal/tests/testutils&quot;<br>)<br><br>// ItemFactory generates an item and saves it to the test database<br>func ItemFactory(userID uint) models.Item {<br>   item := models.Item{<br>      Name:   testutils.GenerateRandomString(10),<br>      UserID: userID,<br>   }<br>   testutils.TestDB.Create(&amp;item)<br>   testutils.TestDB.First(&amp;item, item.ID)<br>   return item<br>}</pre><p>An Item must always have a parent User, so creating an Item requires passing the userID.</p><h3>Test clients</h3><p>I want to write tests for the API routes. To do this, <strong>we’ll create a client specifically for testing routes</strong>. This client should support making test requests both <strong>with and without authentication</strong>.</p><p>File db_test_helper.go :</p><pre>package api_clients<br><br>import (<br> &quot;bytes&quot;<br> &quot;encoding/json&quot;<br> &quot;log&quot;<br> &quot;net/http&quot;<br> &quot;net/http/httptest&quot;<br> &quot;os&quot;<br> &quot;simple-gin-backend/internal/models&quot;<br> &quot;simple-gin-backend/internal/routes&quot;<br> &quot;simple-gin-backend/internal/tests/factories&quot;<br> &quot;testing&quot;<br> &quot;time&quot;<br><br> &quot;github.com/gin-gonic/gin&quot;<br> &quot;github.com/golang-jwt/jwt/v5&quot;<br> &quot;github.com/stretchr/testify/assert&quot;<br>)<br><br>// SetupTestRouter sets up the Gin router for testing purposes<br>func SetupTestRouter() *gin.Engine {<br>   router := gin.Default()<br>   // Register common middleware, routes, etc.<br>   routes.RegisterRoutes(router)<br>   return router<br>}<br><br>// GenerateTestJWT generates a JWT token for testing<br>func GenerateTestJWT(userID uint) (string, error) {<br>   // Define the token claims<br>   claims := jwt.MapClaims{<br>      &quot;user_id&quot;: userID,<br>      &quot;exp&quot;:     time.Now().Add(time.Hour * 24).Unix(),<br>   }<br>  <br>   token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)<br>  <br>   // Sign the token with the secret key<br>   tokenString, err := token.SignedString([]byte(os.Getenv(&quot;SECRET_KEY&quot;)))<br>   if err != nil {<br>      return &quot;&quot;, err<br>   }<br>   return tokenString, nil<br>}<br><br>// AssertResponse checks the response status and body<br>func AssertResponse(t *testing.T, response *httptest.ResponseRecorder, expectedStatus int, expectedBody string) {<br>   assert.Equal(t, expectedStatus, response.Code)<br>   if expectedBody != &quot;&quot; {<br>      assert.JSONEq(t, expectedBody, response.Body.String())<br>   }<br>}<br><br>// TestClient represents a reusable client for API testing<br>type TestClient struct {<br>   Router *gin.Engine<br>   Token  string<br>   User   models.User<br>}<br><br>// PerformRequest is a helper function to perform HTTP requests in tests<br>func (client *TestClient) PerformRequest(method, path string, body interface{}, headers map[string]string) *httptest.ResponseRecorder {<br>   var reqBody *bytes.Reader<br>   if body != nil {<br>      jsonBody, _ := json.Marshal(body)<br>      reqBody = bytes.NewReader(jsonBody)<br>   } else {<br>      reqBody = bytes.NewReader([]byte{})<br>   }<br>  <br>   req, _ := http.NewRequest(method, path, reqBody)<br>  <br>   // Set default headers<br>   req.Header.Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  <br>   // Add the token to the Authorization header if available<br>   if client.Token != &quot;&quot; {<br>      req.Header.Set(&quot;Authorization&quot;, &quot;Bearer &quot;+client.Token)<br>   }<br>  <br>   // Set additional headers if provided<br>   for key, value := range headers {<br>      req.Header.Set(key, value)<br>   }<br>  <br>   w := httptest.NewRecorder()<br>   client.Router.ServeHTTP(w, req)<br>   return w<br>}<br><br>// NewTestClientWithAuth initializes a new TestClient with authentication and creates a user in DB<br>func NewTestClient(authenticate bool) *TestClient {<br>   router := SetupTestRouter()<br>   client := &amp;TestClient{Router: router}<br>  <br>   if authenticate {<br>      user := factories.UserFactory()<br>      token, err := GenerateTestJWT(user.ID)<br>      if err != nil {<br>         log.Fatalf(&quot;Failed to generate JWT token: %v&quot;, err)<br>      }<br>      client.Token = token<br>      client.User = user<br>   }<br>   return client<br>}</pre><p>This file introduces the <strong>TestClient structure</strong> along with its PerformRequest function. Additionally, we’ve included a function to initialize a new instance of TestClient. When the authenticate argument is set to true, a new user is created in the database, and an authentication token is generated for them.</p><h3>Tests of API routes</h3><p>Now that the configuration is complete, let’s write tests. I created two tests: one without authentication and another with mandatory authentication.</p><p>File hello_controller_test.go :</p><pre>package api_tests<br><br>import (<br>   &quot;net/http&quot;<br>   api_clients &quot;simple-gin-backend/internal/tests/clients&quot;<br>   &quot;testing&quot;<br>)<br><br>func TestGetHelloWorld(t *testing.T) {<br>   // Set up the Test Client using the reusable function<br>   client := api_clients.NewTestClient(false)<br>  <br>   // Perform a request to the route<br>   response := client.PerformRequest(&quot;GET&quot;, &quot;/&quot;, nil, nil)<br>   // Assert the response<br>   api_clients.AssertResponse(t, response, http.StatusOK, `&quot;Hello, world!&quot;`)<br>}</pre><p>This test performs a <strong>GET request</strong> and compares the response body with the expected result “Hello, world!”.</p><p>File item_controller_test.go :</p><pre>package api_tests<br><br>import (<br> &quot;encoding/json&quot;<br> &quot;net/http&quot;<br> &quot;simple-gin-backend/internal/models&quot;<br> api_clients &quot;simple-gin-backend/internal/tests/clients&quot;<br> &quot;simple-gin-backend/internal/tests/factories&quot;<br> &quot;testing&quot;<br><br> &quot;github.com/stretchr/testify/assert&quot;<br>)<br><br>func TestGetItems(t *testing.T) {<br> // Initialize the test client with authentication (creates a user and token)<br> client := api_clients.NewTestClient(true)<br><br> // Create items for the authenticated user using the factory<br> item1 := factories.ItemFactory(client.User.ID)<br> item2 := factories.ItemFactory(client.User.ID)<br><br> user2 := factories.UserFactory()<br> factories.ItemFactory(user2.ID)<br><br> // Perform a GET request to /items<br> response := client.PerformRequest(&quot;GET&quot;, &quot;/items&quot;, nil, nil)<br><br> // Assert that the response code is 200 OK<br> assert.Equal(t, http.StatusOK, response.Code)<br><br> // Define the expected items response (make sure the structure matches the JSON output)<br> expectedBody := []models.Item{<br>  item1,<br>  item2,<br> }<br><br> // Unmarshal the response to a slice of items and assert it matches the expected data<br> var actualItems []models.Item<br> err := json.Unmarshal(response.Body.Bytes(), &amp;actualItems)<br> if err != nil {<br>  t.Fatalf(&quot;Failed to unmarshal response: %v&quot;, err)<br> }<br><br> // Assert that the returned items match what was created<br> assert.Equal(t, expectedBody, actualItems)<br>}</pre><p>TestGetItems is a bit more complex. It creates a client with a user and two items, where the created user is the parent of these items. This means that when we make a request, we expect to receive a list of the items we created earlier.</p><p>Now, we will run the tests inside a running Docker container using the following command:</p><pre>docker compose exec todo-api go test ./internal/tests/api_tests/</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xP8nJBhta_FAnk_ynrQ-Gg.png" /><figcaption>Result of tests execution.</figcaption></figure><p>Let’s modify the “Hello, World!” test so that it fails:</p><pre>api_clients.AssertResponse(t, response, http.StatusOK, `&quot;Goodbye, world!&quot;`)</pre><p>The result of running the tests this time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uviNGaHe87C5ffNgQThq-g.png" /></figure><p>We got an error indicating that the expected result does not match the actual result, which means our tests are indeed working.</p><h3>Conclusion</h3><p><strong>We created tests for the API application in Golang.</strong> Now, we can integrate these tests into CI/CD pipelines and ensure that the application works as expected after modifications, improvements, and code refactoring.</p><h3>Useful links</h3><ol><li><a href="https://gin-gonic.com/docs/">https://gin-gonic.com/docs/</a> — Gin framework.</li><li><a href="https://medium.com/@gnetkov/golang-application-template-gin-postgresql-mailhog-pgadmin-docker-compose-a243c29d0bee">https://medium.com/@gnetkov/golang-application-template-gin-postgresql-mailhog-pgadmin-docker-compose-a243c29d0bee</a> — article “Golang Application Template (Gin, PostgreSQL, MailHog, PGAdmin, Docker Compose)”.</li><li><a href="https://gitlab.com/FedorGN/go-gin-test">https://gitlab.com/FedorGN/go-gin-test</a> — GitLab repository of the project.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16b187986bf4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GitLab CI/CD configuration for Python (Django) and TypeScript (ReactJS) application]]></title>
            <link>https://medium.com/@gnetkov/gitlab-ci-cd-configuration-for-python-django-and-typescript-reactjs-application-bcc78d593cdf?source=rss-bd9eb418040f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcc78d593cdf</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[cicd]]></category>
            <dc:creator><![CDATA[Fedor GNETKOV]]></dc:creator>
            <pubDate>Sun, 03 Nov 2024 14:13:56 GMT</pubDate>
            <atom:updated>2024-11-03T18:59:30.636Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey! This guide will show you how to set up GitLab CI/CD to run code quality checks every time you make changes to your code. It also explains key GitLab terms and how GitLab CI/CD works.</p><p>We’ll use a project that combines a Django backend with a ReactJS frontend, and we’ll set up GitLab CI/CD for automated linting and testing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7mXgs3njQTz18mnSIxr-lw.png" /><figcaption>Image generated by DALL·E</figcaption></figure><p>As always you can find the entire project code on GitLab at the following link: <a href="https://gitlab.com/FedorGN/gitlab-ci-cd-template">https://gitlab.com/FedorGN/gitlab-ci-cd-template</a> .</p><h3>About GitLab CI/CD</h3><blockquote>GitLab CI/CD is a tool for automating the process of checking, testing, building and deploying code.</blockquote><p>It allows defining pipelines in a .gitlab-ci.yml file, so each code change triggers tests and deployments automatically, ensuring code quality and speeding up development.</p><h4>Main <strong>vocabulary terms</strong> used in GitLab CI/CD:</h4><ol><li><strong>Pipeline</strong>: A set of automated processes that run in a specific order to build, test, and deploy your application. Each time code is pushed or a merge request is created, a pipeline can be triggered.</li><li><strong>Job</strong>: A single task in a pipeline, such as running tests, building code, or deploying. Each job is defined with specific commands and runs in its own environment.</li><li><strong>Stage</strong>: A grouping of jobs that run in a specific order. Common stages include build, test, and deploy. Jobs within a stage run in parallel, while stages run sequentially by default.</li><li><strong>Runner</strong>: An agent that executes the jobs defined in your .gitlab-ci.yml. Runners can be hosted by GitLab or set up on your own infrastructure (e.g., on your server or cloud instance).</li><li><strong>.gitlab-ci.yml</strong>: The configuration file for GitLab CI/CD, located in the root of the project repository. This file defines the pipeline structure, jobs, stages, and rules for when to trigger jobs.</li><li><strong>Artifacts</strong>: Files or directories generated by a job that can be passed to later stages or downloaded (e.g., compiled code, test reports). Artifacts can be defined within jobs to save their output.</li><li><strong>Cache</strong>: Cached files are saved between jobs or pipeline runs to speed up builds (e.g., dependencies). Unlike artifacts, caches are not preserved after the pipeline finishes.</li><li><strong>Environment variables</strong>: Key-value pairs used to store data that can be accessed within jobs, such as API keys, passwords, or configuration settings. Variables can be defined in the .gitlab-ci.yml file, project settings, or GitLab’s CI/CD environment settings.</li><li><strong>Environment</strong>: A deployment target, such as staging, production, or testing. Environments define where code is deployed, and GitLab tracks deployments per environment.</li><li><strong>Trigger</strong>: A way to start a pipeline or specific job manually or through an API. You can use triggers for scenarios like scheduled jobs or automated deployments from other applications.</li><li><strong>Rules</strong>: Conditions defined within jobs to control when and under what circumstances a job runs. For example, rules can specify file changes, branches, or manual execution.</li><li><strong>Image</strong>: A Docker image used as the environment for a job. It provides the necessary runtime and dependencies for executing commands in the job.</li><li><strong>Manual Job</strong>: A job that doesn’t run automatically and requires a manual trigger (e.g., clicking “Play” in the GitLab UI).</li><li><strong>When</strong>: A keyword that defines when a job should run. Options include on_success, on_failure, always, and manual.</li><li><strong>Dependencies</strong>: Defines which jobs’ artifacts are downloaded for a job, allowing data sharing between jobs.</li><li><strong>Include</strong>: Allows importing configurations from other files or templates into the main .gitlab-ci.yml file, enabling code reuse.</li><li><strong>Timeout</strong>: Sets a maximum execution time for a job. If a job exceeds the timeout, it’s canceled.</li><li><strong>Protected</strong>: A keyword to restrict jobs to specific branches (like main or production) and/or specific user roles, adding security to sensitive actions like deployments.</li><li><strong>Retry</strong>: Defines the number of times a job should retry on failure. Useful for handling flaky tests or network-related issues.</li></ol><p>When we commit changes to a GitLab repository with CI/CD enabled, GitLab CI/CD automatically kicks off a series of steps to build, test, and possibly deploy the code. Here’s a breakdown of the process.</p><h4>GitLab CI/CD Pipeline Execution:</h4><p><strong>1. Detecting Changes and Triggering a Pipeline:</strong></p><ul><li>Upon pushing a commit or creating a merge request, <strong>GitLab detects the changes</strong>.</li><li>GitLab checks the .gitlab-ci.yml file located in the root of the repository. This file defines the <strong>CI/CD pipeline configuration</strong>, including jobs, stages, and rules.</li><li>Based on this configuration, GitLab decides <strong>if a pipeline should start </strong>(e.g., based on branch name, file changes, or specific keywords in commit messages).</li></ul><p><strong>2. Pipeline Initialization:</strong></p><ul><li><strong>GitLab creates a pipeline </strong>consisting of stages and jobs according to the order and rules specified in .gitlab-ci.yml. Each pipeline runs in stages (e.g., build, test, deploy), and within each stage, multiple jobs can run in parallel if they are independent.</li></ul><p><strong>3. Assigning Runners:</strong></p><ul><li><strong>Each job in the pipeline is assigned to a runner</strong>, which is an agent responsible for executing the job’s commands.</li><li>GitLab assigns the job to an available runner based on the job’s requirements and the runner’s configuration. Runners can be shared (hosted by GitLab) or specific to a project, group, or instance (self-hosted).</li></ul><p><strong>4. Executing Jobs in Stages:</strong></p><ul><li>Within each stage, <strong>runners execute the commands defined in each job</strong> (such as installing dependencies, running tests, or building the code).</li><li>If a Docker image is specified, GitLab uses it as the environment for running the job, ensuring <strong>consistency in dependencies and runtime</strong>.</li><li>Jobs can save files as <strong>artifacts </strong>or <strong>cache</strong> dependencies to reuse in other jobs or pipeline runs, speeding up the process.</li><li><strong>Once all jobs in a stage are complete, the next stage begins</strong>. If a job fails and is not configured to allow failure, the pipeline halts.</li></ul><p><strong>5. Testing and Feedback:</strong></p><ul><li>As jobs complete, <strong>GitLab provides real-time feedback</strong> on their success or failure. For example, if you have test jobs in your pipeline, GitLab displays results, logs, and any artifacts generated, so you can debug or fix issues.</li></ul><p><strong>6. Deployment (if configured):</strong></p><ul><li>If the pipeline reaches the deploy stage, it deploys the application to a specified environment (e.g., staging or production).</li><li>GitLab can use environments and protected branches to control access to deployments, ensuring that only specific branches or users can trigger production deployments.</li></ul><p><strong>7. Completion and Notifications:</strong></p><ul><li>Once all stages and jobs in the pipeline are complete, GitLab marks the pipeline as successful or failed.</li></ul><h3>Adding GitLab CI/CD to the project</h3><p>What will we add to the project? I want to add <strong>three stages</strong>, each performing specific tasks:</p><p><strong>1. lint - code quality checks </strong>using the following tools:</p><ul><li><strong>Codespell</strong> for fixing common misspellings.</li><li><strong>Ruff</strong> for Python linting and formatting.</li><li><strong>Mypy</strong> for Python type checking, ensuring type safety in the backend code.</li><li><strong>Prettier</strong> for frontend code formatting.</li><li><strong>ESLint</strong> for frontend code quality.</li></ul><p>2.<strong> test -</strong> running tests:</p><ul><li>Backend tests</li><li>Frontend tests</li></ul><p><strong>3. build - generation of the production build</strong>, saving it to artifacts for subsequent deployment.</p><p>In this project, I won’t be covering deployment.</p><p>I’ll be using my <strong>previous pre-commit template</strong>. More details about this project can be found in this article: <a href="https://medium.com/@gnetkov/automating-code-quality-control-with-pre-commit-hooks-fdbc1ec5cfea">Automating Code Quality Control with Pre-commit Hooks</a>. This repository contains <strong>a small Python application</strong> on the Django framework and <strong>a frontend application in TypeScript </strong>on the ReactJS framework. Additionally, pre-commit is already being used for code quality control in the local environment. I will use pre-commit in GitLab CI/CD as well <strong>to avoid code duplication and reuse existing tools</strong>.</p><p>In that project, pre-commit is used to run checks for:</p><ul><li>Codespell</li><li>Ruff</li><li>Mypy</li><li>Prettier</li><li>ESLint</li><li>Backend tests</li><li>Frontend tests</li></ul><p>Instead of configuring all these tools to run in the GitLab CI/CD YAML file, I just <strong>want to run pre-commit, which will perform everything necessary</strong>. But I want to run pre-commit in the lint stage and run tests in the test stage. I don’t want to run tests in lint stage. Therefore, I updated the pre-commit configuration file slightly.</p><p>Let’s look at the pre-commit configuration.</p><pre>repos:<br> # Codespell for common misspellings<br> - repo: https://github.com/codespell-project/codespell<br>   rev: v2.3.0<br>   hooks:<br>     - id: codespell<br>       name: Spell Checker (backend and frontend)<br>       files: ^(backend|frontend)/ # Only backend and frontend directories<br>       args: [&quot;--exclude-file=frontend/package-lock.json&quot;]<br>       stages: [pre-commit]<br> # Ruff for Python formatting and linting<br> - repo: https://github.com/astral-sh/ruff-pre-commit<br>   rev: v0.7.0<br>   hooks:<br>     - id: ruff<br>       name: Ruff Linter (backend)<br>       args: [&quot;--fix&quot;] # Automatically fix issues (auto-format)<br>       files: ^backend/ # Only backend folder<br>       stages: [pre-commit]<br>     - id: ruff-format<br>       name: Ruff Formatter (backend)<br>       files: ^backend/ # Only backend folder<br>       stages: [pre-commit]<br> # Mypy to check type annotations<br> - repo: https://github.com/pre-commit/mirrors-mypy<br>   rev: v1.0.1<br>   hooks:<br>     - id: mypy<br>       name: Mypy Type Checker (backend)<br>       args: [&quot;--explicit-package-bases&quot;]<br>       additional_dependencies:<br>         [<br>           django-stubs==5.1.0,<br>           django-stubs-ext==5.1.0,<br>           pydantic==2.9.2,<br>           django-ninja==1.3.0,<br>         ]<br>       files: ^backend/<br>       stages: [pre-commit]<br> # Prettier for frontend formatting<br> - repo: https://github.com/pre-commit/mirrors-prettier<br>   rev: &quot;v4.0.0-alpha.8&quot;<br>   hooks:<br>     - id: prettier<br>       name: Prettier Formatter (frontend)<br>       files: ^frontend/.*\.(js|jsx|ts|tsx|json|css|scss|md)$<br>       stages: [pre-commit]<br><br><br> # ESLint for frontend linting<br> - repo: https://github.com/pre-commit/mirrors-eslint<br>   rev: v9.13.0<br>   hooks:<br>     - id: eslint<br>       name: ESLint Linter (frontend)<br>       # entry: npx eslint --config frontend/eslint.config.js<br>       entry: ./scripts/run_eslint.sh<br>       files: ^.*\.(js|jsx|ts|tsx)$<br>       types: [file]<br>       stages: [pre-commit]<br> - repo: local<br>   hooks:<br>     # Backend Django tests<br>     - id: django-tests<br>       name: Django Tests (backend)<br>       entry: bash -c &quot;if [ -z [ -z \&quot;${CI:-}\&quot; ]; then cd backend &amp;&amp; python manage.py test; else exit 0; fi&quot; # THIS LINE IS CHANGED <br>       language: system<br>       pass_filenames: false<br>       stages: [pre-commit]<br><br><br>     # Frontend ReactJS tests<br>     - id: react-tests<br>       name: React Tests (frontend)<br>       # Execute tests only if CI is empty or not set<br>       entry: bash -c &quot;if [ -z \&quot;${CI:-}\&quot; ]; then cd frontend &amp;&amp; npm run test -- --watchAll=false --bail; else exit 0; fi&quot; # THIS LINE IS CHANGED <br>       language: system<br>       pass_filenames: false<br>       stages: [pre-commit]</pre><p>I modified the entry command in the django-tests and react-tests hooks, adding an if-else condition. Now, <strong>these hooks will only run if the environment variable </strong><strong>CI is not empty.</strong> CI=true when running CI/CD jobs on runners. This way, these hooks will run in the local environment and will be skipped on runners in the lint stage.</p><p>The GitLab CI/CD configuration is done using the .gitlab-ci.yml file. This file should be added to the root directory of the project.</p><p>Let’s take a look at the .gitlab-ci.yml file.</p><pre>stages:<br> - lint<br> - test<br> - build<br><br><br># Linting &amp; Formatting<br>lint:<br> stage: lint<br> image: python:3.12<br> script:<br>   - pip install pre-commit<br>   - pre-commit run --all-files<br> rules:<br>   # Run only when files in the folders backend and front<br>   - changes:<br>       - backend/**/*<br>       - frontend/**/*<br><br><br># Unit Tests - Backend<br>backend_unit_tests:<br> stage: test<br> image: python:3.12<br> script:<br>   - pip install -r backend/requirements.txt<br>   - cd backend<br>   - python manage.py test<br> # Run only if files in folder backend changed<br> rules:<br>   - changes:<br>       - backend/**/*<br><br><br># Unit Tests - Frontend<br>frontend_unit_tests:<br> stage: test<br> image: node:16<br> script:<br>   - cd frontend<br>   - npm install<br>   - npm run test<br> # Run only if files in folder frontend changed<br> rules:<br>   - changes:<br>       - frontend/**/*<br><br><br># Build Frontend<br>frontend_build:<br> stage: build<br> image: node:20<br> script:<br>   - cd frontend<br>   - npm install<br>   - npm run build<br> rules:<br>   # Run only if files in folder frontend changed<br>   - changes:<br>       - frontend/**/*<br> # Saved the build in the artifacts<br> artifacts:<br>   paths:<br>     - frontend/build/</pre><p>I defined three stages: lint, test, and build at the beginning of the file.</p><p>In the lint job, I use the Docker image python:3.12 for the job to run in. I install pre-commit and run it for all files. rules specify that this job will only run if at least one file in the frontend or backend folders has been modified.</p><p>This way, we run all checks defined in pre-commit, without needing to define them again in GitLab CI/CD, and the backend and frontend tests won’t run on the runners.</p><p>The test stage has two jobs: backend_unit_tests and frontend_unit_tests. In the backend, we install packages from requirements.txt and run tests. In the frontend, we install packages and run frontend tests.</p><p>The last stage, build, serves to bundle the frontend application. The build output will be saved as artifacts so that in the next stage,<strong> it can be deployed to the production server</strong>.</p><p>If any of the processes we run fail, it will return an exit code 1, and the job will fail. In the web interface, we’ll be able to see the logs and the reason the job failed.</p><p>That’s all for the configuration.</p><h3><strong>Testing the configuration</strong></h3><blockquote>Now let’s test the configuration we created.</blockquote><p>I made a commit, fixed the frontend tests in the project, and pushed the changes to the repository. GitLab CI/CD will now start the pipeline. I can view the pipeline’s progress by clicking on Build -&gt; Pipelines in the web interface menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-NTBFHb0JNG3KAvW" /><figcaption>Page “Pipelines”</figcaption></figure><p>I see that <strong>all stages were completed without errors</strong>.</p><p>By clicking on the Pipeline ID, I can view the execution details, specifically the jobs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LbjfPAwDHq8dknft" /><figcaption>Page “Papileine”</figcaption></figure><p>Since I only made changes in the frontend folder in the last commit, the backend_unit_tests job was skipped. By clicking on one of the jobs, we go to the job page, where we can view the job details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yNTYWimxjRfO34rS" /><figcaption>Page “Job lint”</figcaption></figure><p>Let’s now modify the backend and frontend tests so that they fail, and observe the Pipeline results.</p><p>I modified the tests to fail. Normally, pre-commit would detect that the tests are not OK, but I made the commit with the --no-verify flag, which commits without running the pre-commit hooks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VjeffRMjX7L8MVNQ" /><figcaption>Page “Pipeline”</figcaption></figure><p>Lint is OK because tests are not run in the lint job. In the test stage, both backend and frontend tests were executed, running in parallel. We see that the final build job was skipped since the previous jobs completed with errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0ma63fOOxWXlP1zt" /><figcaption>Page “Job backend_unit_tests”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gV0wFQ8a_PsE3y78" /><figcaption>Page “Job frontend_unit_tests”</figcaption></figure><p>On the jobs page, <strong>we see which tests were failed</strong>. Now we know what we need to fix in the project.</p><h3><strong>Conclusion</strong></h3><p>In this project, <strong>we configured a GitLab CI/CD pipeline to do code quality checks, automated testing, and build creation</strong>. This setup can be integrated into the development workflow, enhancing efficiency and reliability.</p><p>By automating linting with tools like Codespell, Ruff, Mypy, Prettier, and ESLint in the lint stage, we ensure code quality. The test stage runs backend and frontend tests in parallel, catching issues. Additionally, the build stage generates and saves production-ready artifacts, preparing the project for future deployment.</p><p>This CI/CD pipeline enforces consistent standards and provides visibility into errors, making it easier to maintain code quality and prepare for deployments. Overall, this setup enhances productivity and code integrity, laying the groundwork for a robust development process.</p><h3>My Other Articles on Related Topics</h3><ol><li><a href="https://medium.com/@gnetkov/testing-fastapi-application-with-pytest-57080960fd62">Testing FastAPI Application with Pytest</a></li><li><a href="https://medium.com/@gnetkov/e2e-tests-with-playwright-3b011df85791">E2E tests with PlayWright</a></li><li><a href="https://medium.com/@gnetkov/automating-code-quality-control-with-pre-commit-hooks-fdbc1ec5cfea">Automating Code Quality Control with Pre-commit Hooks</a></li></ol><h3>Useful Links</h3><ol><li><a href="https://gitlab.com/FedorGN/gitlab-ci-cd-template">https://gitlab.com/FedorGN/gitlab-ci-cd-template</a> — repository with code of this project project.</li><li><a href="https://docs.gitlab.com/ee/topics/build_your_application.html">https://docs.gitlab.com/ee/topics/build_your_application.html</a> — GitLab CI/CD documentation.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcc78d593cdf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Code Quality Control with Pre-commit Hooks]]></title>
            <link>https://medium.com/@gnetkov/automating-code-quality-control-with-pre-commit-hooks-fdbc1ec5cfea?source=rss-bd9eb418040f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdbc1ec5cfea</guid>
            <category><![CDATA[pre-commit]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[code-quality]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cicd]]></category>
            <dc:creator><![CDATA[Fedor GNETKOV]]></dc:creator>
            <pubDate>Mon, 21 Oct 2024 16:07:49 GMT</pubDate>
            <atom:updated>2025-01-01T10:23:47.492Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi, this article is about how to <strong>automatically run formatting, linting, and unit tests using pre-commit before each commit</strong> in a local development environment. We will walk through this with an example of a repository featuring a Python backend with the Django framework and a TypeScript frontend with the ReactJS framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FNMn_ctghrvHCnIWlDENRA.png" /></figure><p>We want to add automatic code quality control before each commit to the repository.</p><h4>What do we want to do before commit?</h4><ul><li>Automatic spell checking to avoid simple typos.</li><li>Automatic code formatting.</li><li>Automatic code quality checks (linting).</li><li>Running all unit tests on both the backend and frontend.</li></ul><p>Let’s implement this using pre-commit.</p><h3>What is Pre-commit?</h3><p>Pre-commit is a framework for managing and automating pre-commit hooks, which are scripts that run automatically before a commit is finalized in a version control system like Git. These hooks are designed to check the code for issues and ensure that only high-quality code is committed to repository.</p><h4>Key Features of Pre-commit:</h4><ul><li><strong>Automated Code Quality Checks</strong>: Pre-commit hooks automatically run checks like code formatting, linting, type checking, and running tests before committing changes.</li><li><strong>Wide Tool Support</strong>: It supports various tools for Python, JavaScript, and many other languages and frameworks.</li><li><strong>Customizable Hooks</strong>: It’s possible to define your own hooks or choose from a wide range of pre-defined hooks.</li><li><strong>Cross-language Support</strong>: Pre-commit can handle hooks written in different languages and apply them across different types of files in your project.</li></ul><h4>How Pre-commit Works:</h4><ol><li><strong>Pre-commit Configuration</strong>: Define a p.pre-commit-config.yaml file in your project that specifies the hooks to be run.</li><li><strong>Install Hooks</strong>: Run pre-commit install to set up the hooks for your Git repository:<br>- Install pre-commit: pip install pre-commit <br>- Install the hooks: pre-commit install</li><li><strong>Run Automatically</strong>: Every time you run git commit, the hooks are triggered and check your code for errors before the commit is completed. If any of the hooks fail (e.g., code formatting issues or test failures), the commit is rejected.</li><li><strong>Fix and Retry</strong>: You can fix the issues identified by the hooks and retry the commit.</li></ol><p>You can find more information about installing pre-commit on the official website:<a href="https://pre-commit.com/"> https://pre-commit.com/</a>.</p><p>Here, I assume that we have already set up a python virtual environment and installed pre-commit.</p><h4>The project structure.</h4><pre>precommit-template/<br>│<br>├── backend/                # Django backend<br>│   ├── apidemo/            # Example Django app with a single endpoint<br>│   ├── manage.py           # Django entry point<br>│   └── requirements.txt    # Backend dependencies<br>│<br>└── frontend/               # React frontend<br>│   ├── src/                # Source files<br>│   ├── package.json        # Frontend dependencies<br>│   ├── eslint.config.js    # ESLint configuration file<br>│   └── .prettierrc         # Prettier configuration file<br>│<br>├── .env                    # File with env variables for the configuration of the app<br>├── .env.example            # Example of .env<br>├── .gitignore              # Untracked files that Git should ignore<br>├── .pre-commit-config.yaml # Pre-commit configuration file<br>├── pyproject.toml          # Configuration file used by python tools<br>└── README.md               # Project documentation</pre><p>As usual, you can find the full project on GitLab: <a href="https://gitlab.com/FedorGN/precommit-template">https://gitlab.com/FedorGN/precommit-template</a>.</p><h3>Configuration of Pre-commit</h3><p>The configuration for Pre-commit is done in the .pre-commit-config.yaml file. This file is used by the Pre-commit framework to define a set of hooks that should run automatically before making a Git commit.</p><p>This file specifies which tools (linters, formatters, etc.) should run, which files they should be applied to, and when they should be triggered (e.g., before a commit or push).</p><p>Let’s go over the .pre-commit-config.yaml file from the project.</p><pre>repos:<br> # Codespell for common misspellings<br> - repo: https://github.com/codespell-project/codespell<br>   rev: v2.3.0<br>   hooks:<br>     - id: codespell<br>       name: Spell Checker (backend and frontend)<br>       files: ^(backend|frontend)/ # Only backend and frontend directories<br>       args: [&quot;--exclude-file=frontend/package-lock.json&quot;]<br>       stages: [pre-commit]<br> # Ruff for Python formatting and linting<br> - repo: https://github.com/astral-sh/ruff-pre-commit<br>   rev: v0.7.0<br>   hooks:<br>     - id: ruff<br>       name: Ruff Linter (backend)<br>       args: [&quot;--fix&quot;] # Automatically fix issues<br>       files: ^backend/ # Only backend folder<br>       stages: [pre-commit]<br>     - id: ruff-format<br>       name: Ruff Formatter (backend)<br>       files: ^backend/ # Only backend folder<br>       stages: [pre-commit]<br> # Mypy to check type annotations<br> - repo: https://github.com/pre-commit/mirrors-mypy<br>   rev: v1.0.1<br>   hooks:<br>     - id: mypy<br>       name: Mypy Type Checker (backend)<br>       args: [&quot;--explicit-package-bases&quot;]<br>       additional_dependencies:<br>         [<br>           django-stubs==5.1.0,<br>           django-stubs-ext==5.1.0,<br>           pydantic==2.9.2,<br>           django-ninja==1.3.0,<br>         ]<br>       files: ^backend/<br>       stages: [pre-commit]<br> # Prettier for frontend formatting<br> - repo: https://github.com/pre-commit/mirrors-prettier<br>   rev: &quot;v4.0.0-alpha.8&quot;<br>   hooks:<br>     - id: prettier<br>       name: Prettier Formatter (frontend)<br>       files: ^frontend/.*\.(js|jsx|ts|tsx|json|css|scss|md)$<br>       stages: [pre-commit]<br><br><br> # ESLint for frontend linting<br> - repo: https://github.com/pre-commit/mirrors-eslint<br>   rev: v9.13.0<br>   hooks:<br>     - id: eslint<br>       name: ESLint Linter (frontend)<br>       entry: npx eslint --config frontend/eslint.config.js<br>       files: ^frontend/.*\.(js|jsx|ts|tsx)$<br>       types: [file]<br>       stages: [pre-commit]<br> - repo: local<br>   hooks:<br>     # Backend Django tests<br>     - id: django-tests<br>       name: Django Tests (backend)<br>       entry: bash -c &quot;cd backend &amp;&amp; python manage.py test&quot;<br>       language: system<br>       pass_filenames: false<br>       stages: [pre-commit, pre-push]<br>     # Frontend React (Jest) tests<br>     - id: react-tests<br>       name: React Tests (frontend)<br>       entry: bash -c &quot;cd frontend &amp;&amp; npm run test -- --watchAll=false --bail&quot;<br>       language: system<br>       pass_filenames: false<br>       stages: [pre-commit, pre-push]</pre><p>In this file, we have defined the following hooks:</p><ul><li><strong>codespell</strong> — for detecting typos. It checks both backend and frontend code.</li><li><strong>ruff</strong> — The Ruff Linter is an extremely fast Python linter designed as a drop-in replacement for Flake8 (plus dozens of plugins), isort, pydocstyle, pyupgrade, autoflake, and more. It checks Python code only on the backend.</li><li><strong>ruff-format</strong> — The Ruff formatter is an extremely fast Python code formatter designed as a drop-in replacement for Black. It is used only for Python code on the backend.</li><li><strong>mypy</strong> — Mypy is a static type checker for Python that aims to combine the benefits of dynamic (or “duck”) typing and static typing. It is used only for Python code on the backend.</li><li><strong>prettier</strong> — Prettier is a code formatter with support for TypeScript (and other languages). It is used only for formatting TypeScript code on the frontend.</li><li><strong>eslint</strong> — ESLint is a tool for identifying and reporting on patterns found in ECMAScript/JavaScript code, with the goal of making the code more consistent and avoiding bugs. It is used only for TypeScript code on the frontend.</li><li><strong>django-tests</strong> — A hook for running backend unit tests in Django.</li><li><strong>react-tests</strong> — A hook for running frontend unit tests in ReactJS.</li></ul><p>I use <strong>codespell</strong> because it is helpful for spotting and fixing simple typos in text, documentation, and code comments. It helps avoid mistakes like writing “fetature” instead of “feature.”</p><p>I use <strong>ruff</strong> as both a linter and a formatter because it is written in Rust, and it is much, much faster — up to 200 times faster than other popular tools like Flake8, pylint, and others. This speed is very noticeable. Ruff can be used both as a linter and a formatter, which is why I use it for both code quality checks and formatting.</p><p>I really like using <strong>mypy</strong> in Python projects because it allows for type checking. This helps prevent errors and makes the code more stable.</p><p><strong>Prettier</strong> is one of the most popular formatters for JS/TS, and <strong>ESLint</strong> is one of the most popular linters for JS/TS.</p><p>The last two hooks are for <strong>unit tests</strong>. Before committing changes to a branch, I want to ensure that the code doesn’t break any existing functionality.</p><p>Each tool can be configured:</p><ul><li>Configuration for the Python tools is located in the pyproject.toml file.</li><li>Configuration for <strong>Prettier</strong> is in the frontend/.prettierrc file.</li><li>Configuration for <strong>ESLint</strong> is in the frontend/.eslintrc.json file.</li></ul><p>File pyproject.toml :</p><pre>[tool.ruff]<br>lint.select = [    <br> # pycodestyle<br> &quot;E&quot;,<br> # Pyflakes<br> &quot;F&quot;,<br> # pyupgrade<br> &quot;UP&quot;,<br> # flake8-bugbear<br> &quot;B&quot;,<br> # flake8-simplify<br> &quot;SIM&quot;,<br> # isort<br> &quot;I&quot;,]  # Rules to apply<br>lint.ignore = []                 # Example of ignoring specific rules<br>target-version = &quot;py312&quot;         # Target Python version<br>line-length = 100                # Line length for formatting<br>lint.fixable = [&quot;ALL&quot;]           # Allow automatic fixes for all fixable issues<br><br>[tool.ruff.lint.isort]<br>force-single-line = true         # One import per line<br><br>[tool.mypy]<br>ignore_missing_imports = false   # Display error for all missing imports<br>strict = true                    # Enable more checks</pre><p>File frontend/.prettierrc :</p><pre>{<br>   &quot;singleQuote&quot;: true,<br>   &quot;semi&quot;: false,<br>   &quot;trailingComma&quot;: &quot;es5&quot;,<br>   &quot;tabWidth&quot;: 2,<br>   &quot;printWidth&quot;: 100<br> }</pre><p>File frontend/.eslintrc.json :</p><pre>import eslintPluginReact from &#39;eslint-plugin-react&#39;<br>import typescriptParser from &#39;@typescript-eslint/parser&#39;<br>import typescriptPlugin from &#39;@typescript-eslint/eslint-plugin&#39;<br><br><br>export default [<br> {<br>   files: [&#39;**/*.{js,jsx,ts,tsx}&#39;],<br>   languageOptions: {<br>     ecmaVersion: 2022,<br>     sourceType: &#39;module&#39;,<br>     parser: typescriptParser,<br>     parserOptions: {<br>       ecmaFeatures: {<br>         jsx: true,<br>       },<br>     },<br>   },<br>   plugins: {<br>     react: eslintPluginReact,<br>     &#39;@typescript-eslint&#39;: typescriptPlugin,<br>   },<br>   rules: {<br>     &#39;@typescript-eslint/no-unused-vars&#39;: &#39;error&#39;, // Disallow unused variables in TS<br>     &#39;@typescript-eslint/explicit-function-return-type&#39;: &#39;warn&#39;, // Encourage explicit return types<br>   },<br>   settings: {<br>     react: {<br>       version: &#39;detect&#39;,<br>     },<br>   },<br> },<br>]</pre><p><strong>ecmaVersion</strong> indicates the ECMAScript version of the code being linted, determining both the syntax and the available global variables.<br>Additionally, you need to install the <strong>typescript</strong> plugin so that ESLint can work with TypeScript files.</p><p>Once the configuration is complete, we can run the checks using the following command:</p><pre>pre-commit run --all-files</pre><p>This command runs all hooks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9iZUCnRQACPV2dNT" /></figure><p>All hooks were executed without errors.</p><h3>Testing the Hooks</h3><p>Let’s test how the hooks work.</p><p>I’ll intentionally introduce an error in the docstring of one of the Python files by writing “feture” instead of “feature.”<br>The result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hJwQXHsFp2-wdppm" /></figure><p>It’s worth mentioning that <strong>codespell</strong> doesn’t always catch every typo, but it’s much better than nothing.</p><p>Next, I’ll add an unused variable to a Python file. Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uBDCpE7ZCqnvtknJ" /></figure><p>Now, let me edit a Python file by adding some empty lines and then run all pre-commit hooks again.<br>The result will be below. <strong>Ruff</strong> will format the file and notify us about it. The hook “Ruff Formatter (backend)” will not pass because the process doesn’t return a 0 exit code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GxpZ-13Ftp29kVlf" /></figure><p>Now, I will change the return type of a function to see if <strong>mypy</strong> works. Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T2iEF5xcmLz4Cxe-" /></figure><p>Mypy informs us that the function returns an incompatible data type.</p><p>Next, I’ll add some empty lines to a .tsx file. Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3yq7at0k7TUuEtk7" /></figure><p>The file was automatically formatted.</p><p>I’ll add an unused variable to a .tsx file. <strong>ESLint</strong> displays an error. Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZHZXbgaVx5fG8_dx" /></figure><p>Now, I’ll modify a backend test so that it fails. Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vv0Zxs1n4CjAbmfD" /></figure><p>200 != 201, which is exactly what I changed. It works! 🙂</p><p>Next, I’ll modify a frontend test. Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9vptvKa65fe13xIP" /></figure><p>Now we know that every pre-commit hook works! Just what we need.</p><h3>Conclusion</h3><blockquote>We have created a project with fully configured pre-commit hooks that check code quality and run tests for both the backend and frontend.</blockquote><p>This project can be used with any Python framework (Django, Flask, FastAPI) and JavaScript/TypeScript frameworks (ReactJS, VueJS, Angular, Svelte). You may need to make minor adjustments to the configuration to suit your specific needs.</p><p>Additionally, you can modify and fine-tune the configurations for <strong>Ruff</strong>, <strong>MyPy</strong>, <strong>Prettier</strong>, and <strong>ESLint</strong> as you like since they offer great flexibility in customization.</p><p>Thank you for your attention!</p><h3>My Other Articles on Related Topics</h3><ol><li><a href="https://medium.com/@gnetkov/testing-fastapi-application-with-pytest-57080960fd62">Testing FastAPI Application with Pytest</a></li><li><a href="https://medium.com/@gnetkov/e2e-tests-with-playwright-3b011df85791">E2E tests with PlayWright</a></li></ol><h3>Useful Links</h3><ol><li><a href="https://gitlab.com/FedorGN/precommit-template">https://gitlab.com/FedorGN/precommit-template</a> — repository with code of this project project.</li><li><a href="https://pre-commit.com/">https://pre-commit.com/</a> — Pre-commit.</li><li><a href="https://github.com/codespell-project/codespell">https://github.com/codespell-project/codespell</a> — Codespell.</li><li><a href="https://docs.astral.sh/ruff/">https://docs.astral.sh/ruff/</a> — Ruff python linter and formatter.</li><li><a href="https://mypy.readthedocs.io/en/stable/">https://mypy.readthedocs.io/en/stable/</a> — MyPy.</li><li><a href="https://prettier.io/docs/en/">https://prettier.io/docs/en/</a> — Prettier.</li><li><a href="https://eslint.org/docs/latest/">https://eslint.org/docs/latest/</a> — ESLint.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdbc1ec5cfea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang Application Template (Gin, PostgreSQL, MailHog, PGAdmin, Docker Compose)]]></title>
            <link>https://medium.com/@gnetkov/golang-application-template-gin-postgresql-mailhog-pgadmin-docker-compose-a243c29d0bee?source=rss-bd9eb418040f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a243c29d0bee</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[gin]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Fedor GNETKOV]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 12:00:41 GMT</pubDate>
            <atom:updated>2024-10-09T12:00:41.937Z</atom:updated>
            <content:encoded><![CDATA[<p>This template was created to allow to quickly start developing a backend using <strong>Golang with the Gin framework and Gorm ORM</strong>.</p><h4>Key Features:</h4><ul><li><strong>Easy setup</strong> with docker compose. Just one command (docker compose up) to launch all services.</li><li><strong>Environment variables</strong> configuration (.env).</li><li><strong>Hot reload </strong>with Air.</li><li><strong>ORM</strong> models with Gorm.</li><li><strong>CRUD operations </strong>examples.</li><li><strong>User registration and authentication</strong> with JWT.</li><li><strong>Swagger</strong> documentation for the API.</li><li><strong>Email sending</strong> feature with SMTP, configured for <strong>MailHog</strong> in the development environment.</li></ul><p>The full project code is available in the GitLab repository:<a href="https://gitlab.com/FedorGN/go-gin-test"> https://gitlab.com/FedorGN/go-gin-test</a>. Feel free to clone it (and don’t forget to leave a star :) — it lets me know the project is useful).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iKFHX62m4lrN8Z0_Fy7igQ.png" /><figcaption>Image generated by DALL·E</figcaption></figure><p><strong>Project Structure:</strong></p><pre>├── backend   <br>│   ├── docs                  // Generated Swagger documentation<br>│   ├── internal<br>│   │   ├── config            // Configuration files of app<br>│   │   ├── controllers       // API routes<br>│   │   ├── database          // DB configuration<br>│   │   ├── middleware        // Middleware (Auth)<br>│   │   ├── models            // Gorm models (Item, User)<br>│   │   ├── routes            // Router for registering routes from controller<br>│   │   ├── schemas           // Schemas (Item, User)<br>│   │   ├── services          // Email and CRUD services<br>│   │   ├── tests<br>│   │   │   ├── api_tests         // Tests for controllers<br>│   │   │   ├── clients           // API test clients<br>│   │   │   ├── factories         // Factories (User, Item)<br>│   │   │   ├── testutils         // Test database and data utils<br>│   │   ├── utils                 // Utils (JWT generation and parsing)<br>│   │   ├── validators            // Validators for inputs<br>│   │<br>│   ├── air.toml              // Configuration of Air for hot reload<br>│   ├── Dockerfile            // Dockerfile for building the app<br>│   ├── go.mod                // Module&#39;s dependencies<br>│   ├── go.sum                // Hashes for specific versions of the dependencies<br>│   ├── main.go               // Entry point of the application<br>│<br>├── .env                  // File with env variables for the configuration of the app<br>├── .env.example          // Example of .env<br>├── .gitignore            // Untracked files that Git should ignore<br>├── docker-compose.yaml   // Docker compose configuration<br>└── README.md             // Project documentation</pre><h3>Docker compose configuration of the project</h3><p>I use Docker Compose to simplify getting started and avoid installing any programs on the local computer.</p><p>After you clone the project, you need to copy the .env.example file to .env and change the environment variables if necessary. In this file, you can also find ports, passwords, emails, and users for all services used in the project.</p><p>The .env file is used to avoid hardcoding configuration data in different parts of the code. We declare these variables in one place, just once.</p><p><strong>Services:</strong></p><ul><li><strong>todo-api</strong> — the backend service using the Gin framework + Gorm ORM. It uses the Dockerfile located at ./backend/Dockerfile for building the Docker image.</li><li><strong>todo-postgresql</strong> — the PostgreSQL server, which is the local database for the application. We’ve added binding to the todo-postgres-data volume to persist data when containers are restarted.</li><li><strong>todo-pgadmin</strong> — PGAdmin is a powerful tool for viewing and modifying the database structure and data.</li><li><strong>todo-mailhog</strong> — MailHog is a fake SMTP server to prevent the backend from sending emails to real email addresses. It allows developers to view and inspect sent emails.</li><li><strong>todo-stunnel</strong> — A proxy to add TLS encryption in the development environment. It is used because the gomail module requires TLS for sending all emails.</li></ul><p>The ./docker-compose.yaml file:</p><pre># Environment variables are omitted for the article. See the full file in the project<br><br><br>services:<br> # Gin application<br> todo-api:<br>   image: &quot;todo-api:latest&quot;<br>   ports:<br>     - ${API_PORT}:${API_PORT_INTERNAL}<br>   environment:<br>     &lt;&lt;: *common-gin-app-environment-variables<br>   build:<br>     context: ./backend<br>     dockerfile: Dockerfile<br>   volumes:<br>     - ./backend/:/app<br>   depends_on:<br>     - todo-postgres<br>   restart: unless-stopped<br><br><br><br><br> # Postgres database, data is persisted in a volume<br> todo-postgres:<br>   image: &quot;postgres:14.5-alpine&quot;<br>   environment:<br>     &lt;&lt;: *common-linux-container-environment-variables<br>     POSTGRES_USER: ${POSTGRES_USER}<br>     POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}<br>     POSTGRES_DB: ${POSTGRES_DB}<br>   ports:<br>     - ${POSTGRES_PORT}:${POSTRGRES_PORT_INTERNAL}<br>   volumes:<br>     - todo-postgres-data:/var/lib/postgresql/data<br>   restart: unless-stopped<br><br><br> # PGAdmin to view and control the database<br> todo-pgadmin:<br>   image: &quot;dpage/pgadmin4:8.11&quot;<br>   depends_on:<br>     - todo-postgres<br>   ports:<br>     - ${PGADMIN_PORT}:80<br>   environment:<br>     &lt;&lt;: *common-linux-container-environment-variables<br>     PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL}<br>     PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD}<br>     PGADMIN_DEFAULT_PASSWORD_FILE: ${PGADMIN_DEFAULT_PASSWORD_FILE}<br>     # disable spamming all the screen with logs<br>     GUNICORN_ACCESS_LOGFILE: /dev/null<br>   restart: unless-stopped<br><br><br> # Fake smtp server to intercept and view sent emails<br> todo-mailhog:<br>   image: &quot;mailhog/mailhog:v1.0.1&quot;<br>   ports:<br>     - ${MAILHOG_PORT}:${MAILHOG_PORT_INTERNAL}<br>   environment:<br>     &lt;&lt;: *common-linux-container-environment-variables<br>   restart: unless-stopped<br><br><br> # Proxy to add TLS encryption on development env, because gomail needs TLS<br> todo-stunnel:<br>   image: dweomer/stunnel<br>   restart: always<br>   environment:<br>     - STUNNEL_SERVICE=smtps<br>     - STUNNEL_ACCEPT=465<br>     - STUNNEL_CONNECT=todo-mailhog:1025<br>   ports:<br>     - 465:465<br><br><br>volumes:<br> todo-postgres-data:<br>   name: ${POSTGRES_STORAGE_VOLUME_NAME}</pre><p>File ./backend/Dockerfile :</p><pre># Use an official Golang runtime as a parent image<br>FROM golang:1.22-alpine<br>RUN apk add - no-cache git make musl-dev go<br># Install air for hot-reloading<br>RUN go install github.com/air-verse/air@latest<br># Set the Current Working Directory inside the container<br>WORKDIR /app<br># Copy go.mod and go.sum files<br>COPY go.mod go.sum ./<br># Download all dependencies<br>RUN go mod download<br># Copy the rest of the application code to the container<br>COPY . .<br># Expose port 8080<br>EXPOSE 8080<br># Start the application with air for live reloading<br>CMD [&quot;air&quot;]</pre><p>Please note that we install <strong>Air</strong>, a command-line utility designed for live-reloading Go applications during development. This allows us to see changes made to the todo-backend service without restarting the Docker container.</p><h3>Backend service</h3><p>The backend service is built on the <strong>Gin</strong> framework. Let’s take a closer look at the backend service.</p><p>The ./backend/main.go file is the entry point of the application:</p><pre>package main<br><br><br>import (<br>   &quot;simple-gin-backend/internal/config&quot;<br>   &quot;simple-gin-backend/internal/database&quot;<br>   &quot;simple-gin-backend/internal/routes&quot;<br><br><br>   &quot;github.com/gin-gonic/gin&quot;<br>)<br><br><br>// @title Simple Gin Backend API<br>// @version 1.0<br>// @description This is a simple backend using Gin and GORM.<br>// @BasePath /<br>// @securityDefinitions.apikey BearerAuth<br>// @in header<br>// @name Authorization<br>func main() {<br>   // Load the configuration from environment variables<br>   config.LoadConfig()<br><br><br>   // Initialize the database<br>   database.InitDB()<br>   // Auto-migrate the database schema<br>   database.AutoMigrate()<br><br><br>   r := gin.Default()<br><br><br>   // Set up routes<br>   routes.RegisterRoutes(r)<br><br><br>   // Run the server<br>   r.Run(&quot;:8080&quot;)<br>}<br></pre><p>Please note the Go doc comments before the main function. This comment is used to generate the OpenAPI specification, which is utilized in <strong>Swagger</strong>. The comment defines the parameters for the OpenAPI schema. This project uses the <strong>Swag</strong> package.</p><p>In the main function, we initialize the connection to the <strong>PostgreSQL</strong> database and run automatic migrations. Let’s take a look at these functions.</p><p>File ./backend/internalt/database/db.go :</p><pre>package database<br><br><br>import (<br>   &quot;fmt&quot;<br>   &quot;log&quot;<br>   &quot;simple-gin-backend/internal/config&quot;<br>   &quot;simple-gin-backend/internal/models&quot;<br><br><br>   &quot;gorm.io/driver/postgres&quot;<br>   &quot;gorm.io/gorm&quot;<br>)<br><br><br>var DB *gorm.DB<br><br><br>func AutoMigrate() {<br>   DB.AutoMigrate(&amp;models.Item{}, &amp;models.User{})<br>}<br><br><br>func InitDB() {<br>   dsn := fmt.Sprintf(<br>       &quot;host=%s user=%s password=%s dbname=%s port=%s sslmode=disable&quot;,<br>       config.AppConfig.PostgresHost,<br>       config.AppConfig.PostgresUser,<br>       config.AppConfig.PostgresPassword,<br>       config.AppConfig.PostgresDb,<br>       config.AppConfig.PostgresPort)<br><br><br>   var dbErr error<br>   DB, dbErr = gorm.Open(postgres.Open(dsn), &amp;gorm.Config{})<br>   if dbErr != nil {<br>       log.Fatalf(&quot;Failed to connect to the database: %v&quot;, dbErr)<br>   }<br><br><br>   log.Println(&quot;Database connected successfully!&quot;)<br>}</pre><p>DB is a global variable that will hold the database connection instance. It is of type *gorm.DB, which represents the database session that Gorm provides.</p><p>The AutoMigrate function automatically creates or updates the database schema (tables, columns, etc.) based on the models `Item` and `User` defined in the `models` package.</p><p>The InitDB function initializes the database connection using Gorm’s PostgreSQL driver. It connects to the PostgreSQL database and assigns the connection to the global DB variable.</p><p>Now, let’s take a look at the route registration.</p><p>File ./backend/internal/routes/routes.go :</p><pre>package routes<br><br><br>import (<br>   &quot;simple-gin-backend/internal/controllers&quot;<br>   &quot;simple-gin-backend/internal/middleware&quot;<br><br>   &quot;github.com/gin-gonic/gin&quot;<br><br>   docs &quot;simple-gin-backend/docs&quot;<br><br>   swaggerfiles &quot;github.com/swaggo/files&quot;<br>   ginSwagger &quot;github.com/swaggo/gin-swagger&quot;<br>)<br><br><br>// RegisterRoutes sets up the application routes<br>func RegisterRoutes(router *gin.Engine) {<br>   // Swagger routes<br>   docs.SwaggerInfo.BasePath = &quot;/&quot;<br>   router.GET(&quot;/swagger/*any&quot;, ginSwagger.WrapHandler(swaggerfiles.Handler))<br><br>   // Hello world routes<br>   router.GET(&quot;/&quot;, controllers.GetHelloWorld)<br>   router.POST(&quot;/send-test-email&quot;, controllers.PostSendEmail)<br>   <br>   router.POST(&quot;/sign-up&quot;, controllers.RegisterUser)<br>   router.POST(&quot;/login&quot;, controllers.LoginUser)<br><br>   // Protected routes (Require authentication)<br>   api := router.Group(&quot;&quot;)<br>   api.Use(middleware.JWTAuthMiddleware())<br>   {<br>       // CRUD Routes for items<br>       api.POST(&quot;/items&quot;, controllers.CreateItem)<br>       api.GET(&quot;/items/:id&quot;, controllers.GetItem)<br>       api.PUT(&quot;/items/:id&quot;, controllers.UpdateItem)<br>       api.DELETE(&quot;/items/:id&quot;, controllers.DeleteItem)<br>       api.GET(&quot;/items&quot;, controllers.GetItems)<br>   }<br>}</pre><p>In the RegisterRoutes function, we register the Swagger documentation. If we deploy the service to production, the Swagger routes will need to be hidden.</p><p>After that, we register both unprotected routes and protected routes. The functions for these routes are located in the `controllers` module. For the protected routes, we use JWTAuthMiddleware to validate the token.</p><p>Now, let’s take a look at the file:</p><p>File ./backend/internal/middleware/auth.go :</p><pre>package middleware<br><br><br>import (<br>   &quot;net/http&quot;<br>   &quot;simple-gin-backend/internal/utils&quot;<br>   &quot;strings&quot;<br><br><br>   &quot;github.com/gin-gonic/gin&quot;<br>)<br><br><br>// JWTAuthMiddleware is a middleware to protect routes<br>func JWTAuthMiddleware() gin.HandlerFunc {<br>   return func(c *gin.Context) {<br>       // Get the token from the Authorization header<br>       authHeader := c.GetHeader(&quot;Authorization&quot;)<br>       if authHeader == &quot;&quot; || !strings.HasPrefix(authHeader, &quot;Bearer &quot;) {<br>           c.JSON(http.StatusUnauthorized, gin.H{&quot;error&quot;: &quot;Missing or invalid token&quot;})<br>           c.Abort()<br>           return<br>       }<br><br><br>       // Remove the &quot;Bearer &quot; prefix<br>       tokenString := strings.TrimPrefix(authHeader, &quot;Bearer &quot;)<br><br><br>       // Validate the JWT<br>       claims, err := utils.ParseJWT(tokenString)<br>       if err != nil {<br>           c.JSON(http.StatusUnauthorized, gin.H{&quot;error&quot;: &quot;Invalid token&quot;})<br>           c.Abort()<br>           return<br>       }<br><br><br>       // Store the user ID in the context for future use<br>       c.Set(&quot;user_id&quot;, claims.UserID)<br><br><br>       c.Next() // Continue to the next handler<br>   }<br>}</pre><p>c *gin.Context represents the context for a specific HTTP request. It contains information about the request, such as headers, query parameters, the request body, and the response writer. The *gin.Context also provides utility methods for interacting with HTTP requests and responses, like sending JSON responses, setting status codes, and managing request flow (such as aborting a request or continuing with the next handler).</p><p>Now, let’s look at the Gorm models. I created a BaseModel with common fields for all models because I want ID, CreatedAt, UpdatedAt, and DeletedAt to be present in all models without repeating this code in every model.</p><p>File ./backend/internal/models/base_model.go :</p><pre>package models<br><br><br>import (<br>   &quot;time&quot;<br><br><br>   &quot;gorm.io/gorm&quot;<br>)<br><br><br>// BaseModel contains common fields for all models<br>type BaseModel struct {<br>   ID        uint           `gorm:&quot;primaryKey&quot; json:&quot;id&quot; example:&quot;1&quot;`<br>   CreatedAt time.Time      `json:&quot;created_at&quot; example:&quot;2023-09-06T14:00:00Z&quot;`<br>   UpdatedAt time.Time      `json:&quot;updated_at&quot; example:&quot;2023-09-06T14:00:00Z&quot;`<br>   DeletedAt gorm.DeletedAt `swaggertype:&quot;primitive,string&quot; json:&quot;deleted_at,omitempty&quot; example:&quot;2023-09-06T14:00:00Z&quot;`<br>}</pre><p>More about Gorm ORM can be found on the official site:<a href="https://gorm.io/docs/"> https://gorm.io/docs/</a></p><p>You can see annotations (tags) after the type of each field; they are used by Gorm, JSON serialization tags, and Swagger.</p><p>In this application, I created two models: User and Item.</p><p>File ./backend/internal/models/user.go :</p><pre>package models<br><br><br>// User represents a user in the system<br>type User struct {<br>   BaseModel<br>   FirstName    string `json:&quot;first_name&quot; example:&quot;John&quot;`<br>   LastName     string `json:&quot;last_name&quot; example:&quot;Doe&quot;`<br>   Email        string `gorm:&quot;unique;not null&quot; json:&quot;email&quot; example:&quot;john.doe@example.com&quot;`<br>   PasswordHash string `gorm:&quot;not null&quot; json:&quot;-&quot;` // Password will be hashed<br>}</pre><p>I created three services in the ./backend/internal/services folder: item_service.go, user_service.go, and email_service.go.</p><p>File ./backend/internal/services/user_service.go :</p><pre>package services<br><br><br>import (<br>   &quot;fmt&quot;<br>   &quot;simple-gin-backend/internal/database&quot;<br>   &quot;simple-gin-backend/internal/models&quot;<br>   &quot;simple-gin-backend/internal/schemas&quot;<br>   &quot;simple-gin-backend/internal/utils&quot;<br><br>   &quot;golang.org/x/crypto/bcrypt&quot;<br>)<br><br><br>// CreateUser creates a new user in the database using the UserSchemaIn struct<br>func CreateUser(input schemas.UserSchemaIn) (*models.User, error) {<br>   // Check if the email is already registered<br>   var existingUser models.User<br>   if err := database.DB.Where(&quot;email = ?&quot;, input.Email).First(&amp;existingUser).Error; err == nil {<br>       return nil, fmt.Errorf(&quot;email already exists&quot;)<br>   }<br><br>   // Hash the password before saving<br>   hashedPassword, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)<br>   if err != nil {<br>       return nil, fmt.Errorf(&quot;error hashing password: %v&quot;, err)<br>   }<br><br>   // Create a new User model instance and set fields<br>   newUser := models.User{<br>       Email:        input.Email,<br>       FirstName:    input.FirstName,<br>       LastName:     input.LastName,<br>       PasswordHash: string(hashedPassword),<br>   }<br>   // Save the user to the database<br>   if err := database.DB.Create(&amp;newUser).Error; err != nil {<br>       return nil, fmt.Errorf(&quot;error creating user: %v&quot;, err)<br>   }<br><br>   return &amp;newUser, nil<br>}<br><br><br>// AuthenticateUser checks user credentials and returns a JWT if successful<br>func AuthenticateUser(input schemas.UserLoginSchemaIn) (string, error) {<br>   var user models.User<br><br><br>   // Find the user in the database by email<br>   if err := database.DB.Where(&quot;email = ?&quot;, input.Email).First(&amp;user).Error; err != nil {<br>       return &quot;&quot;, fmt.Errorf(&quot;user not found&quot;)<br>   }<br><br><br>   // Compare the provided password with the stored hashed password<br>   if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(input.Password)); err != nil {<br>       return &quot;&quot;, fmt.Errorf(&quot;incorrect password&quot;)<br>   }<br><br><br>   // Generate JWT token if authentication is successful<br>   token, err := utils.GenerateJWT(user.ID)<br>   if err != nil {<br>       return &quot;&quot;, fmt.Errorf(&quot;failed to generate token&quot;)<br>   }<br><br><br>   return token, nil<br>}</pre><p>In this file, there are two functions:</p><ul><li>CreateUser creates a new user. We check if a user with the given email already exists in the database, hash the password, and save the user in the database with the hashed password.</li><li>AuthenticateUser validates the password and generates a JWT token.</li></ul><p>In the provided code, the password is hashed using the <strong>bcrypt</strong> algorithm, and no “secret” key (such as a salt) is explicitly provided. <strong>Bcrypt</strong> is a cryptographic hashing algorithm designed for password hashing. One of the key features of bcrypt is that it automatically handles salting internally, meaning that it generates a unique salt for each password hash and stores the salt within the resulting hash itself. Therefore, there’s no need to provide an explicit secret or salt when using bcrypt, as it ensures that even if two users have the same password, the resulting hashes will be different.</p><p>Now, let’s look at the API endpoints.</p><p>File ./backend/internal/controllers/user_controller.go :</p><pre>package controllers<br><br><br>import (<br>   &quot;net/http&quot;<br>   &quot;simple-gin-backend/internal/schemas&quot;<br>   &quot;simple-gin-backend/internal/services&quot;<br><br>   &quot;github.com/gin-gonic/gin&quot;<br>)<br><br>// RegisterUser godoc<br>// @Summary Register a new user<br>// @Description Create a new user by providing email and password<br>// @Tags Auth<br>// @Accept json<br>// @Produce json<br>// @Param user body schemas.UserSchemaIn true &quot;User Data&quot;<br>// @Success 201 {object} models.User<br>// @Failure 400 {string} string &quot;Bad request&quot;<br>// @Router /sign-up [post]<br>func RegisterUser(c *gin.Context) {<br>   var input schemas.UserSchemaIn<br><br>   // Bind the JSON input to the UserSchemaIn DTO<br>   if err := c.ShouldBindJSON(&amp;input); err != nil {<br>       c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: &quot;Invalid input&quot;})<br>       return<br>   }<br><br>   // Call the service to create the user, passing the entire input schema<br>   user, err := services.CreateUser(input)<br>   if err != nil {<br>       if err.Error() == &quot;email already exists&quot; {<br>           c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: &quot;Email already exists&quot;})<br>       } else {<br>           c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: err.Error()})<br>       }<br>       return<br>   }<br><br>   c.JSON(http.StatusCreated, user)<br>}<br><br><br>// LoginUser godoc<br>// @Summary Log in a user<br>// @Description Log in by providing email and password to receive a JWT<br>// @Tags Auth<br>// @Accept json<br>// @Produce json<br>// @Param user body schemas.UserLoginSchemaIn true &quot;User Login Data&quot;<br>// @Success 200 {string} string &quot;JWT Token&quot;<br>// @Failure 401 {string} string &quot;Unauthorized&quot;<br>// @Router /login [post]<br>func LoginUser(c *gin.Context) {<br>   var input schemas.UserLoginSchemaIn<br><br>   // Bind the JSON input to the UserLoginSchemaIn DTO<br>   if err := c.ShouldBindJSON(&amp;input); err != nil {<br>       c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: &quot;Invalid input&quot;})<br>       return<br>   }<br><br>   // Authenticate the user and generate JWT token using the service<br>   token, err := services.AuthenticateUser(input)<br>   if err != nil {<br>       if err.Error() == &quot;user not found&quot; || err.Error() == &quot;incorrect password&quot; {<br>           c.JSON(http.StatusUnauthorized, gin.H{&quot;error&quot;: err.Error()})<br>       } else {<br>           c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: err.Error()})<br>       }<br>       return<br>   }<br><br>   c.JSON(http.StatusOK, gin.H{&quot;token&quot;: token})<br>}</pre><p>Please note the Go Doc Comments. They are <strong>mandatory</strong> and used for generating <strong>Swagger</strong> documentation. Swagger documentation<strong> is not generated automatically</strong>. After you change a Go Doc Comment, you need to run the following command (in this example, within the running todo-api container):</p><pre>docker-compose exec todo-api swag init</pre><p>This command will generate the documentation in the ./backend/docs folder.</p><h3>Sending Emails</h3><p>In this project, I added the functionality to send emails from the backend service via SMTP.</p><p>File ./backend/internal/services/email_service.go :</p><pre>package services<br><br>import (<br> &quot;crypto/tls&quot;<br> &quot;log&quot;<br> &quot;simple-gin-backend/internal/config&quot;<br><br> &quot;gopkg.in/gomail.v2&quot;<br>)<br><br>// EmailService struct to hold the email configuration<br>type EmailService struct {<br> Host     string<br> Port     int<br> Username string<br> Password string<br> From     string<br> UseTLS   bool<br>}<br><br>// NewEmailService initializes a new EmailService<br>func NewEmailService() *EmailService {<br><br> return &amp;EmailService{<br>  Host:     config.AppConfig.SMTPHost,<br>  Port:     config.AppConfig.SMTPPort,<br>  Username: config.AppConfig.SMTPUser,<br>  Password: config.AppConfig.SMTPPassword,<br>  From:     config.AppConfig.EmailFromEmail,<br>  UseTLS:   config.AppConfig.UseMailTLS,<br> }<br>}<br><br>// SendEmail sends an email using the EmailService<br>func (es *EmailService) SendEmail(to string, subject string, body string) error {<br> m := gomail.NewMessage()<br><br> // Set the sender and recipient<br> m.SetHeader(&quot;From&quot;, es.From)<br> m.SetHeader(&quot;To&quot;, to)<br> m.SetHeader(&quot;Subject&quot;, subject)<br> m.SetBody(&quot;text/html&quot;, body)<br><br> // Dial the SMTP server<br> d := gomail.NewDialer(es.Host, es.Port, es.Username, es.Password)<br><br> // Disable certificate verification for development purposes<br> if es.UseTLS &amp;&amp; config.AppConfig.IsDevelopmentEnv {<br>  d.TLSConfig = &amp;tls.Config{<br>   InsecureSkipVerify: true, // Skip certificate verification<br>  }<br> } else {<br>  d.TLSConfig = nil<br> }<br><br> // Send the email<br> if err := d.DialAndSend(m); err != nil {<br>  log.Printf(&quot;Failed to send email: %v&quot;, err)<br>  return err<br> }<br><br> log.Println(&quot;Email sent successfully&quot;)<br> return nil<br>}</pre><p>I created a test route send-test-email, which uses this service.</p><p>File ./backend/internal/controllers/hello_controller.go :</p><pre>// Some code is omitted here. See full file in gitlab repository.<br><br>// SendEmailHandler godoc<br>// @Summary Send an email<br>// @Description Sends a welcome email to the recipient<br>// @Tags Dev routes<br>// @Accept json<br>// @Produce json<br>// @Param to query string true &quot;Recipient email&quot;<br>// @Param subject query string true &quot;Email subject&quot;<br>// @Param body query string true &quot;Email body&quot;<br>// @Success 200 {object} map[string]string &quot;Email sent successfully&quot;<br>// @Failure 500 {object} map[string]string &quot;Failed to send email&quot;<br>// @Router /send-test-email [post]<br>func PostSendEmail(c *gin.Context) {<br> emailService := services.NewEmailService()<br><br> // Example email details<br> to := &quot;recipient@example.com&quot;<br> subject := &quot;Welcome to Our Service&quot;<br> body := &quot;&lt;h1&gt;Hello!&lt;/h1&gt;&lt;p&gt;Thanks for signing up.&lt;/p&gt;&quot;<br><br> // Send email<br> if err := emailService.SendEmail(to, subject, body); err != nil {<br>  c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: &quot;Failed to send email&quot;})<br>  return<br> }<br><br> c.JSON(http.StatusOK, gin.H{&quot;message&quot;: &quot;Email sent successfully&quot;})<br>}</pre><p>Now we can easily test email sending using <strong>Swagger</strong> and view the sent email in <strong>MailHog</strong> at<a href="http://localhost:8085/"> http://localhost:8085/</a>. Let’s send an email and check it in MailHog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3xUeEhO3fuNQy618qAdjHg.png" /><figcaption>Mail displayed in MailHog</figcaption></figure><p>I added API tests to this project, but we will review them in the next article. It’s coming soon.</p><h3>Conclusion</h3><p>We have built a backend using the <strong>Gin</strong> framework and <strong>Gorm</strong> ORM:</p><ul><li>Containerized the project using <strong>Docker</strong> and set up all services with <strong>Docker Compose</strong>.</li><li>Connected the <strong>PostgreSQL</strong> database and added table initialization.</li><li>Enabled hot reloading of the API service for development.</li><li>Implemented user authentication using <strong>JWT</strong>.</li><li>Added <strong>Swagger</strong> documentation.</li><li>Created two models: Item and User.</li><li>Created <strong>controllers</strong>.</li></ul><h3>Useful Links:</h3><ol><li><a href="https://gin-gonic.com/docs/">https://gin-gonic.com/docs/</a> — Gin framework</li><li><a href="https://gorm.io/docs/">https://gorm.io/docs/</a> — Gorm framework</li><li><a href="https://go.dev/doc/comment">https://go.dev/doc/comment</a> — Go Doc Comments</li><li><a href="http://github.com/air-verse/air">github.com/air-verse/air</a> — Air</li><li><a href="https://github.com/swaggo/swag">https://github.com/swaggo/swag</a> — Swag package</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a243c29d0bee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing FastAPI Application with Pytest]]></title>
            <link>https://medium.com/@gnetkov/testing-fastapi-application-with-pytest-57080960fd62?source=rss-bd9eb418040f------2</link>
            <guid isPermaLink="false">https://medium.com/p/57080960fd62</guid>
            <category><![CDATA[pytest]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Fedor GNETKOV]]></dc:creator>
            <pubDate>Tue, 27 Aug 2024 09:32:27 GMT</pubDate>
            <atom:updated>2024-09-09T23:07:12.706Z</atom:updated>
            <content:encoded><![CDATA[<p>Today we will look at testing a FastAPI application using Pytest, set up the tests, and go over some good practices. What exactly will we cover?</p><ol><li><strong>Fixtures</strong>: We will discuss what fixtures are and how they simplify testing.</li><li><strong>Using a test database</strong>: We will configure the tests to use a PostgreSQL database that is separate from the local development database and intended exclusively for tests.</li><li><strong>Creating model Factories</strong>: We will simplify the creation of test data in the database. For example, creating a user in the database using a factory like user: User = UserFactory(). Just one line without arguments will create a user with realistic random data in the database.</li><li><strong>Creating clients with authorization for API tests</strong>. We will create a test client to test protected API routes, i.e. routes requiring authentication.</li><li><strong>Tests</strong>: We will write a few simple CRUD and API tests.</li><li><strong>Tests with external service patching</strong>. We will write a test that patches the Google Authentication service to avoid making calls to the Google API during the tests.</li><li><strong>Tests with parameterization</strong>. We will write a test using different data sets as input to cover various scenarios in a single test.</li></ol><p>You can view all the code and run it on your local machine. It is available in the repository:<a href="https://gitlab.com/FedorGN/todo-fastapi-reactjs"> https://gitlab.com/FedorGN/todo-fastapi-reactjs</a>.</p><p>I discussed the project “<a href="https://gitlab.com/FedorGN/todo-fastapi-reactjs">todo-fastapi-reactjs</a>” in more detail in an article: <a href="https://medium.com/@gnetkov/modern-application-template-with-fastapi-reactjs-docker-2a87e44dc3b0">Modern Application Template with FastAPI, ReactJS, Docker</a>.</p><p>Backend tests are located in the backend/app/tests folder. The code modifications will be made in this folder.</p><h3><strong>Fixtures</strong></h3><p>Software test fixtures initialize test functions. They provide a fixed baseline so that tests execute reliably and produce consistent, repeatable results. Initialization may involve setting up services, states, or other operating environments. [<a href="https://docs.pytest.org/en/6.2.x/fixture.html">https://docs.pytest.org/</a>]</p><p>All fixtures in Pytest should be placed in the tests/conftest.py file. conftest.py is a configuration file in Pytest that is used to define fixtures, hooks, and configuration options shared across multiple test modules. conftest.py is a place to centralize reusable test setup logic and configurations.</p><p>Here’s a simple example of a fixture and its use:</p><pre>import pytest<br><br>@pytest.fixture<br>def my_car() -&gt; str:<br>    return &quot;Toyota&quot;<br><br>def test_my_car_toyota(my_car: str):<br>    assert my_car == &quot;Toyota&quot; # True<br><br>def test_my_car_honda(my_car: str):<br>    assert my_car == &quot;Honda&quot; # False</pre><p>In this example, we create a fixture my_car that replaces the argument my_car in the tests test_my_car_toyota and test_my_car_honda.</p><p>Fixtures can have different scopes, which define how often the fixture is invoked:</p><ul><li><strong>Function (scope=”function”)</strong>: <em>(Default)</em> The fixture is created and destroyed for each test function.</li><li><strong>Class (scope=”class”)</strong>: The fixture is created once per test class and shared across all methods of the class.</li><li><strong>Module (scope=”module”)</strong>: The fixture is created once per module and shared across all tests within that module.</li><li><strong>Session (scope=”session”)</strong>: The fixture is created once per test session and shared across all tests in the session.</li></ul><p><strong>Fixtures can be automatically applied to all tests</strong> within a given scope without having to explicitly include them as arguments by using the <strong>autouse=True</strong> option.</p><p>Here is another example of how to use a fixture:</p><pre>@pytest.fixture(scope=&quot;session&quot;, autouse=True)<br>def setup_test_database():</pre><h3>Creating and Deleting Test Database, Tables, and Data</h3><p>Initially, Pytest in the project used the local database for tests, meaning it was the same database that the developer uses. This is inconvenient because data already exists in the database, and moreover the tests create new data.</p><p>Therefore, <strong>it makes sense to set up the tests </strong>in such a way:</p><ul><li>Tests use <strong>a separate test database</strong>.</li><li><strong>All tables are created before all tests</strong>, because the developer may change the database schema during development.</li><li><strong>All data is deleted after each test</strong>, as tests should be isolated from each other. Data created in one test should not affect the next test.</li></ul><p>Let’s configure the database in the tests/conftest.py file.</p><pre># Set up a test database URL<br>TEST_SQLALCHEMY_DATABASE_URL: str = settings.POSTGRESQL_TEST_DATABASE_URI<br>admin_engine = create_engine(<br>   settings.POSTGRESQL_ADMIN_DATABASE_URI, isolation_level=&quot;AUTOCOMMIT&quot;<br>)<br><br># Create an engine and sessionmaker bound to the test database<br>engine = create_engine(TEST_SQLALCHEMY_DATABASE_URL)<br>TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)<br><br><br>def create_test_database():<br>    &quot;&quot;&quot;Create the test database if it doesn&#39;t exist.&quot;&quot;&quot;<br>    with admin_engine.connect() as connection:<br>        try:<br>            connection.execute(<br>                text(f&quot;CREATE DATABASE {TEST_SQLALCHEMY_DATABASE_URL.split(&#39;/&#39;)[-1]}&quot;)<br>            )<br>        except ProgrammingError:<br>            print(&quot;Database already exists, continuing...&quot;)<br><br><br>@pytest.fixture(scope=&quot;session&quot;, autouse=True)<br>def setup_test_database():<br>    &quot;&quot;&quot;<br>    Create the test database schema before any tests run,<br>    and drop it after all tests are done.<br>    &quot;&quot;&quot;<br>    create_test_database()  # Ensure the test database is created<br>    Base.metadata.create_all(bind=engine)  # Create tables<br>    yield<br>    Base.metadata.drop_all(bind=engine)  # Drop tables after tests<br><br><br>@pytest.fixture(scope=&quot;function&quot;)<br>def db() -&gt; Generator:<br>    &quot;&quot;&quot;<br>    Create a new database session for each test and roll it back after the test.<br>    &quot;&quot;&quot;<br>    connection = engine.connect()<br>    transaction = connection.begin()<br>    session = TestingSessionLocal(bind=connection)<br>    <br>    yield session<br>    <br>    session.close()<br>    transaction.rollback()<br>    connection.close()</pre><p>Please note that we created <strong>two engines</strong>:</p><ul><li>admin_engine: This is used to connect to the PostgreSQL server with higher privileges so that we can perform administrative tasks, such as <strong>creating and managing databases</strong>.</li><li>engine: This is connected to the<strong> specific test database</strong>, which is used for running your tests.</li></ul><p>The purpose of the admin_engine is to <strong>create the test database on the PostgreSQL server</strong> using the create_test_database function if the test database does not already exist.</p><p>After this, we created two fixtures:</p><ul><li><strong>setup_test_database</strong>: This fixture creates the database with a “Session” scope. It sets up the tables before all tests and removes them after all tests are completed. This function does not use Alembic migrations; it creates schemas based on the current SQLAlchemy model structure.</li><li><strong>db</strong>: This fixture yields a session with the test database. It creates a transaction that is rolled back after each test completes, ensuring that each test is isolated.</li></ul><p>Thus, we have configured Pytest to use a separate PostgreSQL test database.</p><h3>Creating Model Factories</h3><blockquote>When writing tests for a back-end of web application, <strong>we almost always need initial data</strong> in the database.</blockquote><p>For example, in our specific application, if we want to write a test for the API to get a list of todos, we will at least need a User and a few Todo records. This is the case for almost every test —<strong> initial data in the database is always needed</strong>. In a FastAPI application, we typically work with SQLAlchemy models.</p><p>I will use the popular package <strong>factory_boy</strong> for this purpose. [<a href="https://factoryboy.readthedocs.io/en/stable/">https://factoryboy.readthedocs.io/en/stable/</a>]</p><p>We have two models in the application: User and Todo. <strong>Let’s create a factories for them.</strong></p><p>File tests/factories/user.py:</p><pre>import factory<br>from app.models.user import User<br>from app.core.security import get_password_hash<br>from app.tests.constants.user import UserTestConstants<br><br><br>class UserFactory(factory.alchemy.SQLAlchemyModelFactory):<br>    class Meta:<br>        model = User # SQLAlchemy model<br>        sqlalchemy_session_persistence = &quot;commit&quot; # Commit the session after creating the user instance.<br>    <br>    email = factory.Faker(&quot;email&quot;)<br>    hashed_password = factory.LazyFunction(<br>       lambda: get_password_hash(UserTestConstants.USER_DEFAULT_PASSWORD)<br>    )<br>    is_active = True<br>    is_superuser = False<br>    first_name = factory.Faker(&quot;first_name&quot;)<br>    last_name = factory.Faker(&quot;last_name&quot;)<br>    <br>    <br>    @classmethod<br>    def _create(cls, model_class, *args, **kwargs):<br>        # Handle the password argument before creating the user<br>        if &quot;password&quot; in kwargs:<br>            kwargs[&quot;hashed_password&quot;] = get_password_hash(kwargs.pop(&quot;password&quot;))<br>        return super()._create(model_class, *args, **kwargs)</pre><p>The Meta class is used to configure the Factory.</p><p>For generating random values, we use the<strong> Faker package</strong>. It allows generating realistic values depending on the context (first name, last name, email, random words etc.). <a href="https://faker.readthedocs.io/en/master/">[https://faker.readthedocs.io/en/master/</a>]</p><p>Take note of the default value for hashed_password. By default, each user will have a password defined in UserTestConstants.USER_DEFAULT_PASSWORD.</p><p>However, if a developer wants, they can set any other password simply by writing</p><pre>user: User = UserFactory(password=&quot;my_custom_password&quot;)</pre><p>The new password is set in this case because we override the _create method. This method is called during the creation of the Factory.</p><p>Now, let’s create a Factory for Todo in the tests/factories/todo.py file.</p><pre>import factory<br>from app.models.todo import Todo<br>from app.tests.factories.user import UserFactory<br><br><br>class TodoFactory(factory.alchemy.SQLAlchemyModelFactory):<br>    class Meta:<br>        model = Todo<br>        sqlalchemy_session_persistence = &quot;commit&quot;<br><br>    title = factory.Faker(&quot;word&quot;)<br>    is_done = factory.Faker(&quot;boolean&quot;)<br>    owner = factory.SubFactory(UserFactory)</pre><p>In this Factory, <strong>we set a default value for the owner</strong>. What does this mean in practice? It means that if we don’t provide an owner value, the <strong>TodoFactory will also create a user in addition to the Todo </strong>by default.</p><p>For SQLAlchemy Factories, a mandatory parameter in the configuration within the Meta class is sqlalchemy_session. This is the session <strong>that will be used to create objects in the database</strong>. We haven’t set it in the Factories to avoid circular imports. Instead, we set its value in a fixture in the tests/conftest.py file.</p><pre>@pytest.fixture(autouse=True)<br>def set_session_for_factories(db: Session):<br>    UserFactory._meta.sqlalchemy_session = db<br>    TodoFactory._meta.sqlalchemy_session = db</pre><blockquote>Thus, <strong>we have created Factories that can be used for simple and quick generation of objects in the database</strong>.</blockquote><h3>Test API Clients with authentication</h3><p>FastAPI provides TestClient, which can be used to test endpoints. However, we want to extend the functionality of TestClient as follows:</p><ul><li>The <strong>TestClient should use the test database</strong>.</li><li>We want to have a <strong>TestClient with authentication</strong>, meaning a user must be created, and the TestClient should have a valid access_token in the headers. We want to have two such TestClient instances: one with a superuser and one with a regular user.</li></ul><p>Let’s implement this. We’ll create a <strong>TestClient fixture that uses the test database</strong>. Add the following to the tests/conftest.py file:</p><pre>@pytest.fixture(scope=&quot;function&quot;)<br>def client(db: Session) -&gt; Generator[TestClient, None, None]:<br>    &quot;&quot;&quot;<br>    Provide a TestClient that uses the test database session.<br>    Override the get_db dependency to use the test session.<br>    &quot;&quot;&quot;<br>    <br>    def override_get_db():<br>        yield db<br>    app.dependency_overrides[get_db] = override_get_db<br>    with TestClient(app) as c:<br>        yield c<br>    app.dependency_overrides.clear()</pre><p>app.dependency_overrides[get_db] = override_get_db overrides the get_db dependency in the FastAPI app with the override_get_db function. This ensures that whenever the get_db dependency is called (e.g., in API routes), it will use the test session provided by the fixture.</p><p>The client fixture can be used for routes <strong>not requiring authentication</strong>.</p><p>Now, let’s create fixtures for authenticated users in the tests/fixtures/authorization.py file.</p><pre>from typing import Generator<br>import pytest<br>from app.models.user import User<br>from app.tests.constants.user import UserTestConstants<br>from app.tests.factories.user import UserFactory<br>from fastapi.testclient import TestClient<br>from app.core import security<br><br><br>@pytest.fixture(scope=&quot;function&quot;)<br>def client_superuser(client: TestClient) -&gt; Generator[TestClient, None, None]:<br>    &quot;&quot;&quot;<br>    Fixture that returns a TestClient with superuser authentication headers.<br>    It also creates a user in DB.<br>    &quot;&quot;&quot;<br>    user: User = UserFactory(<br>        is_superuser=True,<br>        email=UserTestConstants.CLIENT_SUPERUSER_EMAIL,<br>        password=UserTestConstants.CLIENT_SUPERUSER_PASSWORD,<br>    )<br>    access_token: str = security.create_access_token(user.id)<br>    headers = {&quot;Authorization&quot;: f&quot;Bearer {access_token}&quot;}<br>    # Modify the client to automatically include the superuser headers in each request<br>    client.headers.update(headers)<br>    yield client<br>    # Clean up: Remove the superuser headers after the test<br>    client.headers.clear()<br><br><br>@pytest.fixture(scope=&quot;function&quot;)<br>def client_user(client: TestClient) -&gt; Generator[TestClient, None, None]:<br>    &quot;&quot;&quot;<br>    Fixture that returns a TestClient with authentication headers. It also creates a user in DB.<br>    &quot;&quot;&quot;<br>    user: User = UserFactory()<br>    access_token: str = security.create_access_token(user.id)<br>    headers = {&quot;Authorization&quot;: f&quot;Bearer {access_token}&quot;}<br>    client.headers.update(headers)<br>    yield client<br>    client.headers.clear()</pre><p>In the client_superuser function, we create a superuser, generate a token, and add the token to the headers. We do the same in the client_user function.</p><blockquote>Now, we can test endpoints with authenticated users.</blockquote><h3>Tests</h3><p>Now that tests are set up to use a test database, and we have Factories and authenticated clients, we can write tests that <strong>focus solely on testing, without code repetition, thanks to the fixtures</strong>.</p><p>Let’s write tests for CRUD operations on Todo in the file tests/crud/test_todo.py.</p><pre>from sqlalchemy.orm import Session  # type: ignore<br><br>from app import crud<br>from app.models.todo import Todo<br>from app.models.user import User<br>from app.schemas.todo import TodoCreate<br>from app.tests.factories.user import UserFactory<br>from faker import Faker<br><br><br>def test_create_todo(db: Session) -&gt; None:<br>    user: User = UserFactory()<br>    title = Faker().word()<br>    todo_in = TodoCreate(title=title)<br>    todo = crud.todo.create_with_owner(db=db, obj_in=todo_in, owner_id=user.id)<br>    assert todo.title == title<br>    assert todo.owner_id == user.id<br><br><br>def test_get_todo(db: Session, todo: Todo) -&gt; None:<br>    stored_todo = crud.todo.get(db=db, id=todo.id)<br>    assert stored_todo<br>    assert todo.id == stored_todo.id<br>    assert todo.title == stored_todo.title<br>    assert todo.owner_id == stored_todo.owner_id<br><br><br>def test_delete_todo(db: Session, todo: Todo) -&gt; None:<br>    todo2 = crud.todo.remove(db=db, id=todo.id)<br>    todo3 = crud.todo.get(db=db, id=todo.id)<br>    assert todo3 is None<br>    assert todo2.id == todo.id<br>    assert todo2.title == todo.title<br>    assert todo2.owner_id == todo.owner_id</pre><p>We created<strong> simple CRUD tests</strong> for Todo using the db and todo fixtures. For example, in the test_delete_todo test, the Todo that we want to delete <strong>was created using the todo fixture</strong>.</p><p>Now, let’s create tests for the login endpoints.</p><pre>from faker import Faker<br>from fastapi.testclient import TestClient<br>from unittest.mock import MagicMock, patch<br>from app import crud, schemas<br>from app.core.config import settings<br>from app.models.user import User<br>from app.tests.factories.user import UserFactory<br>from sqlalchemy.orm import Session  # type: ignore<br>from jose import jwt  # type: ignore<br>from app.core import security<br><br><br>def test_get_access_token(client: TestClient) -&gt; None:<br>     password: str = &quot;password&quot;<br>     user: User = UserFactory(password=password)<br>     login_data: dict = {<br>        &quot;username&quot;: user.email,<br>        &quot;password&quot;: password,<br>     }<br>     r = client.post(f&quot;{settings.API_V1_STR}/login/get-access-token&quot;, data=login_data)<br>     tokens: dict = r.json()<br>     assert r.status_code == 200<br>     assert &quot;access_token&quot; in tokens<br>     assert tokens[&quot;access_token&quot;]<br><br><br>def test_use_access_token(client: TestClient, client_user: TestClient) -&gt; None:<br>    r = client_user.post(<br>        f&quot;{settings.API_V1_STR}/login/verify-token&quot;,<br>    )<br>    result = r.json()<br>    assert r.status_code == 200<br>    assert &quot;email&quot; in result<br><br><br>def test_forgot_email_not_existing_email(client: TestClient) -&gt; None:<br>    email = Faker().email()<br>    r = client.post(f&quot;{settings.API_V1_STR}/login/password-recovery/{email}&quot;)<br>    assert r.status_code == 201<br><br><br>def test_forgot_email_existing_email(client: TestClient, ordinary_user: User) -&gt; None:<br>    email = ordinary_user.email<br>    r = client.post(f&quot;{settings.API_V1_STR}/login/password-recovery/{email}&quot;)<br>    assert r.status_code == 200</pre><p>In the test_get_access_token test, we create a user using UserFactory within the function to demonstrate an example of how to use UserFactory. Alternatively, we could have created the user using the ordinary_user fixture. For example:</p><pre>def test_get_access_token(client: TestClient, ordinary_user: User) -&gt; None:<br>    login_data: dict = {<br>       “username”=UserTestConstants.ORDINARY_USER_EMAIL,<br>       “password”=UserTestConstants.ORDINARY_USER_PASSWORD,<br>    }<br>    r = client.post(f&quot;{settings.API_V1_STR}/login/get-access-token&quot;, data=login_data)</pre><p>A brief note: I use the enum UserTestConstants to <strong>gather constants related to users in one place</strong>, avoiding the need to write them out each time in a new file, or worse, using the same strings in different parts of the code. Using <strong>Enum allows you to change a value once in the Enum and be confident that the code works as expected</strong>, without needing to search through the code for repeated strings. When a project becomes large and involves many developers, <strong>repeated strings can become a real problem</strong>.</p><p><strong>File: </strong>tests/constants/user.py<strong>:</strong></p><pre>from sqlalchemy import Enum<br><br>class UserTestConstants(Enum):<br>    # Default password for UserFactory<br>    USER_DEFAULT_PASSWORD = &quot;password&quot;<br>    <br>    # Users used for TestClient with authentification headers<br>    # Credentials super user<br>    CLIENT_SUPERUSER_EMAIL = &quot;client.superuser@email.com&quot;<br>    CLIENT_SUPERUSER_PASSWORD = &quot;client_superuser_password&quot;<br>    # Credentials ordinary user<br>    CLIENT_ORDINARY_USER_EMAIL = &quot;client.ordinary@email.com&quot;<br>    CLIENT_ORDINARY_USER_PASSWORD = &quot;client_ordinary_password&quot;<br>    <br>    # Credentials ordinary user<br>    ORDINARY_USER_EMAIL = &quot;user@email.com&quot;<br>    ORDINARY_USER_PASSWORD = &quot;user_password&quot;</pre><h3>Using patch</h3><p>Let’s test the following endpoint for autentication through Google:</p><pre>@router.post(&#39;/login/google-auth&#39;, response_model=schemas.Token)<br>async def auth_credentials(<br>        credentials: str = Body(..., embed=True),<br>        db: Session = Depends(deps.get_db)):<br>    &quot;&quot;&quot;Swap google token to app jwt token.&quot;&quot;&quot;<br>    try:<br>        idinfo = id_token.verify_oauth2_token(<br>            credentials, requests.Request(), settings.GOOGLE_AUTH_CLIENT_ID)<br>    except Exception:<br>        raise HTTPException(<br>            status_code=400, detail=&quot;Incorrect google credentials.&quot;)<br>    user_email = idinfo[&#39;email&#39;]</pre><p>In this endpoint, there is a call to the Google service to verify the Google token. However, the problem is that the <strong>test users do not have Google accounts</strong>, and we do not want to test Google’s services because that is beyond our scope. The functionality of Google’s endpoints is tested by Google’s engineers. However, we still want to test this endpoint to ensure that the rest of our code works as expected. How can we do this? For this purpose, <strong>we will use the patch function from the unittest package</strong>.</p><p>Let’s add a test for the /login/google-auth endpoint. This will go into the tests/api/api_v1/test_login.py file.</p><pre>@patch(&quot;app.api.api_v1.endpoints.login.id_token.verify_oauth2_token&quot;)<br>def test_google_auth(<br>    mock_verify_oauth2_token: MagicMock,<br>    client: TestClient,<br>    db: Session,<br>    ordinary_user: User,<br>):<br>    # Mock data to return from the patched `verify_oauth2_token` function<br>    mock_verify_oauth2_token.return_value = {<br>        &quot;email&quot;: ordinary_user.email,<br>    }<br>    data: dict = {&quot;credentials&quot;: &quot;string&quot;}<br>    r = client.post(f&quot;{settings.API_V1_STR}/login/google-auth&quot;, json=data)<br>    assert r.status_code == 200<br>    access_token: str = r.json()[&quot;access_token&quot;]<br>    payload = jwt.decode(<br>        access_token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]<br>    )<br>    token_data = schemas.TokenPayload(**payload)<br>    user = crud.user.get(db, id=token_data.sub)<br>    assert user.id == ordinary_user.id</pre><p>In this test, we “replaced” the verify_oauth2_token function with mock_verify_oauth2_token, which returns the value we need without making a call to Google services.</p><p>This allows us to test the endpoint <strong>without making a call </strong>to Google’s endpoint.</p><p><strong>Patch can be useful in many cases where your application uses third-party services.</strong> Additionally, patch can be used to change the values of environment variables.</p><h3>Parametrizing Tests</h3><p>Very often, you need to <strong>test the same function with different arguments</strong>. You could write many tests, but this would lead to an increase in code, code repetition, and reduced readability. All of this would make the tests harder to maintain and understand. To avoid this, <strong>you should use the </strong>parametrize<strong> decorator</strong>.</p><p>Let’s create a test for the create todo endpoint. File: tests/api/api_v1/test_todo.py.</p><pre>@pytest.mark.parametrize(<br>    &quot;data, expected_status_code&quot;,<br>    [<br>        ({&quot;title&quot;: &quot;Foo&quot;}, 200),  # Test with valid data<br>        ({&quot;invalid_key&quot;: &quot;&quot;}, 422),  # Test without key title<br>        ({&quot;title&quot;: &quot;&quot;}, 422),  # Test with empty title<br>        ({&quot;title&quot;: None}, 422),  # Test with None as title<br>        (&quot;title&quot;, 422),  # Test without dict<br>    ],<br>)<br>def test_create_todo(<br>    client_user: TestClient, data: Union[dict, str], expected_status_code: int<br>) -&gt; None:<br>    response = client_user.post(<br>        f&quot;{settings.API_V1_STR}/todos/create-todo&quot;,<br>        json=data,<br>    )<br>    assert response.status_code == expected_status_code</pre><p>This test <strong>will run 5 times with different values for data and expected_status_code</strong>. We test the create-todo endpoint with different input data. The first test is for successful creation of a todo, while the others are validation errors (e.g., incorrect key in the dictionary, empty title string, etc.).</p><p>Instead of writing a new test function, we simply add a new element to the decorator’s list.<strong> </strong>Using the parametrize decorator reduces repetition, making the tests easier to read and maintain.</p><h3>Conclusion</h3><p>We have ended up with the following file structure:</p><pre>tests/<br>├── api/                        # API related tests<br>│   ├── api_v1/                 # Tests for API version 1<br>│   │   ├── test_login.py       # Tests for login functionality<br>│   │   ├── test_todos.py       # Tests for todos functionality<br>│   │   ├── test_users.py       # Tests for user-related functionality<br>│<br>├── constants/                  # Storage of test constants<br>│   └── user.py                 # Constants related to users<br>│<br>├── crud/                       # CRUD-related tests<br>│   ├── test_todo.py            # Tests for CRUD operations on todos<br>│   └── test_user.py            # Tests for CRUD operations on users<br>│<br>├── factories/                  # SQLAlchemy model factories for tests<br>│   ├── todo.py                 # Factory for Todo model<br>│   └── user.py                 # Factory for User model<br>│<br>├── fixtures/                   # Test fixtures<br>│   ├── authorization.py        # Fixtures for authorization<br>│   ├── todo.py                 # Fixtures for todo-related tests<br>│   └── user.py                 # Fixtures for user-related tests</pre><p>We improved the tests by doing the following:</p><ul><li>Used a <strong>test PostgreSQL database</strong> to ensure isolation and repeatability of tests.</li><li><strong>Added fixtures</strong> to set up tests and avoid code repetition.</li><li><strong>Added Factory</strong> to simplify the creation of test data and reduce repetitive code.</li><li>Created an <strong>API Test Client</strong> with autentication for testing API endpoints.</li><li>Wrote a few <strong>tests using fixtures</strong>.</li><li>Created a <strong>test using patch</strong> to avoid calling an external service during tests.</li><li>Implemented a<strong> parameterized test</strong> to test the API with different data inputs.</li></ul><p>The source code of the project is avaliable on GitLab: <a href="https://gitlab.com/FedorGN/todo-fastapi-reactjs">https://gitlab.com/FedorGN/todo-fastapi-reactjs</a> .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*xzLk-qpxY2nQ8L5yXu09Tw.png" /><figcaption>Test results.</figcaption></figure><h3>Useful Links:</h3><ol><li><a href="https://medium.com/@gnetkov/modern-application-template-with-fastapi-reactjs-docker-2a87e44dc3b0">https://medium.com/@gnetkov/modern-application-template-with-fastapi-reactjs-docker-2a87e44dc3b0</a> — article “Modern Application Template with FastAPI, ReactJS, Docker”</li><li><a href="https://docs.pytest.org/en/6.2.x/fixture.html">https://docs.pytest.org/</a> — pytest package official website.</li><li><a href="https://factoryboy.readthedocs.io/en/stable/">https://factoryboy.readthedocs.io/en/stable/</a> — Factory Boy package official documentation.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57080960fd62" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>