<?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 Alex on Medium]]></title>
        <description><![CDATA[Stories by Alex on Medium]]></description>
        <link>https://medium.com/@chitsalex?source=rss-4bb1162eee89------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*xhS96yKZEhXlQV-t</url>
            <title>Stories by Alex on Medium</title>
            <link>https://medium.com/@chitsalex?source=rss-4bb1162eee89------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:44:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chitsalex/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[I improved fastapi-viewsets: soft deletes, nested resources, search, and filters — all in one class]]></title>
            <link>https://medium.com/@chitsalex/i-improved-fastapi-viewsets-soft-deletes-nested-resources-search-and-filters-all-in-one-class-9efd238d0e14?source=rss-4bb1162eee89------2</link>
            <guid isPermaLink="false">https://medium.com/p/9efd238d0e14</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[python-web-developer]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Alex]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 05:27:05 GMT</pubDate>
            <atom:updated>2026-11-05T05:27:05.606Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve ever built anything more complex than a demo project with FastAPI, you probably know the feeling. A new entity appears, and once again you write the same five endpoints: list, retrieve by ID, create, update, and delete. Once again, there’s `limit` and `offset`. Once again, you raise `HTTPException(404)` when a record doesn’t exist. Once again, you end up debating the right way to handle PATCH. A month later, the product manager shows up and says, “Permanent deletion is off the table; I need a trash bin.” And you start all over again.</p><p>That’s exactly why I originally built **fastapi-viewsets** — Django REST Framework-style ViewSets for FastAPI. You describe a model and a Pydantic schema and get a ready-to-use `APIRouter` with CRUD. The library works with SQLAlchemy (sync and async), Tortoise ORM, and Peewee.</p><p>Over the past six months, I’ve improved it significantly. I started with declarative eager loading in 1.3.0, then released **1.7.0** in October with soft deletes and nested resources. Below, I’ll walk you through what I built, why I needed it, and how it works in code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oGgMcRyhbgwm1oyQj8teMA.jpeg" /></figure><h3>The starting point: the real cost of a basic CRUD</h3><p>Let’s start with what the library eliminates. Here’s a typical CRUD implementation in plain FastAPI with SQLAlchemy — and it’s already heavily trimmed down:</p><pre>@app.get(&quot;/items&quot;, response_model=list[ItemSchema])<br>def list_items(limit: int = 10, offset: int = 0, db: Session = Depends(get_db)):<br>    return db.query(Item).offset(offset).limit(limit).all()<br><br><br>@app.get(&quot;/items/{id}&quot;, response_model=ItemSchema)<br>def get_item(id: int, db: Session = Depends(get_db)):<br>    item = db.get(Item, id)<br>    if item is None:<br>        raise HTTPException(status_code=404, detail=&quot;Not found&quot;)<br>    return item<br><br><br>@app.post(&quot;/items&quot;, response_model=ItemSchema)<br>def create_item(payload: ItemSchema, db: Session = Depends(get_db)):<br>    item = Item(**payload.model_dump(exclude={&quot;id&quot;}))<br>    db.add(item)<br>    db.commit()<br>    db.refresh(item)<br>    return item<br><br># ...plus PUT, PATCH, and DELETE. Repeat for every model.</pre><p>There’s still no search, ordering, filtering, `IntegrityError` handling, or protection against a negative `limit`. Here’s the same example with fastapi-viewsets:</p><pre>pip install &quot;fastapi-viewsets[sqlalchemy]&quot;<br>pip install uvicorn  # to run the application</pre><pre>from typing import Optional<br><br>from fastapi import FastAPI<br>from pydantic import BaseModel, ConfigDict<br>from sqlalchemy import Column, Integer, String<br><br>from fastapi_viewsets import BaseViewset<br>from fastapi_viewsets.db_conf import Base, engine, get_session<br><br>app = FastAPI()<br><br><br>class Item(Base):<br>    __tablename__ = &quot;items&quot;<br>    id = Column(Integer, primary_key=True)<br>    name = Column(String(255), nullable=False)<br><br><br>class ItemSchema(BaseModel):<br>    model_config = ConfigDict(from_attributes=True)<br>    id: Optional[int] = None<br>    name: str<br><br><br>Base.metadata.create_all(bind=engine)<br><br>items = BaseViewset(<br>    endpoint=&quot;/items&quot;,<br>    model=Item,<br>    response_model=ItemSchema,<br>    db_session=get_session,<br>    tags=[&quot;items&quot;],<br>)<br>items.register(methods=[&quot;LIST&quot;, &quot;GET&quot;, &quot;POST&quot;, &quot;PATCH&quot;, &quot;DELETE&quot;])<br>app.include_router(items)</pre><p>BaseViewset inherits from APIRouter, so you can include it with a regular include_router. The `<em>register()</em>` method creates the routes `<em>GET /items</em>`, `GET /items/{id}`, `POST /items`, `PATCH /items/{id}`, and `DELETE /items/{id}`. Call it without arguments, and it registers every method, including `PUT`. For asynchronous code, there’s <strong>AsyncBaseViewset</strong> with the same API. It needs an async session, such as `<em>get_async_session</em>` from <em>fastapi_viewsets.db_conf</em>, and a driver like `<em>aiosqlite</em>` or `<em>asyncpg</em>`.</p><p>That was the baseline. Now let’s look at what I added.</p><h3>Chapter 1. Enough N+1: declarative eager loading (1.3.0)</h3><p>The first pain point came from nested schemas. As soon as the response includes <strong><em>author: AuthorSchema</em></strong>, SQLAlchemy issues a separate query for every row in the list. That’s the classic N+1 problem.</p><p>I didn’t want to override list() in every viewset just to deal with it. So I decided to keep relationship-loading settings right in the schema, next to the fields that need them. That’s how the internal `RelatedConfig` class appeared in version 1.3.0:</p><pre>class AuthorSchema(BaseModel):<br>    model_config = ConfigDict(from_attributes=True)<br>    id: int<br>    name: str<br><br><br>class PostSchema(BaseModel):<br>    model_config = ConfigDict(from_attributes=True)<br>    id: int<br>    title: str<br>    author: AuthorSchema<br><br>    class RelatedConfig:<br>        select_related = [&quot;author&quot;]   # FK / many-to-one → JOIN<br>        prefetch_related = [&quot;tags&quot;]   # collections / M2M → a separate SELECT IN</pre><p>You don’t need to change the viewset itself: <strong><em>BaseViewset</em></strong> and <strong><em>AsyncBaseViewset</em></strong> pass these lists to the ORM adapter for <strong>LIST</strong> and <strong>GET</strong>. In <strong><em>SQLAlchemy</em></strong>, they map to `<em>joinedload</em>` and `<em>selectinload</em>`. Tortoise passes both lists to its native `prefetch_related()`, while <strong><em>Peewee</em></strong> turns `select_related` into `.join()`.</p><h3>Chapter 2. Search, ordering, and filters without a single line in the viewset (1.5.0)</h3><p>The next question I kept hearing was, “How do I add `?search=`?” My usual answer used to be, “Override `list()`.” An honest answer, but a boring one.</p><p>In 1.5.0, I took the same approach as with <strong><em>RelatedConfig</em></strong> and added an internal <strong><em>ListConfig</em></strong> class:</p><pre>class PostSchema(BaseModel):<br>    model_config = ConfigDict(from_attributes=True)<br>    id: Optional[int] = None<br>    title: str<br>    status: str = &quot;draft&quot;<br><br>    class ListConfig:<br>        search_fields = [&quot;title&quot;]           # ?search=fastapi<br>        ordering_fields = [&quot;title&quot;, &quot;id&quot;]   # ?ordering=-title,id<br>        ordering = [&quot;-id&quot;]                  # default ordering<br>        filters = [&quot;status&quot;, &quot;id&quot;]          # ?status=published, ?id__gte=2</pre><p>The list endpoint now supports:</p><ul><li><strong>?search=term</strong> — a case-insensitive substring search across all `search_fields` (combined with OR);<br>- <strong>?ordering=-title,id</strong> — ordering, but only by fields listed in `<em>ordering_fields</em>`. An unknown field returns `400` instead of being sent to the database;<br>- <strong>filters. — </strong>exact matches and the operators `__ne`, `__gt`, `__gte`, `__lt`, `__lte`, `__contains`, and `__in`. Values are coerced to int/float/bool.</li></ul><p>GET /posts?search=fastapi&amp;ordering=title<br>GET /posts?status=published&amp;id__gte=2<br>GET /posts?status__in=draft,published&amp;limit=20&amp;offset=40<br>GET /posts?ordering=secret → 400 Invalid ordering field: ‘secret’. Allowed fields: [‘id’, ‘title’]</p><p>What mattered most to me was the <strong>allowlist</strong>: only explicitly listed fields reach the ORM. Filters on unknown fields are simply ignored, while unknown ordering fields return `400`. All of this works across the four backends: SQLAlchemy sync/async, Tortoise, and Peewee. In 1.5.2, I also exposed the filters and their `__op` variants in OpenAPI, so you can see them in Swagger UI too.</p><h3>Chapter 3. Fixing my mistakes: the changes people usually leave out of release posts (1.5.1–1.5.3)</h3><p>Not every improvement makes for a flashy announcement. In September and October, I worked on the unglamorous things a library needs before you can trust it. I’ll be honest: some of these bugs were nasty.</p><p><strong>Schema leakage between viewsets.</strong> Previously, `register()` modified the `__annotations__` of shared handler functions at the class level. As a result, in a process with two or more viewsets, every `POST`/`PUT`/`PATCH` validated the request body against the schema belonging to the *last registered* viewset. In 1.5.2, I started cloning the handlers for each instance.</p><p><strong>PATCH is now genuinely partial.</strong> PATCH bodies are validated by an automatically generated `&lt;Schema&gt;Patch` schema in which every field is optional. An explicit `null` clears a nullable column and no longer gets lost. In 1.5.3, I finished the job: the partial schema preserves field validators, `Field` constraints, aliases, and the model configuration. Model-level validators don’t run against incomplete payloads. If you need invariants across fields, validate them against the final record.</p><p><strong>PUT no longer wipes data.</strong> Previously, columns absent from the schema were turned into `NULL` on `PUT`. That was actual data loss. Now only the fields actually present in the request are written, and the primary key is never overwritten.</p><p><strong>409 instead of leaking SQL.</strong> Database constraint violations now return `409 Conflict` with a neutral message. Raw SQL, parameters, and driver internals no longer make their way into the response.</p><p><strong>Honest packaging.</strong> The base `pip install fastapi-viewsets` now installs only FastAPI, Pydantic, and python-dotenv. SQLAlchemy comes via the `[sqlalchemy]` extra, which also brings in `SQLAlchemy[asyncio]` and `greenlet`. Python 3.14 support arrived in 1.4.0, and CI now runs all ORM adapters across the entire Python version matrix.</p><h3>Chapter 4. A trash bin instead of DELETE FROM: soft deletes (1.7.0)</h3><p>Now for the headline feature of the latest release. Sooner or later, almost every project I worked on grew an `is_deleted` flag. Then the same checks spread through the codebase: don’t show deleted records in lists, return 404 on GET, and don’t allow deleted records to be edited. And there was always one place where a check got missed.</p><p>In 1.7.0, you can enable soft deletes with a single parameter — `soft_delete=SoftDeleteConfig()`:</p><pre>from sqlalchemy import Boolean, Column<br>from fastapi_viewsets import BaseViewset, SoftDeleteConfig<br><br><br>class Post(Base):<br>    __tablename__ = &quot;posts&quot;<br>    id = Column(Integer, primary_key=True)<br>    title = Column(String, nullable=False)<br>    is_deleted = Column(Boolean, nullable=False, default=False, server_default=&quot;false&quot;)<br><br><br>posts = BaseViewset(<br>    endpoint=&quot;/posts&quot;,<br>    model=Post,<br>    response_model=PostSchema,<br>    db_session=get_session,<br>    soft_delete=SoftDeleteConfig(),<br>)<br>posts.register()<br>app.include_router(posts)</pre><p>Here’s what changes:</p><p>- DELETE /posts/{id} sets the marker instead of physically deleting the row;<br>- `LIST` and `GET` hide deleted records. Filtering happens in the database <strong>before pagination</strong>, so `limit=10` really does return ten active records;<br>- `PUT`/`PATCH` and a repeated `DELETE` against a deleted record return `404`;<br>- a new <strong>`POST /posts/{id}/restore`</strong> route appears. If you register `DELETE`, `RESTORE` is added automatically and inherits its OAuth2 protection;<br>- the client cannot change the marker through POST/PUT/PATCH bodies or bypass the “active only” restriction through query filters.</p><p>If you need to know <strong>when</strong> a record was deleted, use a timestamp marker:</p><pre>policy = SoftDeleteConfig(field=&quot;deleted_at&quot;, mode=&quot;timestamp&quot;)</pre><p>Restoration uses the same protection as deletion:</p><pre>from fastapi.security import OAuth2PasswordBearer<br><br>posts.register(<br>    oauth_protect=OAuth2PasswordBearer(tokenUrl=&quot;/token&quot;),<br>    protected_methods=[&quot;DELETE&quot;],  # RESTORE inherits this protection<br>)</pre><p>I deliberately left the database schema under your control: <strong>the library does not modify it</strong>. Add and backfill the marker column in your own migration before enabling the option. The marker does not cascade to related records. Direct ORM queries and other viewsets using the same model do not inherit this policy. By default, `soft_delete=None`, and everything works as before: a physical DELETE and the same routes.</p><h3>Chapter 5. `/posts/{post_id}/comments`: nested resources (1.7.0)</h3><p>The second major feature in this release is nested resources. Previously, you had to build a route like `/posts/{post_id}/comments` by hand. You needed to check that the post existed, filter comments by `post_id`, set `post_id` when creating a comment, and make sure a PATCH request couldn’t move a comment to someone else’s post. Every one of those steps was a potential access-control hole.</p><p>Now `NestedConfig` handles all of that:</p><pre>from fastapi_viewsets import BaseViewset, NestedConfig<br>from fastapi_viewsets.orm.sqlalchemy_adapter import SQLAlchemyAdapter<br><br>adapter = SQLAlchemyAdapter(database_url=&quot;sqlite:///blog.db&quot;)<br>Base = adapter.get_base()<br><br><br>class Comment(Base):<br>    __tablename__ = &quot;comments&quot;<br>    id = Column(Integer, primary_key=True)<br>    post_id = Column(Integer, ForeignKey(&quot;posts.id&quot;), nullable=False)<br>    text = Column(String, nullable=False)<br><br><br>class CommentSchema(BaseModel):<br>    model_config = ConfigDict(from_attributes=True)<br>    id: Optional[int] = None<br>    post_id: int<br>    text: str<br><br><br>comments = BaseViewset(<br>    endpoint=&quot;/posts/{post_id}/comments&quot;,<br>    model=Comment,<br>    response_model=CommentSchema,<br>    db_session=adapter.get_session,<br>    orm_adapter=adapter,<br>    nested=NestedConfig(parent_model=Post, foreign_key=&quot;post_id&quot;),<br>)<br>comments.register()<br>app.include_router(comments)</pre><p>Now you can create a comment with the body `{“text”: “Hello”}`, and `post_id` comes from the URL. Even if the client sends `”post_id”: 3` in the JSON, the URL wins: the value is injected before body validation and checked again at the ORM level. A missing parent or a comment belonging to a different post returns `404`. Search, filters, ordering, and pagination are all scoped to the parent.</p><p>You can access the parent inside a handler through `self.get_parent()` or `request.state.viewset_parent`. The context is bound to the request and works correctly in both sync and async handlers. I’ve seen nesting confused with authorization more than once, so I added an explicit extension point — `resolve_parent(request)`:</p><pre>from fastapi import HTTPException, Request<br>from fastapi_viewsets import AsyncBaseViewset<br><br><br>class AuthorizedComments(AsyncBaseViewset):<br>    async def resolve_parent(self, request: Request):<br>        parent = await super().resolve_parent(request)<br>        # your authentication dependency sets request.state.user<br>        if not request.state.user.can_access(parent):<br>            raise HTTPException(status_code=403, detail=&quot;Forbidden parent&quot;)<br>        return parent</pre><p>Both 1.7.0 features work together. If you pass `parent_soft_delete`, a deleted post blocks all operations on its comments, including restoring them:</p><pre>policy = SoftDeleteConfig()<br><br>comments = BaseViewset(<br>    endpoint=&quot;/posts/{post_id}/comments&quot;,<br>    model=Comment,<br>    response_model=CommentSchema,<br>    db_session=get_session,<br>    soft_delete=policy,<br>    nested=NestedConfig(parent_model=Post, foreign_key=&quot;post_id&quot;, parent_soft_delete=policy),<br>)<br>comments.register()</pre><p>Among the other options, `path_param` lets you customize the URL parameter name — for example, when the parent path is defined on an outer `APIRouter(prefix=”/posts/{post_pk}”)`. Integer, string, and UUID parent keys are supported. There are limitations too: the parent must have a single primary key named `id`, and each viewset supports one parent.</p><h4>What this looks like in practice</h4><p>I put together a small blog from the examples above: posts with `ListConfig` and soft deletes, plus comments via `NestedConfig`. Here are the actual responses from 1.7.0:</p><pre>POST  /posts {&quot;title&quot;: &quot;FastAPI tips&quot;, &quot;status&quot;: &quot;published&quot;}   → {&quot;id&quot;: 1, ...}<br>GET   /posts?search=fastapi&amp;ordering=title                     → posts 1 and 3<br>POST  /posts/1/comments {&quot;text&quot;: &quot;hi&quot;, &quot;post_id&quot;: 3}           → {&quot;id&quot;: 2, &quot;post_id&quot;: 1, &quot;text&quot;: &quot;hi&quot;}<br>GET   /posts/2/comments                                        → []<br>DELETE /posts/1                                                → {&quot;status&quot;: true, &quot;text&quot;: &quot;successfully deleted&quot;}<br>GET   /posts/1                                                 → 404<br>GET   /posts/1/comments                                        → 404  (parent is soft-deleted)<br>POST  /posts/1/restore                                         → {&quot;status&quot;: true, &quot;text&quot;: &quot;successfully restored&quot;}<br>POST  /posts/1/restore                                         → 404  (already active)<br>GET   /posts?limit=-1                                          → 422</pre><h3>How I approached it</h3><p>In short, I followed three rules.</p><p>1. <strong>Configuration next to the data.</strong> `RelatedConfig` and `ListConfig` live in the schema, while `SoftDeleteConfig` and `NestedConfig` go in the viewset constructor. You only need to subclass and override `list()` for truly custom logic. That option hasn’t gone anywhere: all CRUD handlers remain ordinary methods.<br>2. <strong>Everything new is opt-in. </strong>All new parameters default to `None`. Third-party ORM adapters keep working. An adapter explicitly enables support for the new features through `supports_soft_delete = True` and `supports_nested = True`.<br>3. <strong>Secure by default.</strong> Field allowlists for filters and ordering, the URL taking precedence over the request body, 409 responses without SQL, and a deletion marker that clients cannot access.</p><p>By the 1.7.0 release, the test suite had grown to 496 tests. They run in two environments: Python 3.13 with current FastAPI and Pydantic, and an older stack with Python 3.11, FastAPI 0.110, Pydantic 2.5, and SQLAlchemy 2.0.0. Coverage is around 90%. A separate note on Python 3.9: it is functionally supported, but some of its dependencies have known vulnerabilities that cannot be fixed on that version. For production, I recommend 3.11+.</p><h3>Try it</h3><pre>- **GitHub:** https://github.com/svalench/fastapi_viewsets<br>- **PyPI:** https://pypi.org/project/fastapi-viewsets/<br>- **Documentation:** https://svalench.github.io/fastapi_viewsets/<br>- **Release notes 1.7.0:** https://github.com/svalench/fastapi_viewsets/blob/master/RELEASE_1.7.0.md</pre><p>If the library has saved you even one evening of writing yet another CRUD, give it a ⭐ on GitHub — it helps others find the project. Bug reports, ideas, and pull requests are welcome. The repository has a “PRs welcome” badge, and I genuinely mean it.</p><p><strong><em>Thanks for reading! Let me know in the comments which feature you miss most in out-of-the-box FastAPI.</em></strong></p><p>Best regards, <a href="https://valenchits.dev/">valenchits</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9efd238d0e14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Writes Code Now. So What Do We Still Need Programmers For?]]></title>
            <link>https://medium.com/@chitsalex/ai-writes-code-now-so-what-do-we-still-need-programmers-for-9bef70ff467e?source=rss-4bb1162eee89------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bef70ff467e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alex]]></dc:creator>
            <pubDate>Sun, 13 Sep 2026 09:47:23 GMT</pubDate>
            <atom:updated>2026-09-13T09:47:23.591Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Why the “developers are doomed” cycle keeps missing the point — and what the research actually says.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vlt7bfl2dutbK1k0CV6Zjg.jpeg" /></figure><p>The wave hit again recently. New model drops, my feed fills up with “programmers have six months left,” and a couple of junior devs I know message me — like, hey lead, so is it over for us? Honestly, I’ve watched this cycle maybe four times now. When Copilot came out — same conversation. When GPT started writing decent Python — same conversation. And yet the job postings somehow didn’t shrink.</p><p>So here’s why I don’t buy the “programmers are finished” thing. Not because I’m defending my own profession (though sure, probably that too), but because I see every single day what a developer actually does. And it is not what a neural network does.</p><h3>The secret: we don’t write code. Well, we do, but that’s not the point</h3><p>Picture a call I’ve been on a hundred times. The client says: “We need a report export. A little button here, downloads to Excel.” Hand that sentence to a model and it will honestly generate an export. A nice one. With pagination. Everything by the book.</p><p>Me? When I hear “export to Excel,” my brain immediately goes: who is this for, and how often? Because if a thousand managers pull a hundred-thousand-row report every Monday morning, the database goes down. I’ve fixed exactly that before. Then I remember the report definitely has names and phone numbers in it, so I ask — are we really sure sales should see all of this? And then it turns out they don’t need Excel at all, they need a dashboard. The client just doesn’t know the word “dashboard.”</p><p>That whole conversation <em>is</em> the job. Sure, the code afterwards I can generate myself — no argument there. But where would a model get those questions from? It answers what’s written. And what was written is “a little button here.”</p><h3>Now the boring part — the numbers</h3><p>I actually went and read through the research while writing this, so here it is, with no cherry-picking in my favor.</p><p>IBM, in <a href="https://www.ibm.com/think/news/ai-write-code-can-beat-software-engineers">“AI can write code, but can it beat software engineers?”</a>, puts it like this: AI-generated code carries roughly 2.7x the security vulnerabilities of human-written code, 1.7x the bugs, and about 75% more logic errors. Logic errors, by the way, are the ones that don’t crash. They just quietly calculate the wrong thing. For months. A perfect gift for a client who “saved money on developers.”</p><p>A survey on arXiv, <a href="https://arxiv.org/html/2512.05239v1">“A Survey of Bugs in AI-Generated Code”</a>, adds more: in Copilot-based studies, around 40% of generated code came out with vulnerabilities. And my favorite, from a paper in JSE — <a href="https://www.icck.org/filebob/uploads/storage/JSE_FyL0HuDVujarkKO0C.pdf">“Is AI Code Generation Undermining Developers’ Problem-Solving Skills”</a>: when you ask a model to keep fixing its own code over and over, after five iterations the critical vulnerabilities <em>increase</em> by 37-something percent. It doesn’t clean up its own mistakes. It warehouses them.</p><p>And this isn’t “the model is dumb.” It’s “the model wasn’t in the room.” It doesn’t know that the orders table in our database historically also stores returns (don’t ask). It doesn’t know you don’t touch the bank integration on Fridays. It doesn’t know that “I want it like the competitors” must never, ever be taken literally.</p><h3>The main point, which nobody writes about for some reason</h3><p>Everything above is technical. Now the thing that actually decides the matter. And it’s embarrassingly simple: accountability.</p><p>Look at it from the paying side. A business doesn’t buy code from a developer. A business buys the state of “there is someone responsible for this thing.” A person you can drag into a call, who has a name, a reputation, and a contract. Who signs off on shipping to prod. And who you can yell at when prod goes down.</p><p>You can’t drag a model into a call. There are decent pieces on this — Gary Goldhammer wrote <a href="https://www.linkedin.com/pulse/ai-accountability-gap-gary-goldhammer-vlgwc">“The AI Accountability Gap”</a>, and the folks at Not For Humans did a write-up on the <a href="https://notforhumans.com.au/lexicon/governance-and-accountability/accountability-gap/">accountability gap</a>. The shared idea: when an algorithm messes up, there’s nobody to blame. Everything diffuses down the chain — the model messed up, but I entered the prompt, but the model was trained somewhere in California. Everyone is responsible, which means no one is. Clients don’t know these terms, but they feel it in their gut. Which is why even the most progressive companies keep a human signature under every release.</p><h3>“Fine, let the client talk to the neural network themselves!”</h3><p>Heard that one already. The argument sounds logical — until you remember what a real client actually looks like.</p><p>There’s a fun study from HEC Paris, <a href="https://www.hec.edu/en/dare/innovation-entrepreneurship/why-people-trust-ai-more-humans-even-when-it-s-flawed">“Why People Trust AI More Than Humans — Even When It’s Flawed”</a>. The title says it all: for simple questions, people trust algorithms more than humans. Everyone trusts a calculator. But the moment money, reputation, or the fate of a project is on the line — game over, people reach for a human. The chatbot trust study in customer service, <a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC12953761/">“Building user trust in AI chatbots for customer service”</a>, says the same: while the question is simple, the bot is tolerated; the moment something broke <em>for you personally</em>, it’s “get me an operator.”</p><p>Now imagine the dialog. A real one, I’ve had it: “We need something like a personal account page, but not the usual kind… our accounting is complicated. Let me send you how we do it in Excel.” And they send a file. Three hundred columns, two sheets, half the formulas pointing into the void. A day of scoping and a couple of spoken questions later — there’s a spec the client couldn’t have written themselves in a week or a month. Because they thought they needed a client portal, and what they needed was to automate their invoices.</p><p>Which, by the way, answers the old debate of “a programmer is just an executor of someone else’s will, same as a neural net.” Nope. A programmer is the one who first figures out what the will even <em>is</em>. Execution is the second half of the job — and yes, most of that half is being automated already.</p><h3>What does the market actually show?</h3><p>We’re not riding on my gut feeling alone. The folks at Don’t Panic Labs recently went through the fresh research in <a href="https://dontpaniclabs.com/blog/post/2026/03/12/ai-replacing-software-developers-what-the-latest-research-actually-shows/">“AI Replacing Software Developers? What the Latest Research Actually Shows”</a>, and citing Goldman Sachs the picture goes: roughly a quarter of work hours are technically automatable, but the share of occupations that disappear entirely because of that is around 6–7%. The rest don’t disappear. They change.</p><p>Software development gets called out there specifically as a profession where the <em>tasks</em> get automated, not the profession itself. Because it’s not just “write the function.” There’s judgment, context, negotiating with the same stakeholders.</p><p>MIT CSAIL says exactly the same thing in technical language — here’s their release: <a href="https://www.csail.mit.edu/news/can-ai-really-code-study-maps-roadblocks-autonomous-software-engineering">“Can AI really code? Study maps the roadblocks to autonomous software engineering”</a>. The benchmarks where AI is “basically a mid-level dev” are isolated little tasks in a vacuum. Real work is legacy code, a library with no docs, a bug that reproduces once a month on even-numbered days. On all of that, the model and the developer are still playing in different leagues.</p><p>A spoonful of tar, to keep it honest. The same studies notice something unpleasant: juniors who generate everything from day one understand their own code worse. Conceptual test scores dropped by about a quarter. The code works, but <em>why</em> it works — nobody knows. Two years down the line, that team is sitting on a project no one can maintain, and hello, “AI legacy.”</p><h3>So who does it replace, then?</h3><p>This guy: boilerplate. Spinning up CRUD, writing tests for a function, following a migration template — all of that is going away, and good riddance. I built fastapi-viewsets back in the day for exactly that reason — why should I write the same endpoints for the fiftieth time? One class, one register, done. AI is the same principle, just a bigger tool.</p><p>What stays with the developer: listening to what the person across from you means, not what they say. Catching the moment where “like the competitors” means “not like the competitors.” Calculating in advance where we’ll hit the wall in prod. Saying “no” — clients actually end up liking that one, when it saves them money. And when prod does go down — picking up the phone, apologizing, fixing it. For every one of these points, no model I know of is even in shouting distance. Not because they’re stupid. Because these aren’t coding tasks.</p><h3>Instead of a conclusion</h3><p>I’ll write the phrase anyway, banal as it sounds — <a href="https://www.coursera.org/articles/will-ai-replace-programmers">Coursera’s FAQ</a> uses it too: AI doesn’t replace programmers. Programmers with AI replace programmers without AI. Boring truth, not headline material, but it’s easy to live with.</p><p>So, two pieces of advice. To companies: don’t rush to cut engineers — the role isn’t disappearing, it’s moving up the “understand → decide → write” chain. And to developers: if you’re still proud of writing everything by hand, it’s time to stop. Your future self will thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bef70ff467e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[fastapi-viewsets vs fastapi-crudrouter: Which CRUD Generator Should You Pick in 2026?]]></title>
            <link>https://medium.com/@chitsalex/fastapi-viewsets-vs-fastapi-crudrouter-which-crud-generator-should-you-pick-in-2026-af5dda530f7c?source=rss-4bb1162eee89------2</link>
            <guid isPermaLink="false">https://medium.com/p/af5dda530f7c</guid>
            <dc:creator><![CDATA[Alex]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 04:20:47 GMT</pubDate>
            <atom:updated>2026-08-18T04:20:47.178Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve built more than one FastAPI service, you know the drill: define a model, define a schema, then write the same five endpoints: list, retrieve, create, update, delete over and over again. Two libraries try to kill that boilerplate: the veteran <strong>fastapi-crudrouter</strong> and the newer, DRF-inspired <strong>fastapi-viewsets</strong>. Here’s how they actually compare.</p><h3>The Core Idea</h3><p>Both libraries generate CRUD routes automatically, but they start from different mental models.</p><p><strong>fastapi-crudrouter</strong>, created by Adam Watkins back in December 2020, treats each resource as a self-contained router. You instantiate a CRUDRouter a subclass of FastAPI&#39;s own APIRouterpoint it at a model and a schema, and it hands you a fully working set of REST routes in about ten lines of code.</p><p><strong>fastapi-viewsets</strong> borrows its philosophy from Django REST Framework’s ViewSets. Instead of a router factory, you define a BaseViewset class, override what you need, and call .register() to wire it up. If you&#39;ve ever written a DRF ModelViewSet, this will feel instantly familiar.</p><p>That difference in philosophy <em>generate a router</em> vs <em>define a controller class</em>is the thread that runs through almost every other comparison point below.</p><h3>Where fastapi-crudrouter Wins</h3><p><strong>Track record.</strong> This is the library everyone in the FastAPI ecosystem has at least heard of. It sits around 1.5k GitHub stars, 168 forks, and is a dependency in 240+ public repositories -numbers that fastapi-viewsets simply hasn’t reached yet.</p><p><strong>ORM breadth.</strong> Six supported backends (SQLAlchemy, Tortoise, Ormar, Databases, Gino, and an in-memory backend) versus three for its rival. If your stack uses one of the less common ORMs, crudrouter is more likely to already support it.</p><p><strong>Battle-tested simplicity.</strong> The “ten lines of code” pitch isn’t marketing fluff for a simple CRUD resource with no custom logic, crudrouter genuinely gets you there faster than any class-based alternative.</p><h3>Where fastapi-crudrouter Loses</h3><p><strong>It’s effectively unmaintained.</strong> No release since v0.8.6 in January 2023 is a serious red flag in an ecosystem that moves as fast as FastAPI and Pydantic do. There’s no confirmed Pydantic v2 support, which matters a lot if you’re starting a project today.</p><p><strong>Limited extensibility.</strong> Because routes are generated rather than defined as overridable methods, customizing behavior beyond what the library anticipates often means abandoning the abstraction and writing routes by hand anyway.</p><h3>Where fastapi-viewsets Wins</h3><p><strong>Modern stack, actively maintained.</strong> Version 1.3.0 ships with Pydantic v2 support and the project is clearly under active development, unlike its older rival.</p><p><strong>Familiar to Django developers.</strong> If your team has DRF experience, the ViewSet pattern maps almost one-to-one onto what they already know — list, create, retrieve, update, destroy which shortens the learning curve dramatically.</p><p><strong>Real extensibility.</strong> Because a viewset is just a class, overriding a single method (say, adding a custom filter to list()) doesn&#39;t require fighting the abstraction — you just override it.</p><p><strong>Granular authorization.</strong> Auth can be applied per method rather than per router, which is a meaningfully different (and often more useful) security model for APIs with mixed public/private endpoints.</p><h3>Two different mental models</h3><p>Both libraries generate CRUD routes automatically, but they start from different places.</p><p>fastapi-crudrouter, created by awtkns in December 2020, treats each resource as a self-contained router. You instantiate a CRUDRouter (a subclass of FastAPI&#39;s own APIRouter), point it at a model and a schema, and it hands you a fully working set of REST routes in about ten lines of code.</p><p>fastapi-viewsets borrows its philosophy from Django REST Framework&#39;s ViewSets. Instead of a router factory, you define a BaseViewset class, override what you need, and call .register() to wire it up. If you&#39;ve ever written a DRF ModelViewSet, this will feel instantly familiar.</p><p>The difference between “generate a router” and “define a controller class” shapes almost everything else.</p><h3>Track record and ecosystem</h3><p>This is where fastapi-crudrouter has a real edge. It&#39;s the library everyone in the FastAPI ecosystem has at least heard of. As of August 2026, it sits at roughly 1,700 GitHub stars and 178 forks, and it&#39;s a dependency in 240+ public repositories. fastapi-viewsets hasn&#39;t reached those numbers. The community is smaller, there&#39;s less Stack Overflow history, and fewer blog posts to fall back on when you hit an edge case.</p><p>If community size matters to you, crudrouter wins this round comfortably</p><h3>So which one should you use?</h3><p>Be specific about your situation:</p><ul><li><strong>You’re on Gino or Databases, or you need one of the six backends that only crudrouter supports.</strong> Use fastapi-crudrouter. Pin your dependencies carefully and don&#39;t expect Pydantic v2 fixes.</li><li><strong>You’re starting a new project on SQLAlchemy or Tortoise, you need custom logic beyond basic CRUD, and especially if your team has DRF experience.</strong> fastapi-viewsets is the better fit. I&#39;m biased, but the extensibility argument is the real one: if you&#39;re going to need custom behavior (and you probably are), you want a library that lets you add it without throwing away the abstraction.</li><li><strong>You just need five plain CRUD endpoints with zero custom logic and you want it working in ten minutes.</strong> Either library gets you there. fastapi-crudrouter is slightly faster to set up for this case because there&#39;s no class to define.</li></ul><p>Both libraries solve the same problem from different angles. The question isn’t which is “better” in the abstract, it’s which tradeoff fits your project: a mature library that’s gone quiet, or a younger one that’s still moving.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af5dda530f7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Shop Admin Panel CRUD in Minutes with fastapi-viewsets]]></title>
            <link>https://medium.com/@chitsalex/building-a-shop-admin-panel-crud-in-minutes-with-fastapi-viewsets-23d23bdcd6b1?source=rss-4bb1162eee89------2</link>
            <guid isPermaLink="false">https://medium.com/p/23d23bdcd6b1</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Alex]]></dc:creator>
            <pubDate>Sun, 28 Jun 2026 09:08:24 GMT</pubDate>
            <atom:updated>2026-06-28T09:13:27.735Z</atom:updated>
            <content:encoded><![CDATA[<p><em>If you’ve ever written the same LIST / GET / POST / PATCH / DELETE boilerplate five times in one sprint, you already know the pain. This post shows how </em>**<strong><em>fastapi-viewsets</em></strong>**<em> erases that boilerplate for a real-world use case: a tiny but fully functional shop admin panel.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*myR5qh4yaNzbuvkoeXug9w.png" /></figure><h4>The problem with plain FastAPI CRUD</h4><p>FastAPI is fantastic — but it has no built-in opinion on how to organise CRUD. Most tutorials end up looking like this:</p><pre>@router.get(&quot;/products&quot;, response_model=list[ProductSchema])<br>def list_products(db: Session = Depends(get_db)):<br>    return db.query(Product).all()<br><br>@router.post(&quot;/products&quot;, response_model=ProductSchema)<br>def create_product(body: ProductCreateSchema, db: Session = Depends(get_db)):<br>    obj = Product(**body.dict())<br>    db.add(obj); db.commit(); db.refresh(obj)<br>    return obj<br><br># … repeat for GET, PATCH, DELETE, and then again for Category, Order …</pre><p>Three resources × five endpoints = 15 nearly identical functions. The moment you need pagination or auth, you add that in 15 places.</p><p><strong>fastapi-viewsets</strong> brings Django REST Framework–style ViewSets to FastAPI: one class declaration auto-generates all six standard CRUD routes.</p><h4>What we’re building</h4><p>A minimal <strong>shop admin API</strong> with three resources:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m9TfWKhbvxhPf8XU0XOSIQ.jpeg" /></figure><h4>Project setup</h4><pre>pip install &quot;fastapi-viewsets[sqlalchemy]&quot; aiosqlite uvicorn</pre><p>We use <strong>async SQLAlchemy + aiosqlite</strong> for a zero-config local database. In production swap aiosqlite for asyncpg (PostgreSQL) or aiomysql (MySQL) — the rest of the code stays the same.</p><p>Create a .env file in the project root:</p><pre>ORM_TYPE=sqlalchemy<br>SQLALCHEMY_DATABASE_URL=sqlite:///./shop.db</pre><blockquote>`fastapi-viewsets` reads this automatically via `python-dotenv`.</blockquote><h4>Step 1 — Models (`models.py`)</h4><pre>from sqlalchemy import Column, ForeignKey, Integer, Numeric, String, Text<br>from fastapi_viewsets.db_conf import Base<br><br><br>class Category(Base):<br>    __tablename__ = &quot;categories&quot;<br><br>    id = Column(Integer, primary_key=True)<br>    name = Column(String(128), nullable=False, unique=True)<br>    description = Column(Text, nullable=True)<br><br><br>class Product(Base):<br>    __tablename__ = &quot;products&quot;<br><br>    id = Column(Integer, primary_key=True)<br>    name = Column(String(255), nullable=False)<br>    price = Column(Numeric(10, 2), nullable=False)<br>    stock = Column(Integer, default=0, nullable=False)<br>    category_id = Column(Integer, ForeignKey(&quot;categories.id&quot;), nullable=True)<br><br><br>class Order(Base):<br>    __tablename__ = &quot;orders&quot;<br><br>    id = Column(Integer, primary_key=True)<br>    customer_email = Column(String(255), nullable=False)<br>    product_id = Column(Integer, ForeignKey(&quot;products.id&quot;), nullable=False)<br>    quantity = Column(Integer, default=1, nullable=False)<br>    status = Column(String(32), default=&quot;pending&quot;, nullable=False)</pre><blockquote>Plain SQLAlchemy — nothing special here.</blockquote><h4>Step 2 — Pydantic schemas (`schemas.py`)</h4><pre>from decimal import Decimal<br>from typing import Optional<br>from pydantic import BaseModel, ConfigDict, EmailStr, Field<br><br><br>class CategorySchema(BaseModel):<br>    model_config = ConfigDict(from_attributes=True)<br><br>    id: Optional[int] = None<br>    name: str = Field(..., min_length=1, max_length=128)<br>    description: Optional[str] = None<br><br><br>class ProductSchema(BaseModel):<br>    model_config = ConfigDict(from_attributes=True)<br><br>    id: Optional[int] = None<br>    name: str = Field(..., min_length=1, max_length=255)<br>    price: Decimal = Field(..., gt=0)<br>    stock: int = Field(default=0, ge=0)<br>    category_id: Optional[int] = None<br><br><br>class OrderSchema(BaseModel):<br>    model_config = ConfigDict(from_attributes=True)<br><br>    id: Optional[int] = None<br>    customer_email: EmailStr<br>    product_id: int<br>    quantity: int = Field(default=1, ge=1)<br>    status: str = Field(default=&quot;pending&quot;)</pre><blockquote>`model_config = ConfigDict(from_attributes=True)` is the Pydantic v2 equivalent of `orm_mode = True`. It lets the viewset serialize ORM objects directly into the response.</blockquote><h4>Step 3 — Viewsets (`routers.py`)</h4><p>This is where the magic happens. Three resources, <strong>~20 lines</strong>:</p><pre>from fastapi.security import OAuth2PasswordBearer<br>from fastapi_viewsets import AsyncBaseViewset<br>from fastapi_viewsets.db_conf import get_async_session<br><br>from models import Category, Product, Order<br>from schemas import CategorySchema, ProductSchema, OrderSchema<br><br>oauth2 = OAuth2PasswordBearer(tokenUrl=&quot;/token&quot;)<br><br># --- Categories ---<br>categories = AsyncBaseViewset(<br>    endpoint=&quot;/categories&quot;,<br>    model=Category,<br>    response_model=CategorySchema,<br>    db_session=get_async_session,<br>    tags=[&quot;Admin / Categories&quot;],<br>)<br>categories.register(<br>    methods=[&quot;LIST&quot;, &quot;GET&quot;, &quot;POST&quot;, &quot;PATCH&quot;, &quot;DELETE&quot;],<br>    oauth_protect=oauth2,<br>    protected_methods=[&quot;POST&quot;, &quot;PATCH&quot;, &quot;DELETE&quot;],<br>)<br><br># --- Products ---<br>products = AsyncBaseViewset(<br>    endpoint=&quot;/products&quot;,<br>    model=Product,<br>    response_model=ProductSchema,<br>    db_session=get_async_session,<br>    tags=[&quot;Admin / Products&quot;],<br>)<br>products.register(<br>    methods=[&quot;LIST&quot;, &quot;GET&quot;, &quot;POST&quot;, &quot;PATCH&quot;, &quot;DELETE&quot;],<br>    oauth_protect=oauth2,<br>    protected_methods=[&quot;POST&quot;, &quot;PATCH&quot;, &quot;DELETE&quot;],<br>)<br><br># --- Orders ---<br>orders = AsyncBaseViewset(<br>    endpoint=&quot;/orders&quot;,<br>    model=Order,<br>    response_model=OrderSchema,<br>    db_session=get_async_session,<br>    tags=[&quot;Admin / Orders&quot;],<br>)<br>orders.register(<br>    methods=[&quot;LIST&quot;, &quot;GET&quot;, &quot;POST&quot;, &quot;PATCH&quot;, &quot;DELETE&quot;],<br>    oauth_protect=oauth2,<br>    protected_methods=[&quot;POST&quot;, &quot;PATCH&quot;, &quot;DELETE&quot;],<br>)</pre><blockquote>`oauth_protect` wires the `OAuth2PasswordBearer` dependency only to `protected_methods`. `GET /products` and `GET /products/{id}` stay public — perfect for a shop storefront.</blockquote><h4>Step 4 — Main app (`main.py`)</h4><pre>from fastapi import FastAPI<br>from fastapi_viewsets.db_conf import async_engine, Base<br><br>from routers import categories, products, orders<br><br>app = FastAPI(title=&quot;Shop Admin API&quot;)<br><br><br>@app.on_event(&quot;startup&quot;)<br>async def create_tables() -&gt; None:<br>    async with async_engine.begin() as conn:<br>        await conn.run_sync(Base.metadata.create_all)<br><br><br>app.include_router(categories)<br>app.include_router(products)<br>app.include_router(orders)</pre><p>Run it:</p><pre>uvicorn main:app --reload</pre><p>Open <a href="http://127.0.0.1:8000/docs">http://127.0.0.1:8000/docs</a> — you’ll see a fully populated Swagger UI with all 15 endpoints, grouped by tag, with request/response schemas inferred from your Pydantic models.</p><h4>Bonus: custom LIST with search and ordering</h4><p>The built-in `list` gives you `limit` / `offset` pagination out of the box. Need to search products by name and sort by price? Subclass and override `list` — no need to touch the other four methods:</p><pre>from typing import List, Optional<br>from sqlalchemy import select<br>from sqlalchemy.ext.asyncio import AsyncSession<br>from fastapi_viewsets import AsyncBaseViewset<br><br>from models import Product<br>from schemas import ProductSchema<br><br><br>class ProductsViewSet(AsyncBaseViewset):<br>    async def list(<br>        self,<br>        limit: int = 20,<br>        offset: int = 0,<br>        search: Optional[str] = None,<br>        order_by: str = &quot;name&quot;,<br>    ) -&gt; List[ProductSchema]:<br>        session: AsyncSession = self.db_session()<br>        try:<br>            stmt = select(self.model)<br><br>            if search:<br>                stmt = stmt.where(self.model.name.ilike(f&quot;%{search}%&quot;))<br><br>            column_map = {<br>                &quot;name&quot;: self.model.name,<br>                &quot;price&quot;: self.model.price,<br>                &quot;stock&quot;: self.model.stock,<br>            }<br>            col = column_map.get(order_by.lstrip(&quot;-&quot;))<br>            if col is not None:<br>                stmt = stmt.order_by(col.desc() if order_by.startswith(&quot;-&quot;) else col.asc())<br><br>            stmt = stmt.offset(offset).limit(limit)<br>            rows = (await session.execute(stmt)).scalars().all()<br>            return [ProductSchema.model_validate(row) for row in rows]<br>        finally:<br>            await session.close()<br><br><br>products = ProductsViewSet(<br>    endpoint=&quot;/products&quot;,<br>    model=Product,<br>    response_model=ProductSchema,<br>    db_session=get_async_session,<br>    tags=[&quot;Admin / Products&quot;],<br>)<br>products.register(<br>    methods=[&quot;LIST&quot;, &quot;GET&quot;, &quot;POST&quot;, &quot;PATCH&quot;, &quot;DELETE&quot;],<br>    oauth_protect=oauth2,<br>    protected_methods=[&quot;POST&quot;, &quot;PATCH&quot;, &quot;DELETE&quot;],<br>)</pre><p>`GET /products?search=apple&amp;order_by=-price&amp;limit=5` — search by name, sort by price descending, take top 5. FastAPI picks up the new query parameters automatically — no route redeclaration needed.</p><h4>Eager loading for nested schemas</h4><p>If `ProductSchema` included a nested `CategorySchema`, you’d normally hit an N+1 problem on `GET /products`. With `fastapi-viewsets` v1.3+ you fix it declaratively — just add an inner `RelatedConfig` to the schema:</p><pre>class ProductWithCategorySchema(BaseModel):<br>    model_config = ConfigDict(from_attributes=True)<br><br>    id: Optional[int] = None<br>    name: str<br>    price: Decimal<br>    category: Optional[CategorySchema] = None   # nested model<br><br>    class RelatedConfig:<br>        select_related = [&quot;category&quot;]   # → one JOIN, no extra queries</pre><p>Pass this as `response_model` to the viewset and `LIST` / `GET` will automatically apply `joinedload(“category”)` — zero extra configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GFtPC4ThQDz-wYhmvKZi8w.jpeg" /></figure><h4>Wrapping up</h4><p>`fastapi-viewsets` doesn’t hide FastAPI — it builds on top of `APIRouter`, so every familiar concept (dependencies, middleware, lifespan events) keeps working exactly as you’d expect. The viewset is just the boilerplate layer you shouldn’t have to write by hand every time.</p><p>The full source for this example is available on GitHub: [github.com/svalench/fastapi_viewsets](https://github.com/svalench/fastapi_viewsets).</p><p>If you found this useful, consider giving the repo a ⭐ — it helps other developers discover it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23d23bdcd6b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add Semantic Search + RAG to Any Django App in 5 Minutes (No Migrations)]]></title>
            <link>https://medium.com/@chitsalex/your-django-app-has-years-of-data-heres-how-to-make-ai-agents-actually-use-it-f6f68eb45b9c?source=rss-4bb1162eee89------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6f68eb45b9c</guid>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python-web-developer]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Alex]]></dc:creator>
            <pubDate>Fri, 05 Jun 2026 14:45:34 GMT</pubDate>
            <atom:updated>2026-06-08T07:54:27.498Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Your data is locked in relational tables. Here is the easiest way to feed it to an AI agent.</strong>You have a Django app with years of data — products, articles, orders, users. Your users type natural language queries into a search box and get either nothing or keyword-matched garbage.</h4><p>Worse: you want to connect an AI agent that can answer questions about this data. But everything is locked inside relational tables. To feed it to an LLM, you either dump the database, write custom ETL pipelines, or stand up a separate vector store and manually keep it in sync with your ORM.</p><p>I ran into exactly this problem. So I built a library that solves it with one config file.</p><h4>The Core Idea: Your ORM Graph as a Vector Source</h4><blockquote>django-graph-search doesn’t just vectorize individual model fields. It **traverses your ORM relation graph** and builds a rich document that captures the full context of an object.</blockquote><p>Take a simple `Product` model:</p><blockquote>Product(pk=42)<br>├── name: “Pixel 8”<br>├── description: “Camera-first Android phone with Tensor G3”<br>├── category → Category.name: “Smartphones” ← FK<br>├── tags → [Tag.name: “android”, “5G”, “camera”] ← M2M<br>└── brand → Brand.description: “Google hardware…” ← FK depth=2<br> └── country → Country.name: “USA” ← depth=2</blockquote><p>All of this gets merged into **one text document**, which is passed to the embedding model. The resulting vector is semantically rich — it carries information not just about the object itself, but about its entire relational context.</p><p>This is done by `GraphResolver`, which recursively walks `_meta.get_fields()`, handles FK, M2M, and reverse relations, and tracks cycles via a `visited` set.</p><h4>Zero Migrations. Zero Schema Changes.</h4><p>The most important part: all of this is added on top of your **existing** Django application. You don’t change models, don’t create new tables, don’t touch your views.</p><p>Everything lives in `settings.py`:</p><p>The most important part: all of this is added on top of your **existing** Django application. You don’t change models, don’t create new tables, don’t touch your views.</p><pre>INSTALLED_APPS = [<br> …,<br> &quot;django_graph_search&quot;,<br>]<br>GRAPH_SEARCH = {<br> &quot;MODELS&quot;: [<br> {<br> &quot;model&quot;: &quot;shop.Product&quot;,<br> &quot;fields&quot;: [&quot;name&quot;, &quot;description&quot;, &quot;category__name&quot;, &quot;tags__name&quot;],<br> &quot;follow_relations&quot;: True,<br> &quot;relation_depth&quot;: 2,<br> },<br> ],<br> &quot;VECTOR_STORE&quot;: {<br> &quot;BACKEND&quot;: &quot;django_graph_search.backends.ChromaDBBackend&quot;,<br> &quot;OPTIONS&quot;: {&quot;persist_directory&quot;: &quot;vector_db&quot;},<br> },<br> &quot;EMBEDDINGS&quot;: {<br> &quot;default&quot;: {<br> &quot;BACKEND&quot;: &quot;django_graph_search.embeddings.SentenceTransformerBackend&quot;,<br> # Multilingual - works with Russian, English, German, etc.<br> &quot;MODEL_NAME&quot;: &quot;sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2&quot;,<br> }<br> },<br> &quot;DELTA_INDEXING&quot;: True,<br>}</pre><p>One command and your vector index is built:</p><pre>python manage.py build_search_index</pre><p>Your Django app runs exactly as before. Data stays in PostgreSQL. Vectors live in ChromaDB alongside. `post_save` signals keep the index updated automatically whenever objects change.</p><h4>Control What Gets Vectorized</h4><p>Not everything in your database should end up in a vector. Technical fields like `slug`, `created_at`, internal admin notes — these are noise that degrades search quality. `weight_fields` gives you precise control:</p><pre>&quot;weight_fields&quot;: {<br>    &quot;title&quot;: 2.0,         # repeated twice — embedding &quot;remembers&quot; it more<br>    &quot;description&quot;: 1.0,   # standard weight<br>    &quot;internal_note&quot;: 0.0, # weight 0.0 = completely excluded from the vector<br>    &quot;slug&quot;: 0.0,<br>}</pre><p>This isn’t just filtering. Under the hood, the <em>GraphResolver._apply_weight()</em> method repeats text fragments in the document proportionally to their weight. A field with weight `2.0` appears twice in the concatenated string, shifting the embedding centroid toward that concept in vector space.</p><h4>RAG Over Django Data: The Real Pattern</h4><p>Now for the main point. Here’s how this connects to AI agents. The standard RAG pattern (Retrieval-Augmented Generation) requires: get user query → retrieve relevant context → pass to LLM. Normally “retrieve context” means separate infrastructure. With `django-graph-search`, it’s three lines:</p><pre>from django_graph_search import search<br><br>def build_llm_context(user_question: str) -&gt; str:<br>    results = search(<br>        user_question,<br>        models=[&quot;shop.Product&quot;, &quot;blog.Article&quot;],<br>        limit=5<br>    )<br>    # Each result contains &quot;text&quot; — the full indexed document<br>    # and &quot;score&quot; — cosine similarity from 0.0 to 1.0<br>    context = &quot;\n\n&quot;.join(<br>        r[&quot;text&quot;] for r in results if r[&quot;score&quot;] &gt; 0.7<br>    )<br>    return context<br><br># Pass context to the system prompt of any LLM</pre><p>Key detail: `<em>results[*][“text”]</em>` is not just `<em>str(instance)</em>`. It’s the full text document used to build the vector — with all related fields, all weights applied. The LLM receives <strong>rich, relational context</strong>, not just an object name.</p><h4>LangGraph Pipeline: Agents With Memory</h4><p>For more demanding use cases, the library ships an optional LangGraph pipeline. It adds:</p><p><strong>Query expansion — </strong>an LLM generates 2–3 semantic reformulations; search runs across all variants and merges results<br><strong>Reranking — </strong>top-K candidates are reordered by an LLM based on true relevance<br><strong>Streaming — </strong>clients see real-time progress via SSE or NDJSON</p><pre>GRAPH_SEARCH = {<br>    &quot;LANGGRAPH&quot;: {<br>        &quot;ENABLED&quot;: True,<br>        &quot;QUERY_EXPANSION&quot;: True,<br>        &quot;RERANKING&quot;: True,<br>        &quot;MAX_EXPANDED_QUERIES&quot;: 3,<br>        &quot;FALLBACK_ON_ERROR&quot;: True,  # if LLM fails, falls back to pure vector search<br>        &quot;LLM&quot;: {<br>            &quot;BACKEND&quot;: &quot;myapp.llm.OllamaBackend&quot;,  # plug in your own Ollama/vLLM/OpenAI<br>        },<br>    },<br>}</pre><blockquote>Important: `langgraph` is an **optional dependency**. If the package is not installed, the pipeline automatically falls back to a built-in `_FallbackGraph` with identical behavior. Your application code doesn’t change.</blockquote><p>The conversational endpoint adds stateful memory between requests:</p><blockquote>User: “show me smartphones under $500”<br>Agent: [returns list]<br>User: “only Samsung”<br>Agent: [understands previous context, interpreted_query = “Samsung smartphones under $500”]</blockquote><h4>The Path to Production — Same Config, Different Backend</h4><p>Migrating between vector backends is just changing one line:</p><blockquote>Dev: ChromaDB → local, no server, files on disk<br>Staging: FAISS → fast, CPU-only, everything in memory<br>Production: pgvector → if you already have PostgreSQL — no new server at all<br> Qdrant → if you need filtering and horizontal scaling</blockquote><p>Embedding models are swappable the same way: local <a href="https://pypi.org/project/sentence-transformers/"><em>sentence-transformers</em></a>, OpenAI, Cohere — all through <strong>EMBEDDINGS.BACKEND</strong>. Zero code changes.</p><h4>What This Really Is</h4><p><a href="https://pypi.org/project/django-graph-search/">django-graph-search</a> is not just another search library. It’s a <strong>vector layer on top of your existing Django ORM</strong> that:<br>1. Requires no database schema changes<br>2. Automatically builds rich documents by traversing model relations<br>3. Makes your application data available to AI agents via a standard RAG pattern<br>4. Scales from local ChromaDB to production Qdrant without refactoring</p><pre>pip install django-graph-search[chromadb]</pre><p>Your data is already there. It just needs a vector layer.</p><blockquote>GitHub: [svalench/django_graph_search](<a href="https://github.com/svalench/django_graph_search">https://github.com/svalench/django_graph_search</a>) · PyPI: [django-graph-search](<a href="https://pypi.org/project/django-graph-search/">https://pypi.org/project/django-graph-search/</a>)</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6f68eb45b9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Free AI Assistant for Car Diagnostics, for what?]]></title>
            <link>https://medium.com/@chitsalex/i-built-a-free-ai-assistant-for-car-diagnostics-for-what-164fed024114?source=rss-4bb1162eee89------2</link>
            <guid isPermaLink="false">https://medium.com/p/164fed024114</guid>
            <category><![CDATA[obd2]]></category>
            <category><![CDATA[cars]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Alex]]></dc:creator>
            <pubDate>Fri, 22 May 2026 14:02:18 GMT</pubDate>
            <atom:updated>2026-05-22T14:02:18.996Z</atom:updated>
            <content:encoded><![CDATA[<p><em>It started with a phone call from a friend.</em></p><p>He had spent hours trying to figure out what was wrong with his car. The OBD scanner gave him a code. Just a code. So he opened ChatGPT and started a conversation — copy-pasting the code, describing symptoms, answering follow-up questions, going back and forth, back and forth. It took way too long just to get a simple answer: what is broken and what should I do about it.</p><p>When he told me this story, something clicked. <em>Why doesn’t an app like this exist?</em> Not just a code reader. Not just a definition lookup. Something purpose-built for this exact moment — you’re standing next to your car, you have a code, and you need a real answer.</p><p>I thought about it for a day. Then I started building.</p><h3>Problem!</h3><p>Modern cars are computers on wheels. Since 1996, every car sold in the US and EU has an OBD2 port — a standardized diagnostic interface that can tell you exactly what’s happening inside your vehicle. The problem isn’t access to the data. The data is right there, 16 pins under your steering wheel.<br>The problem is understanding it.<br>The standard OBD2 protocol returns error codes like P0300 — “Random/Multiple Cylinder Misfire Detected.” That tells you something is wrong, but not why, not how urgent it is, and not what to do next. You need context, experience, and domain knowledge to translate raw codes into actionable decisions.<br>Professional scan tools solve this with proprietary databases and expert systems that cost much dollars. Free apps like Torque or AndrOBD do a great job reading raw data, but they stop short of actually explaining what it means for your specific situation.<br>My friend’s experience was the proof. He already had the code. He already had ChatGPT. All that was left was to provide context and wrap it all up with blue duct tape.</p><h3>Connecting AI to a diagnostic scanner</h3><p>Once you have the raw data — fault codes, PID codes, current sensor values — the next step is to make it useful. This is where the AI layer comes in.<br>The architecture is simple: the app reads data from the OBD2 adapter, sends the relevant codes and sensor context to the language model, and returns an explanation in simple language with specific next steps. There is no cloud dependency, and no subscription is required.<br>The key is the use of context-sensitive prompts. The source code means different things depending on:<br>· What other codes are present at the same time<br>· What the current sensor values look like (engine temperature, fuel level, O2)<br>· The make, model, and year of the vehicle<br>· Whether the code is periodic or constant<br>Using all this context in the model, rather than just the isolated code, significantly improves the quality of the explanation.</p><h3>IOS Chalange</h3><p>There’s also an IOS app in development! (I hope I’ll finish it in the next month or two). Of course, there are some fun swings, here they are.<br>Building the iOS version introduced a specific set of constraints that Android developers don’t face.<br>Apple’s Core Bluetooth framework doesn’t give apps raw access to Bluetooth Classic (BR/EDR) — which is what most ELM327 Bluetooth adapters use. This means iOS apps must either use BLE-based adapters (like the Vgate iCar Pro), WiFi-based adapters, or work around this via MFi accessories. This is a real compatibility wall for users with older ELM327 dongles.<br>The solution: focus on WiFi adapters and BLE-compatible dongles, and make the supported hardware list explicit and front-and-center in the UI. No surprises, no “why won’t it connect” frustration.</p><p><strong>What the App Actually Does</strong></p><ul><li><strong>Reads and clears DTCs</strong> — all modes (permanent, pending, confirmed), with AI-generated explanation for each code</li><li><strong>Live data dashboard</strong> — RPM, coolant temp, fuel trims, O2 sensors, MAF, throttle position and more</li><li><strong>AI diagnostic assistant</strong> — plain language analysis combining all active codes and live sensor context</li><li><strong>Offline capable</strong> — core diagnostic functions work without internet; AI explanation requires connectivity</li></ul><p>If you’re interested in trying it out, I’d be happy to help — <a href="https://aiscanauto.com/">https://aiscanauto.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=164fed024114" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Writing CRUD Boilerplate for FastAPI — Use ViewSets Instead]]></title>
            <link>https://medium.com/@chitsalex/stop-writing-crud-boilerplate-for-fastapi-use-viewsets-instead-9f456273414e?source=rss-4bb1162eee89------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f456273414e</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[python-web-developer]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Alex]]></dc:creator>
            <pubDate>Sun, 17 May 2026 20:32:30 GMT</pubDate>
            <atom:updated>2026-05-17T20:32:30.879Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re building REST APIs with FastAPI, you’ve probably written this code dozens of times: a router, a list endpoint, a get-by-id endpoint, a create, an update, a delete… and then you do it all over again for the next resource. And the next. And the next.</p><p>There’s a better way. Meet <strong>fastapi-viewsets</strong> — a library inspired by Django REST Framework’s ViewSets that lets you generate all six standard CRUD endpoints from a single class with one method call.</p><h3>The Problem: FastAPI CRUD Is Verbose by Design</h3><p>FastAPI is fantastic for building APIs. It’s fast, it’s type-safe, it generates OpenAPI docs automatically. But it’s deliberately low-level — it gives you routing primitives, not conventions. That means every resource you build looks roughly like this:</p><pre>from fastapi import APIRouter, Depends, HTTPException<br>from sqlalchemy.orm import Session<br>from typing import List<br><br>router = APIRouter()<br><br>@router.get(&quot;/items&quot;, response_model=List[ItemSchema])<br>def list_items(limit: int = 10, offset: int = 0, db: Session = Depends(get_db)):<br>    return db.query(Item).offset(offset).limit(limit).all()<br><br>@router.get(&quot;/items/{id}&quot;, response_model=ItemSchema)<br>def get_item(id: int, db: Session = Depends(get_db)):<br>    obj = db.query(Item).filter(Item.id == id).first()<br>    if not obj:<br>        raise HTTPException(status_code=404, detail=&quot;Not found&quot;)<br>    return obj<br><br>@router.post(&quot;/items&quot;, response_model=ItemSchema)<br>def create_item(item: ItemSchema, db: Session = Depends(get_db)):<br>    obj = Item(**item.dict())<br>    db.add(obj)<br>    db.commit()<br>    db.refresh(obj)<br>    return obj<br><br>@router.patch(&quot;/items/{id}&quot;, response_model=ItemSchema)<br>def update_item(id: int, item: ItemSchema, db: Session = Depends(get_db)):<br>    obj = db.query(Item).filter(Item.id == id).first()<br>    if not obj:<br>        raise HTTPException(status_code=404, detail=&quot;Not found&quot;)<br>    for key, value in item.dict(exclude_unset=True).items():<br>        setattr(obj, key, value)<br>    db.commit()<br>    db.refresh(obj)<br>    return obj<br><br>@router.delete(&quot;/items/{id}&quot;)<br>def delete_item(id: int, db: Session = Depends(get_db)):<br>    obj = db.query(Item).filter(Item.id == id).first()<br>    if not obj:<br>        raise HTTPException(status_code=404, detail=&quot;Not found&quot;)<br>    db.delete(obj)<br>    db.commit()<br>    return {&quot;status&quot;: &quot;ok&quot;}</pre><p>That&#39;s ~50 lines of nearly identical logic. And you&#39;ll write it again for users, orders, products, categories... You get the idea.</p><h3>The Solution: fastapi-viewsets</h3><p>fastapi-viewsets brings DRF-style ergonomics to FastAPI. Instead of repeating yourself, you declare one class, call .register(), and all the endpoints are wired up automatically — complete with Pydantic validation, OpenAPI docs, and proper HTTP semantics.</p><p>Here&#39;s the same resource from above, rewritten with the library:</p><pre>from fastapi import FastAPI<br>from pydantic import BaseModel, ConfigDict<br>from sqlalchemy import Column, Integer, String<br><br>from fastapi_viewsets import BaseViewset<br>from fastapi_viewsets.db_conf import Base, engine, get_session<br><br>app = FastAPI()<br><br>class Item(Base):<br>    __tablename__ = &quot;items&quot;<br>    id = Column(Integer, primary_key=True)<br>    name = Column(String(255), nullable=False)<br><br>class ItemSchema(BaseModel):<br>    model_config = ConfigDict(from_attributes=True)<br>    id: int | None = None<br>    name: str<br><br>Base.metadata.create_all(bind=engine)<br><br>items = BaseViewset(<br>    endpoint=&quot;/items&quot;,<br>    model=Item,<br>    response_model=ItemSchema,<br>    db_session=get_session,<br>    tags=[&quot;items&quot;]<br>)<br>items.register(methods=[&quot;LIST&quot;, &quot;GET&quot;, &quot;POST&quot;, &quot;PATCH&quot;, &quot;DELETE&quot;])<br>app.include_router(items)</pre><p>That&#39;s it. <strong>~20 lines instead of ~50, and you get the same 5 endpoints.</strong> The more resources you have, the more time you save.</p><h3>What Gets Generated</h3><p>A single .register() call produces these routes (using LIST, GET, POST, PATCH, DELETE):</p><p>MethodPathDescriptionGET/itemsList all items (paginated)GET/items/{id}Get single item by IDPOST/itemsCreate a new itemPATCH/items/{id}Partial update (only provided fields)PUT/items/{id}Full replacementDELETE/items/{id}Delete by ID</p><p>Built-in <strong>pagination</strong> is included on the LIST endpoint via limit and offset query parameters — no extra code needed:</p><pre>GET /items?limit=20&amp;offset=40</pre><h3>Custom Logic: Just Subclass</h3><p>BaseViewset is an APIRouter under the hood, so you can extend it just like any Python class. Override any handler method to add custom business logic:</p><pre>class ItemsWithStats(BaseViewset):<br>    def __init__(self, *args, **kwargs):<br>        super().__init__(*args, **kwargs)<br>        # Add custom routes BEFORE register() to avoid path conflicts<br>        self.add_api_route(<br>            f&quot;{self.endpoint}/stats&quot;,<br>            self.collection_stats,<br>            methods=[&quot;GET&quot;],<br>            tags=self.tags or [],<br>        )<br><br>    def collection_stats(self) -&gt; dict:<br>        return {&quot;resource&quot;: self.endpoint.strip(&quot;/&quot;)}<br><br>    def list(self, limit=10, offset=0, search=None, token=None):<br>        # Add custom filtering logic here<br>        return super().list(limit=limit, offset=offset)</pre><p>You’re not locked into the generated behavior — it’s a starting point, not a cage.</p><h3>Try It</h3><p>The library is open source under the MIT license. If it saves you time, a ⭐ on GitHub goes a long way!</p><ul><li>📦 <strong>PyPI</strong>: <a href="https://pypi.org/project/fastapi-viewsets/">https://pypi.org/project/fastapi-viewsets/</a></li><li>🐙 <strong>GitHub</strong>: <a href="https://github.com/svalench/fastapi_viewsets">https://github.com/svalench/fastapi_viewsets</a></li></ul><p>Stop writing the same CRUD code over and over. Your future self will thank you.</p><p><em>Built by Alexander Valenchits .</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f456273414e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>