<?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 Ck Chris Kechagias on Medium]]></title>
        <description><![CDATA[Stories by Ck Chris Kechagias on Medium]]></description>
        <link>https://medium.com/@ck.chris.kechagias?source=rss-898ab7ac3003------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZcUGJ6RhEDf3tLBODw5tlQ.jpeg</url>
            <title>Stories by Ck Chris Kechagias on Medium</title>
            <link>https://medium.com/@ck.chris.kechagias?source=rss-898ab7ac3003------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 07:17:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ck.chris.kechagias/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[Building a Chatbot API From Scratch -Part 3: UUID Migration, Product Search, and Tests That Caught…]]></title>
            <link>https://python.plainenglish.io/building-a-chatbot-api-from-scratch-part-3-uuid-migration-product-search-and-tests-that-caught-9d2df26b94f2?source=rss-898ab7ac3003------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d2df26b94f2</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ck Chris Kechagias]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 21:03:18 GMT</pubDate>
            <atom:updated>2026-05-05T06:11:01.201Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Chatbot API From Scratch -Part 3: UUID Migration, Product Search, and Tests That Caught a Real Bug</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6L21PXmIlxPZg6au.png" /></figure><p>Two months in, both APIs are running. Before RAG touches either of them, I needed to fix decisions I’d been living with since day one.</p><p>The retail API had integer primary keys. The chatbot had no tests. Both needed to change before I bolted anything else on.</p><p>Five PRs across two repos. One Alembic migration I was genuinely nervous about. A test suite that found a bug I didn’t know existed.</p><h3>UUID primary keys on the retail API</h3><p>The retail API launched with auto-incrementing integers for product and variant IDs. They work. They’re also predictable — a scraper can enumerate your entire catalog by counting up from 1.</p><p>More importantly: integers don’t compose well when you’re building a RAG pipeline where embeddings need stable, unique identifiers across multiple services. id=42 is not what you want there. id=550e8400-e29b-41d4-a716-446655440000 is.</p><p>So I migrated.</p><h3>The model change</h3><p>SQLModel makes the declaration straightforward:</p><pre>from uuid import UUID, uuid4<br>from sqlmodel import Field<br><br>id: UUID = Field(default_factory=uuid4, primary_key=True)</pre><p>default_factory=uuid4 means every new product gets a UUID generated by Python. No sequence, no extra database round-trip.</p><p>Variants were trickier. The product_id foreign key needs to store a UUID and tell SQLAlchemy to use PostgreSQL&#39;s native UUID type:</p><pre>from uuid import UUID, uuid4<br>from sqlalchemy import Column, ForeignKey<br>from sqlalchemy.dialects.postgresql import UUID as PGUUID<br><br>product_id: UUID = Field(<br>    sa_column=Column(<br>        PGUUID(as_uuid=True),<br>        ForeignKey(&quot;product.id&quot;, ondelete=&quot;CASCADE&quot;),<br>        nullable=False,<br>    )<br>)</pre><p>as_uuid=True tells SQLAlchemy to return Python UUID objects, not raw strings. Skip that and you&#39;ll spend 20 minutes confused about why comparisons fail.</p><h3>The migration</h3><p>The model change is two lines. The Alembic migration is where it gets real.</p><p>You can’t drop the integer column and add a UUID one.There’s existing data, and the variant table has a foreign key pointing at the product table. The migration has to be surgical.</p><p>Eight steps:</p><ol><li>Add id_new UUID to product with gen_random_uuid() as server default</li><li>Add product_id_new UUID to product_variant</li><li>Assign SKUs via ROW_NUMBER() OVER (PARTITION BY category) while we&#39;re already in there</li><li>Link variant UUIDs to their products via a join</li><li>Drop the FK constraint on product_variant.product_id</li><li>Drop the old integer columns on both tables</li><li>Rename the new columns, recreate PK and FK constraints</li><li>Add unique constraint on sku</li></ol><p>The downgrade() raises NotImplementedError. This migration is one-way.</p><pre>def downgrade() -&gt; None:<br>    raise NotImplementedError(&quot;UUID migration is irreversible.&quot;)</pre><p>I’ve seen empty downgrade functions. That’s worse! It runs silently and does nothing, which means you think you rolled back when you haven’t. An explicit error is honest.</p><h3>SKU generation</h3><p>Every product now gets a SKU on creation. Format: two-letter category prefix plus four-digit sequential count within that category.</p><p>TS-0001. SW-0003. Seven characters max.</p><p>The prefix map lives in utils/sku.py:</p><pre>CATEGORY_PREFIX: dict[Category, str] = {<br>    Category.TEES: &quot;TS&quot;,<br>    Category.SWEATERS: &quot;SW&quot;,<br>    Category.SHIRTS: &quot;ST&quot;,<br>    Category.PANTS: &quot;PT&quot;,<br>    Category.SHORTS: &quot;SH&quot;,<br>    Category.TANK_TOPS: &quot;TT&quot;,<br>    Category.OTHER: &quot;OR&quot;,<br>}<br><br>def generate_sku(category: Category, count: int) -&gt; str:<br>    prefix = CATEGORY_PREFIX[category]<br>    return f&quot;{prefix}-{count:04d}&quot;</pre><p>The controller counts existing products in that category and passes the next number:</p><pre>category_count = session.exec(<br>    select(func.count()).where(Product.category == product.category)<br>).one()<br>sku = generate_sku(product.category, category_count + 1)<br>db_product = Product.model_validate(product, update={&quot;sku&quot;: sku})</pre><p>.one() on a COUNT query always returns exactly one row. That&#39;s why it&#39;s .one() and not .first().</p><p>One thing to catch: max_length=7 on the SKU field. TS-0001 is 7 characters. I had it set to 10 initially and only caught it during review.</p><h3>Product search</h3><p>One endpoint. One query parameter. Two behaviours.</p><p>GET /products/search?q=TS-0001 should return an exact match. GET /products/search?q=blue tee should return everything with that phrase in the name. Same URL, different logic based on what the query looks like.</p><pre>def looks_like_sku(q: str) -&gt; bool:<br>    return bool(re.match(r&#39;^[A-Za-z]{2}-\d{4}$&#39;, q.strip()))<br><br>def search_products_controller(q: str, session: SessionDep):<br>    if looks_like_sku(q):<br>        product = session.exec(<br>            select(Product).where(Product.sku == q.upper())<br>        ).first()<br>        return [product] if product else []<br>    else:<br>        statement = select(Product).where(Product.name.ilike(f&quot;%{q}%&quot;))<br>        return session.exec(statement).all()</pre><p>Always returns a list. The router signature is list[Product] regardless of which branch ran. Returning a single object from a list endpoint causes a ResponseValidationError. I found this out from a 500.</p><p>The route goes above /{product_id} in the router file. FastAPI matches routes top-to-bottom. If /{product_id} comes first, /search gets matched as a product ID and FastAPI tries to cast the string &quot;search&quot; to a UUID. You get a 422. I found this out from a 422.</p><p>The long-term plan: ilike becomes semantic search when ChromaDB is wired in. Same endpoint, smarter backend. This PR is the foundation.</p><h3>Chatbot tests</h3><p>Part 2 shipped streaming, composable prompts, and Docker. The chatbot had no tests.</p><p>Fine when you’re moving fast. Until you want to add RAG on top of it, at which point you really want to know the foundation holds.</p><h3>The setup</h3><p>Same pattern as the retail API: SQLite in-memory, dependency override, lifespan override.</p><pre>engine = create_engine(<br>    &quot;sqlite://&quot;,<br>    connect_args={&quot;check_same_thread&quot;: False},<br>    poolclass=StaticPool,<br>)<br><br>@pytest.fixture(name=&quot;client&quot;)<br>def client_fixture(session):<br>    app.dependency_overrides[get_session] = lambda: session<br>    app.router.lifespan_context = lifespan_override<br>    with TestClient(app) as client:<br>        yield client<br>    app.dependency_overrides.clear()</pre><p>One gotcha: without pythonpath = [&quot;.&quot;] in pyproject.toml, VS Code&#39;s test runner breaks on import. It overrides PYTHONPATH and relative imports stop resolving. The fix is one line in config, but it costs you a debugging session to find it.</p><h3>Mocking the stream</h3><p>The chat endpoints return StreamingResponse. TestClient handles that, it collects the full stream and gives you the response body. The OpenAI call still needs mocking.</p><p>The streaming function is an async generator, so the mock has to be too:</p><pre>async def mock_streaming_response():<br>    chunks = [<br>        MagicMock(choices=[MagicMock(delta=MagicMock(content=&quot;Hello&quot;))], usage=None),<br>        MagicMock(choices=[MagicMock(delta=MagicMock(content=&quot; world&quot;))], usage=None),<br>        MagicMock(choices=[], usage=MagicMock(total_tokens=10)),<br>    ]<br>    for chunk in chunks:<br>        yield chunk</pre><p>Then patch it:</p><pre>@patch(<br>    &quot;app.controllers.chat.get_chat_completion_stream&quot;,<br>    return_value=mock_streaming_response()<br>)<br>def test_create_chat_success(mock_stream, client):<br>    ...</pre><p>One thing that burned me: using MagicMock for async functions. get_chat_completion and generate_conversation_title are both async def, so they need AsyncMock:</p><pre>@patch(&quot;app.services.summarizer.get_chat_completion&quot;, new_callable=AsyncMock)</pre><p>MagicMock on an async function returns a coroutine object instead of the value. The test passes but asserts against the wrong thing. Silent failure, the worst kind.</p><p>The summarizer tests use side_effect to simulate the nano model failing and the mini model picking it up:</p><pre>mock_get_completion.side_effect = [<br>    OpenAIServiceException(...),  # nano fails<br>    MagicMock(content=&quot;Summary text&quot;),  # mini succeeds<br>]</pre><h3>What the tests actually caught</h3><p>While writing the streaming tests, I noticed POST /chat/ had status_code=status.HTTP_201_CREATED on the router decorator.</p><p>But StreamingResponse ignores the decorator&#39;s status code. It always returns 200. The 201 was a lie.</p><p>Fixed to status_code=status.HTTP_200_OK. Small thing. But clients checking status codes would have gotten 200 and assumed it was wrong.</p><p>Tests found it. Code review didn’t.</p><p>Final count: 10 tests on the chat endpoints, 3 on the token utility, 6 on the summarizer background tasks.</p><h3>The formatting rule</h3><p>The composable prompt system from Part 2 earned its keep here.</p><p>Testing the chatbot on Telegram, responses came back with markdown <strong>bold text</strong>, bullet points with asterisks, full headers. Fine in a web UI. Ugly in a messaging app where asterisks are just asterisks.</p><p>The fix: one new file, prompts/rules/formatting.md:</p><pre>Do not use markdown formatting unless explicitly asked. <br>No headers, no bullet points, no numbered lists, no bold text. <br>Write in plain prose only. <br>Keep responses concise - this is a messaging interface, not a document.</pre><p>And one line in prompts.yaml:</p><pre>stoic:<br>  rules: [communication, factuality, formatting]</pre><p>A new markdown file and a YAML entry. That’s the whole change.</p><p>That’s exactly what the prompt system was designed for.</p><h3>What’s next</h3><p>Both APIs are solid. UUID keys, human-readable SKUs, search endpoints, proper test coverage, a chatbot that doesn’t spam markdown at Telegram.</p><p>RAG is next. ChromaDB for the retail API, semantic search replacing ilike, product embeddings generated on creation. The search endpoint is already wired, it just needs a smarter backend.</p><p>The repo is public: <a href="https://github.com/chris-kechagias/simple-chatbot-api">GitHub</a></p><p>Follow the journey: <a href="https://www.linkedin.com/in/chkechagias">LinkedIn</a> | <a href="https://dev.to/kris_k">Dev.to</a></p><p>Built PR by PR. Mistakes included.</p><p><em>Originally published at </em><a href="https://dev.to/kris_k/building-a-chatbot-api-from-scratch-part-3-uuid-migration-product-search-and-tests-that-caught-3c3o"><em>https://dev.to</em></a><em> on April 28, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d2df26b94f2" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/building-a-chatbot-api-from-scratch-part-3-uuid-migration-product-search-and-tests-that-caught-9d2df26b94f2">Building a Chatbot API From Scratch -Part 3: UUID Migration, Product Search, and Tests That Caught…</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Chatbot API From Scratch — Part 2: Streaming, Prompt Engineering and Docker]]></title>
            <link>https://python.plainenglish.io/building-a-chatbot-api-from-scratch-part-2-streaming-prompt-engineering-and-docker-0bbf89874ce0?source=rss-898ab7ac3003------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bbf89874ce0</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Ck Chris Kechagias]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 05:55:46 GMT</pubDate>
            <atom:updated>2026-04-13T06:06:01.349Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WNtvg3Ab9ejUUtG9.png" /></figure><p>Part 4 actually of building a retail inventory API and then giving it a brain.</p><p>In <a href="https://medium.com/@ck.chris.kechagias/building-a-chatbot-api-from-scratch-13-prs-a-lot-of-broken-things-and-a-context-window-that-d2ac7c9f3b25"><strong>Part 3</strong></a> I built the chatbot foundation: FastAPI, PostgreSQL, conversation memory, context trimming, rolling summarization, and 13 PRs worth of broken things. The API worked. It remembered what you said. It didn’t fall over when the context got too long.</p><p>That was enough to call it functional. But it didn’t feel finished. No streaming. No real identity. No way to run it anywhere except my machine.</p><p>Five PRs later, all of that changed. Some of it was clean. Some of it was not.</p><h3>PR 14 — Auto-Title Generation</h3><p>Small PR. Big quality-of-life improvement.</p><p>Every new conversation started with the title &quot;New Chat...&quot; and stayed that way forever. I wanted it to generate automatically from the first message, without blocking the response.</p><p>The approach: fire a background task after the conversation is created.</p><pre>if not request.title: &quot;&quot;<br>    asyncio.create_task(<br>        update_conversation_title(engine, conversation.id, request.user_message)</pre><p>asyncio.create_task() schedules it and moves on. The 201 Created fires immediately. The title shows up a second or two later. Clean.</p><p>But before I got there, I spent an embarrassing amount of time debugging. The first version of generate_conversation_title was calling the main model ( gpt-5-mini) and getting back empty responses. Latency was around 22 seconds. 22 seconds for a title.</p><p>The problem was max_completion_tokens. I had it set to 1000 which is too low for reasoning models (they need token budget to think before responding). But even after bumping it, the main model was overkill for something this simple.</p><p>The fix was a dual model setup. A utility model ( gpt-5-nano) for cheap background tasks, and the main model only for actual chat. After the switch, latency dropped from 22 seconds to under 2. While testing the fix I noticed OpenAI had released gpt-5.4-mini and gpt-5.4-nano in March 2026, so I bumped both models while I was in there. 3x faster, same quality.</p><pre>latency_ms: 4527  # gpt-5-mini<br>latency_ms: 1418  # gpt-5.4-mini</pre><p>The background task lives in summarizer.py and uses that utility model:</p><pre>async def update_conversation_title(engine, conversation_id, user_message: str):<br>    &quot;&quot;&quot;Background task to generate and set a title for a newly created conversation.&quot;&quot;&quot;<br>    try:<br>        with Session(engine) as session:<br>            conv = session.get(Conversation, conversation_id)<br>            if not conv:<br>                return<br>            title = await generate_conversation_title(user_message)<br>            if title: &quot;&quot;<br>                conv.title = title<br>                session.add(conv)<br>                session.commit()<br>                logger.info(f&quot;Title updated for {conversation_id}: {title}&quot;)<br>    except Exception as e:<br>        logger.error(f&quot;Title generation failed: {e}&quot;)</pre><p>Two lessons that burned me:</p><p><strong>Background tasks need their own DB session.</strong> You can’t pass the request session in (it gets closed before the task runs). Always create a fresh Session(engine) inside the background function.</p><p><strong>@handle_openai_errors cannot be used on background tasks.</strong> The decorator wraps exceptions into HTTP responses, which makes no sense in a fire-and-forget context. Plain try/except is the right pattern.</p><h3>PR 15 — Streaming (SSE)</h3><p>This one took the most time.</p><p>The goal was to replace the blocking endpoint (wait for the full response, return it) with a streaming one. Tokens arrive at the client as they’re generated, using Server-Sent Events.</p><h3>The Service Layer</h3><p>The streaming function is an async generator. This is where the first real problem appeared.</p><p>I tried to decorate it with @handle_openai_errors like everything else:</p><pre>@handle_openai_errors  # THIS BREAKS IT<br>async def get_chat_completion_stream(...):<br>    ...<br>    async for chunk in response:<br>        yield chunk</pre><p>The decorator wraps the function with return await func(...). But func is an async generator - you can&#39;t await a generator. It returns a generator object, not a coroutine. The error:</p><pre>object async_generator can&#39;t be used in &#39;await&#39; expression</pre><p>The fix: remove the decorator entirely and handle errors inline.</p><pre>async def get_chat_completion_stream(<br>    messages: list[dict], model: str | None = None, max_retries: int = 2<br>):<br>    &quot;&quot;&quot;Streams a chat completion response from the OpenAI API.&quot;&quot;&quot;<br>    model = model or config.openai_model<br><br>    for attempt in range(max_retries + 1):<br>        try:<br>            response = await client.chat.completions.create(<br>                model=model,<br>                messages=messages,<br>                stream=True,<br>                stream_options={&quot;include_usage&quot;: True},<br>                max_completion_tokens=config.openai_max_completion_tokens,<br>            )<br>            async for chunk in response:<br>                yield chunk<br>            return<br><br>        except (openai.APIError, openai.APITimeoutError) as e:<br>            if attempt &lt; max_retries:<br>                wait_time = (attempt + 1) * 2<br>                await asyncio.sleep(wait_time)<br>                continue<br>            raise OpenAIServiceException(<br>                message=f&quot;OpenAI stream error: {str(e)}&quot;,<br>                status_code=getattr(e, &quot;status_code&quot;, 502),<br>                error_code=&quot;OPENAI_STREAM_ERROR&quot;,<br>            )</pre><p>Note the stream_options={&quot;include_usage&quot;: True}. This tells OpenAI to include token usage in the final chunk, so you don&#39;t need tiktoken on the streaming path.</p><p>The final chunk has chunk.choices == [] and chunk.usage populated:</p><pre>async for chunk in get_chat_completion_stream(trimmed_messages):<br>    if chunk.choices and chunk.choices[0].delta.content:<br>        delta = chunk.choices[0].delta.content<br>        full_content += delta<br>        yield f&quot;data: {json.dumps({&#39;content&#39;: delta})}\n\n&quot;<br><br>    if chunk.usage:<br>        metadata = {<br>            &quot;model&quot;: chunk.model,<br>            &quot;tokens&quot;: chunk.usage.total_tokens,<br>        }</pre><h3>The Controller</h3><p>The controller returns a StreamingResponse wrapping an async generator. DB writes happen after the stream completes (never during).</p><pre>async def stream_generator():<br>    full_content = &quot;&quot;<br>    metadata = {}<br>    start_time = time.perf_counter()<br><br>    try:<br>        async for chunk in get_chat_completion_stream(trimmed_messages):<br>            if chunk.choices and chunk.choices[0].delta.content:<br>                delta = chunk.choices[0].delta.content<br>                full_content += delta<br>                yield f&quot;data: {json.dumps({&#39;content&#39;: delta})}\n\n&quot;<br>            if chunk.usage:<br>                metadata = {&quot;model&quot;: chunk.model, &quot;tokens&quot;: chunk.usage.total_tokens}<br><br>        # Stream done — now persist<br>        latency_ms = (time.perf_counter() - start_time) * 1000<br>        new_msg = Message(<br>            conversation_id=conversation.id,<br>            user_message=request.user_message,<br>            ai_response=full_content,<br>            ai_model=metadata.get(&quot;model&quot;, config.openai_model),<br>            tokens_used=metadata.get(&quot;tokens&quot;, 0),<br>            latency_ms=latency_ms,<br>        )<br>        db.add(new_msg)<br>        db.commit()<br><br>        yield &quot;data: [DONE]\n\n&quot;<br><br>    except Exception as e:<br>        logger.error(f&quot;Mid-stream failure: {e}&quot;)<br>        yield f&quot;data: {json.dumps({&#39;error&#39;: &#39;Stream interrupted&#39;})}\n\n&quot;<br><br>return StreamingResponse(stream_generator(), media_type=&quot;text/event-stream&quot;)</pre><p>Use time.perf_counter() for latency, not time.time(). It&#39;s higher resolution and not affected by system clock changes.</p><p>To verify streaming is actually working (not just dumping everything at once):</p><pre>curl -N -X POST http://localhost:8000/chat/ \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;user_id&quot;: &quot;your-uuid&quot;, &quot;user_message&quot;: &quot;Tell me a short story&quot;}&#39;<br></pre><p>The -N flag disables buffering. If it works, you&#39;ll see chunks appear one by one in the terminal.</p><h3>PR 16 — Composable Prompt System</h3><p>This is the one I’m most proud of.</p><p>The system prompt was hardcoded in config. One string. Not flexible, not maintainable, and impossible to tune without touching code. I wanted something I could compose and experiment with.</p><h3>The Architecture</h3><p>The idea: YAML as a control layer, markdown files as the actual content. Each prompt is assembled at request time by layering components in a fixed order:</p><pre>base → core → styles → rules → intensity</pre><p>The folder structure:</p><pre>prompts/<br>├── prompts.yaml          # which components each prompt uses<br>├── base/                 # the foundation (default, concise, tutor...)<br>├── core/                 # identity and persona<br>├── styles/               # tone modifiers (casual, formal, sarcastic)<br>├── rules/                # behavioral constraints (communication, factuality...)<br>└── intensity/            # tone calibration (low, medium, high)</pre><p>The YAML defines each named prompt:</p><pre>stoic:<br>  base: base/default.md<br>  core: [identity, persona]<br>  rules: [communication, factuality]<br>  intensity: medium<br><br>summarizer:<br>  base: base/summarizer.md<br>  core: [identity]<br>  rules: [suppression, factuality]<br>  intensity: high</pre><h3>The PromptLoader</h3><p>The loader reads everything at startup and caches it in memory. No file I/O on every request.</p><pre>class PromptLoader:<br>    def __init__(self):<br>        self.base_path = Path(__file__).resolve().parent.parent.parent / &quot;prompts&quot;<br><br>        with open(self.base_path / &quot;prompts.yaml&quot;, &quot;r&quot;) as f:<br>            self.config = yaml.safe_load(f)<br><br>        self.cache = {}<br>        self._preload_files()<br><br>    def _preload_files(self):<br>        for folder in [&quot;base&quot;, &quot;core&quot;, &quot;rules&quot;, &quot;styles&quot;, &quot;intensity&quot;]:<br>            dir_path = self.base_path / folder<br>            if not dir_path.exists():<br>                continue<br>            for file in dir_path.glob(&quot;*.md&quot;):<br>                key = f&quot;{folder}/{file.stem}&quot;<br>                self.cache[key] = file.read_text().strip()<br><br>    def build(self, name: str, intensity_override: str | None = None, **kwargs) -&gt; str:<br>        cfg = self.config[name]<br>        parts = []<br><br>        base_name = Path(cfg[&quot;base&quot;]).stem<br>        parts.append(self._get(f&quot;base/{base_name}&quot;))<br><br>        for section in [&quot;core&quot;, &quot;styles&quot;, &quot;rules&quot;]:<br>            for item in cfg.get(section, []):<br>                parts.append(self._get(f&quot;{section}/{item}&quot;))<br><br>        intensity = intensity_override or cfg.get(&quot;intensity&quot;, &quot;medium&quot;)<br>        parts.append(self._get(f&quot;intensity/{intensity}&quot;))<br><br>        prompt = &quot;\n\n&quot;.join(p for p in parts if p)<br>        return prompt.format(**kwargs)</pre><p>The **kwargs handles variable injection. The summarizer prompt has {input} and {existing_summary} placeholders:</p><pre>prompt = loader.build(<br>    &quot;summarizer&quot;,<br>    input=new_content,<br>    existing_summary=conv.summary or &quot;No previous summary.&quot;,<br>)</pre><p>One thing to watch: any { or } in a markdown prompt file that isn&#39;t a variable placeholder will break prompt.format(**kwargs) with a KeyError. Avoid curly braces in prompt content unless they&#39;re intentional variables.</p><h3>The Persona</h3><p>The identity prompt is the philosophical foundation of the whole thing. This is what I actually care about:</p><blockquote>The assistant exists to sharpen thinking, not replace it.<em><br></em>It does not comfort. It does not flatter. It does not fill silence with noise.<em><br></em>When a question is asked, it answers. When a problem is presented, it cuts to what matters. When thinking is lazy or circular, it names that — once, directly, without judgment.<em><br></em>The goal is not to be helpful in the way a tool is helpful. The goal is to leave the person thinking more clearly than they arrived.</blockquote><p>The chat endpoint now accepts a prompt_key field. Omit it and it defaults to &quot;stoic&quot;. Every conversation persists the prompt key so it stays consistent across messages.</p><pre>{<br>  &quot;user_id&quot;: &quot;...&quot;,<br>  &quot;user_message&quot;: &quot;What is RAG?&quot;,<br>  &quot;prompt_key&quot;: &quot;tutor&quot;<br>}</pre><p>The prompt library lives outside app/ as a standalone content layer. It&#39;s not application code - it&#39;s configuration. Same reasoning as why tests live outside app/.</p><h3>PR 17 — Post-Feature Cleanup</h3><p>After three feature PRs, the codebase had accumulated some debt:</p><ul><li>chat_controller was still in the file (fully functional, no longer routed anywhere)</li><li>Three separate PromptLoader() instances across different files</li><li>Missing docstrings on PromptLoader, build(), stream_generator()</li><li>No success logging on the streaming path</li></ul><p>The singleton fix: export one shared instance from prompt_loader.py and import it everywhere.</p><pre># prompt_loader.py — bottom of file<br>loader = PromptLoader()<br><br># everywhere else<br>from .prompt_loader import loader</pre><p>Same pattern as client = AsyncOpenAI(...) in the OpenAI service. One instance, loaded once at startup.</p><p>Cleanup PRs don’t feel exciting but they’re the difference between a codebase you’re proud of and one you’re embarrassed to show.</p><h3>PR 18 — Containerization</h3><p>Dockerfile is deliberately minimal:</p><pre>FROM python:3.11-slim<br><br>WORKDIR /app<br><br>COPY pyproject.toml .<br>COPY uv.lock .<br><br>RUN pip install uv<br>RUN uv sync --frozen --no-dev<br><br>COPY . .<br><br>EXPOSE 8000<br><br>CMD [&quot;.venv/bin/uvicorn&quot;, &quot;main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><p>uv sync --frozen --no-dev is the important part - reproducible install, no dev dependencies in the image.</p><p>The docker-compose.yml spins up the API and a PostgreSQL 15 container, with a health check on the DB before the API starts:</p><pre>depends_on:<br>  db:<br>    condition: service_healthy</pre><p>Without condition: service_healthy, the API container starts before Postgres is ready and crashes. Learned this the first time.</p><p>The .dockerignore uses a whitelist approach (deny everything, explicitly allow what&#39;s needed):</p><pre>*<br><br>!pyproject.toml<br>!uv.lock<br>!main.py<br>!app/<br>!prompts/</pre><p>The !prompts/ line is easy to miss. The prompt library lives outside app/, so without it the container starts with an empty cache and every loader.build() call returns an empty string. No crash, no error, just silently wrong behavior.</p><p>All Docker commands are wired into taskipy:</p><pre>task build    # docker compose up --build -d<br>task start    # docker compose up -d<br>task stop     # docker compose down<br>task logs     # docker compose logs -f</pre><h3>What’s Next</h3><p>Phase 2 is complete. The API streams responses, has a composable identity, runs in Docker, and manages context intelligently.</p><p>Phase 3 starts with a Telegram bot as a real frontend (no more Swagger UI demos). It’ll live in a separate repo, store a per-user OpenAI key, and talk to this API over HTTP. After that: testing, then RAG.</p><p><em>The repo is public: </em><a href="https://github.com/chris-kechagias/simple-chatbot-api"><em>GitHub</em></a></p><p><em>Follow the journey: </em><a href="https://www.linkedin.com/in/chkechagias"><em>LinkedIn</em></a><em> | </em><a href="https://dev.to/kris_k"><em>D</em>ev.to</a></p><p><em>Built PR by PR. Mistakes included.</em></p><p><em>Originally published at </em><a href="https://dev.to/kris_k/building-a-chatbot-api-from-scratch-part-2-streaming-prompt-engineering-and-docker-3cn4"><em>https://dev.to</em></a><em> on April 6, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bbf89874ce0" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/building-a-chatbot-api-from-scratch-part-2-streaming-prompt-engineering-and-docker-0bbf89874ce0">Building a Chatbot API From Scratch — Part 2: Streaming, Prompt Engineering and Docker</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Chatbot API From Scratch: 13 PRs, a Lot of Broken Things, and a Context Window That…]]></title>
            <link>https://python.plainenglish.io/building-a-chatbot-api-from-scratch-13-prs-a-lot-of-broken-things-and-a-context-window-that-d2ac7c9f3b25?source=rss-898ab7ac3003------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2ac7c9f3b25</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Ck Chris Kechagias]]></dc:creator>
            <pubDate>Sat, 28 Mar 2026 12:13:12 GMT</pubDate>
            <atom:updated>2026-04-05T19:18:31.107Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Chatbot API From Scratch: 13 PRs, a Lot of Broken Things, and a Context Window That Actually Works</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JAwOwuCtg_HTqrVa.png" /></figure><p>Part 3 of building a retail inventory API and then giving it a brain.</p><p>In <a href="https://dev.to/kris_k/why-i-rebuilt-my-first-api-from-scratch-p63">Part 1</a> I explained why I archived my first API and started over. In <a href="https://dev.to/kris_k/restructuring-a-fastapi-project-migrating-to-supabase-and-hitting-97-test-coverage-59eb">Part 2</a> I restructured it properly, migrated to Supabase, and got to 97% test coverage.</p><p>The retail API is solid now. Working in production. Tests passing. Architecture I can explain.</p><p>So I started the next thing: a chatbot API. Same stack, new layer. The goal: a conversational AI service that remembers what you said, manages long conversations intelligently, and eventually connects to the retail inventory data.</p><p>This is what the last few weeks looked like.</p><h3>Why Build the API at All</h3><p>I could use a ready-made chatbot SDK. Drop in a library, wrap the OpenAI call, done in an afternoon.</p><p>The problem is the same one I had with the retail API the first time. I could make it work without understanding any of it.</p><p>I wanted to know what happens when a conversation gets too long for the context window. How tokens get counted. Why the response structure changed between model versions. What “streaming” actually means at the transport layer.</p><p>The only way to learn that is to build it yourself and break it repeatedly.</p><h3>The Stack and the Plan</h3><p>Same core as the retail API: FastAPI, SQLModel, PostgreSQL. Add OpenAI’s Python SDK.</p><p>Three-layer architecture: routers take requests, controllers handle logic, services talk to external APIs. Models define the data shapes. Everything lives under app/.</p><p>The plan was a roadmap of PRs, one feature at a time. No commits directly to main. Every change reviewed before merge.</p><p>I had a senior dev reviewing. Same as the retail API. He reviews my PRs, asks hard questions, and doesn’t let things slide.</p><h3>The First Six PRs Were Fast</h3><p>Scaffold, config, models, logging, error handling, health endpoint. These were mechanical. I’d done the patterns before on the retail API. Took a few days.</p><p>The models are worth mentioning because they drove everything else.</p><p>Two tables: Conversation (user_id, title, timestamps) and Message (conversation_id, user_message, ai_response, model used, tokens consumed, latency). Every API call gets stored. I wanted to track exactly what the model said, which version said it, how many tokens it used, and how long it took.</p><p>This felt like overkill at the time. It wasn’t. That data saved me multiple times during debugging.</p><h3>PR 7: First Working Chat Endpoint</h3><p>This is where it got real.</p><p>The chat endpoint needed to do a few things at once: create or continue a conversation, load the message history, build the right payload for OpenAI, call the API, store the result, return a clean response.</p><p>I wrote a single chat_controller function that handles both new and existing conversations. If no conversation_id is in the request, create one. If there is one, fetch the history and continue.</p><p>The controller builds the messages array like this:</p><pre>messages = [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: config.openai_system_prompt}]<br>for msg in history:<br>    messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: msg.user_message})<br>    messages.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: msg.ai_response})<br>messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: request.user_message})</pre><p>Simple. Obvious in hindsight.</p><p>The decorator for OpenAI error handling was more interesting. A @handle_openai_errors wrapper catches APITimeoutError, APIError, and generic exceptions, and converts them into clean HTTP responses with consistent error codes.</p><p>The controller doesn’t need to know how OpenAI fails( it just calls the service ).</p><h3>PR 8: The Project Structure Refactor</h3><p>The retail API taught me about app/ structure. I used it from the start here. But after seven PRs, I had a problem: config, database, and logging were scattered.</p><p>PR 8 moved everything infrastructure-related into app/core/. Config lives there. Database engine and session dependency live there. Logger setup lives there. Custom exceptions live there under app/core/errors/.</p><p>This sounds like housekeeping. It was. But now when I onboard someone, I can say: “The business logic is in controllers/. The infrastructure is in core/. The data shapes are in models/. Nothing bleeds between them.&quot;</p><p>That’s worth a whole PR.</p><h3>PR 11: The Debug Session From Hell</h3><p>I had a working structure. Clean architecture. Good patterns.</p><p>Then I ran the API for the first time locally and nothing worked.</p><p>The first error was a datetime serialization crash. JSONResponse couldn&#39;t serialize a Python datetime object. The fix was one method call - model_dump(mode=&quot;json&quot;) instead of model_dump(). Mode &quot;json&quot; converts datetimes and UUIDs to strings. Mode &quot;&quot; leaves them as Python objects. I didn&#39;t know that distinction existed.</p><p>The second error was the OpenAI API key not being found. I’d configured it with pydantic-settings, which reads .env files into a Settings object. What I didn&#39;t know: pydantic-settings populates the Settings object, but it doesn&#39;t write to os.environ. The OpenAI library reads os.environ. So the key existed in config.openai_api_key but the OpenAI client couldn&#39;t see it.</p><p>Fix: explicitly pass the key at client initialization.</p><pre>client = AsyncOpenAI(api_key=config.openai_api_key)</pre><p>I’d never had to think about this before because I’d never mixed a settings manager with a third-party SDK that reads environment variables directly.</p><p>Third error: max_tokens is deprecated for GPT-5 models. Use max_completion_tokens. Got a 400.</p><p>Fourth error: temperature isn&#39;t supported by GPT-5 mini. Another 400.</p><p>Fifth error: responses came back empty. The conversation history was being sent in reverse order ( newest messages first ). The model received the conversation backwards and returned nothing useful. Changed order_by(desc()) to order_by(asc()).</p><p>Sixth error: message history serialized as {} in the response. SQLModel&#39;s table=True models loaded from the database don&#39;t serialize cleanly through Pydantic v2 when using sa_column. The fix: Message.model_validate(msg) on each history item before returning.</p><p>Six separate bugs in one session. Each one taught me something I couldn’t have read in a tutorial, because tutorials don’t show you what breaks when you combine five technologies at once.</p><p>The API worked at the end of the day.</p><h3>Context Window: The Feature I Underestimated</h3><p>GPT-5 mini has a 128k token context window. Sounds like enough. It isn’t a reason to be lazy.</p><p>Sending the entire conversation history on every request is wasteful. At scale it’s expensive. And for a long conversation, the model spends time processing messages from hours ago that aren’t relevant anymore.</p><p>The initial implementation was message-count based: keep the last 15 messages. Simple, configurable via env var.</p><p>But message count and token count aren’t the same thing. Ten short messages is not the same as ten essay-length responses.</p><p>After seeing GPT’s assessment of the code, I moved to proper token-based trimming using tiktoken. The trimmer preserves the system prompt and the latest user message always, those are non-negotiable. Then it walks backwards through history, removing the oldest pairs of messages until the total token count fits within the limit.</p><p>When messages get evicted, they don’t disappear. A background task runs after the main response is returned. It takes the evicted messages and calls a cheap utility model to update a rolling summary, which gets stored on the Conversation record and injected back into context on the next request.</p><p>The result: conversations can run indefinitely without the model losing the thread of what was discussed early on.</p><p>This is the kind of problem that seems solved by “just use a big context window” until you start thinking about cost, latency, and what actually matters in a conversation.</p><h3>PR 12: CRUD Endpoints and a Database Lesson</h3><p>PATCH to update a conversation title. DELETE to remove a conversation entirely.</p><p>The DELETE looked simple. Fetch the conversation, delete the messages, delete the conversation, commit. Four lines.</p><p>It crashed with a foreign key violation. PostgreSQL won’t let you delete a conversation record if message records still reference it, even if you&#39;ve already queued those messages for deletion in the same session. SQLAlchemy batches the deletes and executes them in the wrong order.</p><p>The fix is one line: db.flush() after deleting the messages. This forces the message deletions to hit the database before the conversation deletion is issued.</p><p>I knew foreign keys existed. I didn’t know SQLAlchemy’s unit of work could silently reorder operations in a way that breaks FK constraints. Now I do.</p><h3>What the Code Looks Like Now</h3><p>The API has:</p><ul><li>POST /chat/ - new conversation</li><li>POST /chat/{conversation_id} - continue existing conversation</li><li>GET /chat/{conversation_id} - full message history</li><li>GET /chat/conversations/{user_id} - list user&#39;s conversations</li><li>PATCH /chat/{conversation_id}/title - rename a conversation</li><li>DELETE /chat/{conversation_id} - delete conversation and all messages</li></ul><p>Token-based context trimming. Rolling conversation summary. Exponential backoff retry for empty responses. Dual model setup — expensive model for chat, cheap model for background tasks like summarization.</p><p>The architecture is clean enough that adding streaming later won’t require rewriting the controller ( just changing how the service returns its response ).</p><h3>What I Learned That I Didn’t Expect to Learn</h3><p>OpenAI changes their API more than I expected. Parameters get deprecated between minor versions. A field that works on GPT-4o doesn’t work on GPT-5 mini. If you don’t read the changelog you get 400 errors with no obvious explanation.</p><p>Background tasks in FastAPI are useful but need their own database sessions. The main request session might be closed by the time the background task runs. Passing the engine and creating a new session inside the task is the right pattern.</p><p>TypeVar matters for decorator type safety. @handle_openai_errors originally had Any as the return type, which silently disabled type checking on every wrapped function. Fixing it to Callable[..., Awaitable[T]] took ten minutes and caught nothing immediately, but it makes the codebase defensible.</p><p>PR descriptions are not commit messages. A commit says what changed. A PR description explains what you changed, why you changed it, and what wasn’t obvious. I’m still getting this wrong, still getting feedback from the senior dev on it, still improving.</p><h3>Where It Goes From Here</h3><p>Auto-title generation: the model names the conversation from the first message instead of truncating it to 50 characters.</p><p>Streaming responses: instead of waiting for the full reply, tokens arrive as they’re generated.</p><p>Prompt loader: load system prompts from a file, select them via config. This is where the behavioral prompt work I’ve been doing separately gets wired in.</p><p>After that: Docker, tests, then the RAG layer that connects this chatbot to the retail inventory data.</p><p>The retail API is the foundation. This is the layer that makes it conversational. The third layer will make it actually know something about the domain.</p><p><em>Transitioning from retail operations to AI engineering. Building a fashion-focused retail API with a chatbot layer on top. <br> Follow the journey:</em><a href="https://github.com/chris-kechagias/simple-chatbot-api"><em>GitHub</em></a><em> | </em><a href="https://www.linkedin.com/in/chkechagias"><em>LinkedIn</em></a></p><p><em>Originally published at </em><a href="https://dev.to/kris_k/building-a-chatbot-api-from-scratch-13-prs-a-lot-of-broken-things-and-a-context-window-that-3i73"><em>https://dev.to</em></a><em> on March 28, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2ac7c9f3b25" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/building-a-chatbot-api-from-scratch-13-prs-a-lot-of-broken-things-and-a-context-window-that-d2ac7c9f3b25">Building a Chatbot API From Scratch: 13 PRs, a Lot of Broken Things, and a Context Window That…</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Restructuring a FastAPI Project, Migrating to Supabase, and Hitting 97% Test Coverage]]></title>
            <link>https://python.plainenglish.io/restructuring-a-fastapi-project-migrating-to-supabase-and-hitting-97-test-coverage-426dfafe1619?source=rss-898ab7ac3003------2</link>
            <guid isPermaLink="false">https://medium.com/p/426dfafe1619</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[coding-for-beginners]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Ck Chris Kechagias]]></dc:creator>
            <pubDate>Tue, 17 Mar 2026 07:16:50 GMT</pubDate>
            <atom:updated>2026-04-06T16:47:53.429Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Pfg0WjWjWXHUxpxP.png" /></figure><p>In <a href="https://dev.to/kris_k/why-i-rebuilt-my-first-api-from-scratch-p63">Part 1</a>, I explained why I archived my first API and started over. I ended that post with a confession: the new version still had a flat structure and no tests. Not portfolio material yet.</p><p>This is what happened next.</p><h3>The Flat Structure Problem</h3><p>The v2 codebase worked, but everything lived at the root level. products.py, variants.py, analytics.py, database.py - all siblings, all imports pointing everywhere. When I added a new router, I had to touch three files. When something broke, I had to search across the whole project.</p><p>The fix: move everything into an app/ package with proper separation.</p><pre>app/ <br>├── __init__.py <br>├── config.py <br>├── database.py <br>├── controllers/ <br>├── models/ <br>├── routers/ <br>├── middleware/ <br>└── utils/ <br>   └── errors/</pre><p>Each folder has a clear responsibility. controllers/ is business logic. routers/ is just route definitions. models/ is data shapes. middleware/ handles logging and exception handling. utils/errors/ defines custom exceptions.</p><p>This sounds obvious. It wasn’t to me three months ago.</p><h3>The __init__.py Pattern</h3><p>Every folder has an __init__.py that re-exports everything inside it. The goal: any file in the project should be able to import from a single clean path instead of hunting through nested modules.</p><pre># app/controllers/__init__.py<br>from .products import (<br>    create_product_controller as create_product_controller,<br>    delete_product_controller as delete_product_controller,<br>    get_product_controller as get_product_controller,<br>    get_products_controller as get_products_controller,<br>    update_product_controller as update_product_controller,<br>)</pre><p>The as X syntax is not redundant - it tells the linter (ruff) that these re-exports are intentional, not unused imports. Without it, CI fails.</p><p>Now a router just does:</p><pre>from ..controllers import create_product_controller, get_product_controller</pre><p>Clean. One source of truth per namespace.</p><h3>Dev Tooling: uv + Taskipy + Ruff</h3><p>Three tools that changed how I work:</p><p><strong>uv</strong> — package manager. Replaces pip. Dramatically faster, lock file included, virtual env handled automatically. No more pip install -r requirements.txt and hoping for the best.</p><p><strong>Taskipy</strong> — task runner. Instead of remembering long commands, I define shortcuts in pyproject.toml:</p><pre>[tool.taskipy.tasks]<br>dev = &quot;uvicorn main:app --reload&quot;<br>build = &quot;docker compose up --build&quot;<br>lint = &quot;ruff check .&quot;<br>fix = &quot;ruff check . --fix&quot;<br>test = &quot;pytest -v&quot;<br>dev_test = &quot;ruff check . &amp;&amp; pytest -v&quot;</pre><p>task dev_test runs lint then tests in one shot. task fix auto-corrects most ruff violations. Small thing, big quality of life improvement.</p><p><strong>Ruff</strong> — linter and formatter. Replaces flake8, isort, and black in one tool. Fast, opinionated, catches real problems. Made me write better imports and stop accumulating dead code.</p><h3>The Bug Safari</h3><p>Restructuring is not just moving files. Every import path breaks. Here’s what I found:</p><p><strong>Reserved logging keys.</strong> I had this in a controller:</p><pre>logger.info(&quot;Product created&quot;, extra={&quot;name&quot;: product.name})</pre><p>This caused a 500 error. name is a reserved key in Python&#39;s LogRecord - you can&#39;t use it in extra. Renamed to product_name, fixed. The error only appeared at runtime, not at import time.</p><p><strong>Route ordering conflict.</strong> GET /products/total_value kept returning 422. The analytics router was registered <em>after</em> the products router in main.py. FastAPI matched /total_value as a product ID (a string, hence 422). Moved analytics router first. Fixed.</p><p><strong>Missing </strong><strong>product_id in variant creation.</strong> ProductVariant.model_validate(variant) failed validation because product_id was required but not in the incoming request body - it comes from the URL path. The fix:</p><pre>db_variant = ProductVariant.model_validate(<br>    variant, update={&quot;product_id&quot;: product_id}<br>)</pre><p>Pydantic v2’s update parameter merges extra fields into the model during validation.</p><h3>Migrating to Supabase</h3><p>The original setup used a local PostgreSQL container via Docker Compose. Fine for development, annoying for deployment. Supabase gives you a managed PostgreSQL instance with a connection pooler.</p><p>The config change was minimal — just different environment variables:</p><pre># Local Docker <br>DB_HOST=localhost <br>DB_PORT=5432 <br># Supabase (Transaction pooler) <br>DB_HOST=aws-0-eu-central-1.pooler.supabase.com DB_PORT=6543</pre><p>One gotcha: Supabase has two pooler types. <strong>Session pooler</strong> keeps a persistent connection per client. <strong>Transaction pooler</strong> reuses connections across requests — better for serverless and low-traffic APIs on free tier. I use the Transaction pooler.</p><p>The connection string is assembled in database.py:</p><pre>engine = create_engine(<br>    f&quot;postgresql://{config.db_username}:{config.db_password}@{config.db_host}:{config.db_port}/{config.db_name}&quot;,<br>    connect_args={&quot;sslmode&quot;: &quot;prefer&quot;},<br>)</pre><p>If your password contains special characters (@, #, !), they&#39;ll break the URL. Use urllib.parse.quote_plus(password) to encode it.</p><h3>Writing Tests</h3><p>This was the part I’d been avoiding. Not because I didn’t want tests — because I didn’t know how to write them without hitting the real database.</p><p>The solution: SQLite in-memory + FastAPI’s dependency override pattern.</p><pre># tests/conftest.py<br>from contextlib import asynccontextmanager<br>from fastapi.testclient import TestClient<br>import pytest<br>from sqlmodel import Session, SQLModel, create_engine<br>from sqlmodel.pool import StaticPool<br>from app.database import get_session<br>from main import app<br><br>engine = create_engine(<br>    &quot;sqlite://&quot;, connect_args={&quot;check_same_thread&quot;: False}, poolclass=StaticPool<br>)<br><br>@asynccontextmanager<br>async def lifespan_override(app):<br>    yield<br><br>@pytest.fixture(name=&quot;session&quot;)<br>def session_fixture():<br>    SQLModel.metadata.drop_all(engine)<br>    SQLModel.metadata.create_all(engine)<br>    with Session(engine) as session:<br>        yield session<br>    SQLModel.metadata.drop_all(engine)<br><br>@pytest.fixture(name=&quot;client&quot;)<br>def client_fixture(session):<br>    app.dependency_overrides[get_session] = lambda: session<br>    app.router.lifespan_context = lifespan_override<br>    with TestClient(app) as client:<br>        yield client<br>    app.dependency_overrides.clear()</pre><p>Three things happening here:</p><ol><li>SQLite in-memory replaces PostgreSQL. No cloud DB needed, no network, instant setup.</li><li>get_session dependency is overridden - every request gets the test session, not a real DB connection.</li><li>The lifespan is overridden with a no-op — prevents the app from trying to connect to Supabase on test startup.</li></ol><p>Each test gets a fresh database. No shared state, no cleanup between tests.</p><h3>What the Tests Found</h3><p>This is the part worth highlighting.</p><p>While writing tests for the variant endpoints, I noticed the PATCH and DELETE routes didn&#39;t validate product existence before operating on variants:</p><pre># Before: missing product check<br>def update_product_variant_router(product_id, variant_id, ...):<br>    variant = update_product_variant_controller(variant_id, ...)<br>    if not variant:<br>        raise ProductVariantNotFoundException(variant_id)<br>    return variant</pre><p>You could PATCH /products/9999/variants/1 and it would happily update the variant - even if product 9999 didn&#39;t exist. Same for DELETE. Inconsistent behavior, not caught until tests tried to assert PRODUCT_NOT_FOUND.</p><p>The fix was two lines per route:</p><pre>product = get_product_controller(product_id, session)<br>if not product:<br>    raise ProductNotFoundException(product_id)</pre><p>This is exactly what tests are for. Not just confirming the happy path — stress-testing assumptions.</p><p>Final result: 29 tests, 97% coverage.</p><pre>TOTAL    412    11    97%</pre><p>The 3% uncovered is intentional: database error branches that only trigger on real DB failures, and the Supabase connection code skipped by the lifespan override.</p><h3>Where It Is Now</h3><p>The API is live on Render, connected to Supabase, monitored by UptimeRobot.</p><p><strong>Live docs:</strong> <a href="https://retail-inventory-api-yati.onrender.com/docs">retail-inventory-api-yati.onrender.com/docs</a></p><p>What’s still missing: integration tests against the live deployment, an analytics expansion, and a repository pattern refactor I’ve been putting off.</p><p>What’s next: a chatbot API. This retail API becomes the data layer. The chatbot queries it.</p><p><em>Transitioning from retail operations to AI engineering.</em></p><p><em>Follow the journey: </em><a href="http://www.linkedin.com/in/chkechagias">LinkedIn</a> | <a href="https://github.com/chris-kechagias">GitHub</a></p><p><em>Originally published at </em><a href="https://dev.to/kris_k/restructuring-a-fastapi-project-migrating-to-supabase-and-hitting-97-test-coverage-59eb"><em>https://dev.to</em></a><em> on March 17, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=426dfafe1619" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/restructuring-a-fastapi-project-migrating-to-supabase-and-hitting-97-test-coverage-426dfafe1619">Restructuring a FastAPI Project, Migrating to Supabase, and Hitting 97% Test Coverage</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I Rebuilt My First API From Scratch]]></title>
            <link>https://python.plainenglish.io/why-i-rebuilt-my-first-api-from-scratch-1f082da1ccfe?source=rss-898ab7ac3003------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f082da1ccfe</guid>
            <category><![CDATA[career-change]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ck Chris Kechagias]]></dc:creator>
            <pubDate>Sat, 07 Mar 2026 13:00:04 GMT</pubDate>
            <atom:updated>2026-04-06T16:49:47.347Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*31HbD9Ttf0rI3gBD.png" /></figure><p>I built my first API two months ago. It worked. I deployed it. Users could hit endpoints, get responses, everything functioned. By most measures, it was a success.</p><p>Then I looked at the code with someone who actually knew what they were doing, and realized: working isn’t the same as professional.</p><p>So I archived it and started over.</p><h3>The First Version</h3><p>My original retail inventory API did what it was supposed to do. CRUD operations, PostgreSQL database, running in production on Render. I followed tutorials, copied patterns I found online, debugged until things worked.</p><p>The problem wasn’t that it failed. The problem was I couldn’t explain <em>why</em> it succeeded.</p><p>When someone asked me to walk through the architecture, I stumbled. Why did I structure the database this way? “That’s what the tutorial showed.” What’s your error handling strategy? I didn’t have one-just try-catch blocks scattered everywhere.</p><p>I could make it run, but I couldn’t defend the design. That bothered me.</p><h3>Starting Over</h3><p>The easy path: refactor incrementally. Add tests here, clean up there, gradually improve. But the foundation was shaky. I’d built on patterns I didn’t understand. Every new feature would compound that.</p><p>Starting from scratch felt wasteful. Two months of work, gone. But those two months taught me what questions to ask. The second time, I wasn’t following tutorials blindly-I was making actual decisions.</p><h3>What Changed</h3><p><strong>Database Design</strong></p><p>Version one: single products table with basic fields. Version two: proper product-variant relationship.</p><p>Products have category (Tees, Sweaters, Pants), name, color, price, and collection (“FW24”, “SS25”). Variants add size (S-M, L-XL, One Size) with individual quantity and in_stock tracking.</p><p>This solves real fashion problems: when a customer wants Size L-XL specifically, you need to know if <em>that</em> variant is in stock, not just whether the base product exists. Categories and sizes use Enums-can’t create invalid entries. Field validators catch edge cases like empty strings.</p><p>More complex than a single table, but it mirrors how actual retail inventory works.</p><p><strong>Architecture</strong></p><p>Everything used to live in main.py. Routes, business logic, database queries, all mixed. Worked for five endpoints. Would&#39;ve been unmaintainable at fifty.</p><p>Now: separation of concerns. main.py launches. Services handle logic. Routes define endpoints. Models define data. When I need to change product creation, I know exactly where to look.</p><p><strong>Error Handling</strong></p><p>Old way: wrap things in try-catch when they broke, handle locally, hope nothing unexpected happens.</p><p>New way: centralized error handler. One place catches exceptions, formats responses consistently, logs properly. Something goes wrong anywhere, it gets handled the same way.</p><p><strong>Development Workflow</strong></p><p>Biggest change wasn’t the code-it was how I wrote it. Version one was commits to main whenever something worked. Version two uses pull requests for every feature. Every change gets reviewed before merge.</p><p>Felt slow. It is slower. But “slower” means “catching issues before production” and “understanding why patterns matter.”</p><h3>What Code Review Actually Teaches You</h3><p>Having someone review my code exposed gaps I didn’t know existed.</p><p>I renamed functions but didn’t understand what I was renaming. I was splitting routers from controllers mechanically but couldn’t explain the pattern. When asked “are you sure you only need .venv in dockerignore?&quot; I realized I was thinking about exclusions wrong-should&#39;ve been excluding everything and whitelisting what I need.</p><p>I named a docker service web generically. Got told: &quot;You&#39;re api. When you add a frontend later, that&#39;s web.&quot; Right. I was thinking &quot;web server.&quot; Should&#39;ve been thinking &quot;what does this service actually do.&quot;</p><p>These weren’t “change this line” comments. They were “here’s why this matters” and “think about scaling.” That’s what tutorials don’t teach.</p><p>Some PRs got approved quickly. Others took three rounds. The ones that took longer taught me more.</p><h3>The Gaps I’m Still Filling</h3><p>Rebuilding didn’t make me an expert. Made me aware of what I don’t know.</p><p>I implement CRUD operations but couldn’t clearly explain in an interview what CRUD means and why it matters as a pattern. I use an ORM (SQLModel) but can’t give a solid answer on when to use ORM versus raw SQL and what the tradeoffs are. I have a centralized error handler but had to look up why it’s “error handler” not “exception handler” and what that distinction means.</p><p>These are basic things. Interview questions. The fact that I’m building working software while having these gaps means I need to go back to fundamentals-not to learn how to code, but to learn how to articulate what I’m doing and why.</p><h3>The Result</h3><p>Original API: archived, private. Not bad code-just a snapshot of where I was three months ago. Not portfolio material.</p><p>New version isn’t production-ready either, still flat, need tests and a proper folder-structure architecture. I’m honest about that. But it’s built on patterns I can explain. When I add tests next week, the architecture supports it. When I build a chatbot layer next month, I’ll have confidence in the foundation.</p><h3>If You’re In The Same Position</h3><p>If you built something that works but can’t explain it, consider rebuilding. Not because the first version was wrong-because the second version will teach you things the first couldn’t.</p><p>You’ll see patterns you missed. You’ll understand why approaches matter. You’ll find knowledge gaps you didn’t know existed. When someone asks you to explain design decisions, you’ll have answers deeper than “the tutorial told me to.”</p><p>First version proves you can make it work. Second version proves you understand why it works.</p><p>That difference matters.</p><p><em>Transitioning from retail operations to AI engineering. Building a fashion-focused retail API with FastAPI + PostgreSQL. Next: chatbot layer, then RAG, then multi-agent systems.</em></p><p><em>Follow the journey: </em><a href="http://www.linkedin.com/in/chkechagias">LinkedIn</a> | <a href="https://github.com/chris-kechagias">GitHub</a></p><p><em>Originally published at </em><a href="https://dev.to/kris_k/why-i-rebuilt-my-first-api-from-scratch-p63"><em>https://dev.to</em></a><em> on March 7, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f082da1ccfe" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/why-i-rebuilt-my-first-api-from-scratch-1f082da1ccfe">Why I Rebuilt My First API From Scratch</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>