<?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 Ahmet Kutay Ural on Medium]]></title>
        <description><![CDATA[Stories by Ahmet Kutay Ural on Medium]]></description>
        <link>https://medium.com/@ahmetkutayural?source=rss-408cb033f970------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WaP5fgy-bN7wHulznYOifA.jpeg</url>
            <title>Stories by Ahmet Kutay Ural on Medium</title>
            <link>https://medium.com/@ahmetkutayural?source=rss-408cb033f970------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 04:10:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahmetkutayural/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[Improving FastAPI Swagger UI with a Dark / Light Mode Toggle]]></title>
            <link>https://medium.com/@ahmetkutayural/improving-fastapi-swagger-ui-with-a-dark-light-mode-toggle-6f7edb7eaa05?source=rss-408cb033f970------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f7edb7eaa05</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[developer-experience]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ahmet Kutay Ural]]></dc:creator>
            <pubDate>Thu, 12 Feb 2026 20:20:12 GMT</pubDate>
            <atom:updated>2026-02-12T20:20:12.380Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eiaB-MHNM2kn1W5BgR4fOQ.png" /><figcaption>fastapi-ui-swagger-theme</figcaption></figure><p>FastAPI is one of the best Python frameworks for building APIs. It is fast, clean, and developer-friendly. One of its biggest advantages is the built-in Swagger UI documentation.</p><p>If you work with FastAPI daily like I do, you probably spend a lot of time looking at Swagger.</p><p>And while the default theme is clean and functional, staring at a bright white screen for hours, especially during late-night debugging sessions, can be exhausting.</p><p>Instead of replacing Swagger entirely with a custom theme, I asked a simple question:</p><p>What if we just added a proper Dark / Light toggle while keeping the original look?</p><h3>The Problem</h3><p>Most dark-mode implementations either:</p><ul><li>Replace Swagger completely</li><li>Override large parts of the styling</li><li>Or break the default FastAPI integration</li></ul><p>I wanted something minimal.</p><p>No hacks.</p><p>No breaking changes.</p><p>No heavy overrides.</p><p>Just a clean enhancement.</p><h3>The Goal</h3><p>The idea was simple:</p><ul><li>Preserve the original Swagger feel</li><li>Add a smooth Dark / Light toggle</li><li>Keep full compatibility with FastAPI</li><li>Make installation extremely simple</li></ul><p>It should feel like a native extension, not a redesign.</p><h3>The Result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yeYhkHl0pTd1HKml9jhTnQ.png" /><figcaption>fastapi-ui-swagger-theme</figcaption></figure><p>I built a lightweight package that enhances FastAPI’s Swagger UI with:</p><ul><li>Dark / Light theme toggle</li><li>Improved visual comfort</li><li>Zero breaking changes</li><li>One-line integration</li></ul><p>Yes, it literally works with one line of code.</p><p>Your eyesight is worth more than one line of code.</p><h3>Installation</h3><pre>from fastapi import FastAPI<br>from fastapi_swagger_ui_theme import apply_swagger_theme<br><br>app = FastAPI()<br><br>apply_swagger_theme(app)</pre><p>That’s it.</p><h3>Why This Matters</h3><p>Developer experience matters.</p><p>Small improvements compound over time. If you interact with your API documentation every day, even minor visual improvements can significantly reduce fatigue.</p><p>This project is not about redesigning Swagger.</p><p>It is about respecting the original design and making it more comfortable.</p><h3>GitHub &amp; PyPI</h3><p>GitHub:</p><p><a href="https://github.com/akutayural/fastapi-swagger-ui-theme">https://github.com/akutayural/fastapi-swagger-ui-theme</a></p><p>PyPI:</p><p><a href="https://pypi.org/project/fastapi-swagger-ui-theme/">https://pypi.org/project/fastapi-swagger-ui-theme/</a></p><p>Contributions, feedback, and feature ideas are very welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f7edb7eaa05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tired of Messy FastAPI Responses? Standardise Them with APIException]]></title>
            <link>https://medium.com/@ahmetkutayural/tired-of-messy-fastapi-responses-standardise-them-with-apiexception-528b92f5bc4f?source=rss-408cb033f970------2</link>
            <guid isPermaLink="false">https://medium.com/p/528b92f5bc4f</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[api-design]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Ahmet Kutay Ural]]></dc:creator>
            <pubDate>Tue, 22 Jul 2025 08:01:59 GMT</pubDate>
            <atom:updated>2025-07-22T08:01:59.060Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Aren’t you guys tired of receiving inconsistent server responses from different API calls in 2025? You probably are. Besides, let’s not even talk about those nightmare endpoints that return completely different structures for success and error responses… Wouldn’t it be better to have endpoints that return standardised responses for both success and error cases — including unexpected errors such as third-party failures, database errors, and more — in FastAPI? If you think the same, I’ve built something that might be interesting for you.</strong></blockquote><ul><li><a href="https://akutayural.github.io/APIException/">APIException</a></li><li><a href="https://pypi.org/project/apiexception/">apiexception</a></li><li><a href="https://github.com/akutayural/APIException">GitHub - akutayural/APIException: APIException is a customizable exception-handling library designed for Python and FastAPI applications, offering standardized error codes, messages, and HTTP status responses to improve error management and consistency across APIs.</a></li></ul><p>After having 4+ years of experience with <a href="https://fastapi.tiangolo.com/"><em>FastAPI</em></a>, I’ve built a <a href="https://pypi.org/project/APIException/">package</a> that I ended up using across nearly all my <a href="https://fastapi.tiangolo.com/"><em>FastAPI</em></a><em> </em>projects. <a href="https://fastapi.tiangolo.com/"><em>FastAPI</em></a> is a high-performance Web API Framework for <a href="https://www.python.org/"><em>Python</em></a>, created by <a href="https://medium.com/u/963974981597">Sebastián Ramírez</a>, that allows you to create and document APIs with ease. It’s one of the <a href="https://github.com/fastapi/fastapi">best Python web development frameworks</a> out there, no doubt. It provides built-in automatic documentation with <a href="https://swagger.io/specification/"><em>Swagger UI</em></a><em>.</em> <strong>However</strong>, <strong>it lacks a built-in solution for standardising backend responses in both actual <em>API responses</em> and within the </strong><a href="https://swagger.io/specification/"><strong><em>Swagger UI</em></strong></a><strong> documentation.</strong></p><p>We are talking about standardising backend responses in both actual <em>API responses</em> and within the <a href="https://swagger.io/specification/"><em>Swagger UI</em></a> documentation, but what exactly do I mean? I’ve created a <a href="https://akutayural.github.io/APIException/usage/response_model/"><strong><em>ResponseModel</em></strong></a> class that can be imported from <a href="https://akutayural.github.io/APIException/"><strong>APIException</strong></a>, which I believe can cover the majority of projects. It’s quite simple yet effective. The below gift demonstrates how <strong><em>ResponseModel</em></strong><em> looks in the </em><strong><em>Swagger UI</em></strong><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UVdNqAUfqBUbi--WGyjzKA.gif" /><figcaption><a href="https://akutayural.github.io/APIException/usage/response_model/"><strong><em>ResponseModel</em></strong></a> <strong>Schema and Swagger UI</strong></figcaption></figure><p>The <a href="https://akutayural.github.io/APIException/usage/response_model/"><strong>ResponseModel</strong></a> has 5 attributes to cover most of the cases.</p><ul><li><strong><em>data</em></strong>:<em> </em><strong>Optional</strong>[<strong><em>any</em></strong> | <strong><em>None</em></strong>] — The parameter holds the <strong>server response</strong> <strong>payload</strong>. It can be <strong><em>any</em></strong> type(List, dict, List[tuple], List[dict], etc.). It’s used when you want to return actual data (e.g., from a GET or POST request); otherwise, it’s <strong><em>None</em></strong>.</li><li><strong><em>status</em></strong>: <strong><em>str — </em></strong>Indicates the <strong>status of the server response</strong>. It reflects whether the request was successful or not. This field is strongly typed with the importable <strong><em>ExceptionStatus</em></strong> enum, which includes:</li></ul><pre>[&#39;SUCCESS&#39;, &#39;WARNING&#39;, &#39;ERROR&#39;]</pre><ul><li><strong><em>message</em></strong>: <strong><em>str — </em>Default<em> </em></strong>to<strong><em> “Operation completed successfully” </em></strong><em>for successful cases</em><strong><em>. </em></strong>This field is meant to <strong>provide a human-readable summary</strong> of the response.<em> In error cases</em>, it gives a concise explanation of what went wrong — such as “<strong><em>User not found</em></strong>” or “<strong><em>Invalid credentials</em></strong>” — making it easy to communicate with the client or frontend.</li><li><strong><em>error_code</em></strong>: <strong><em>Optional</em></strong>[<strong><em>str | None</em></strong>] — This is a <strong>custom, developer-friendly identifier</strong> for each error type. Instead of just relying on HTTP status codes, you can define specific error codes like:</li></ul><pre>[None, &quot;AUTH-1000&quot;, &quot;USR-404&quot;, &quot;API-401&quot;, &quot;PERM-403&quot;]</pre><p>These can be defined and reused across your project, making debugging and logging <strong>much more efficient and traceable</strong>. <em>APIException</em> also <strong>logs</strong> all the errors <strong>by default</strong>.</p><p>This is especially useful in multilingual systems or where the frontend needs to display different error messages based on the context.</p><ul><li><strong><em>description</em></strong>: <strong>Optional</strong>[<strong><em>str</em></strong> | <strong><em>None</em></strong>] — This field offers a <strong>detailed explanation</strong> of the error or response. While the message is more human-readable and concise, the description provides <strong>context or instructions</strong> — like what might have caused the error, or how to resolve it.</li></ul><p>Example:</p><pre>[&quot;User has been found.&quot;, &quot;Account details have been provided.&quot;, &quot;Permission denied.&quot;]</pre><p>If you’re not building something highly specialised or domain-specific, the ResponseModel class will likely cover <strong>over 90% of your use cases</strong>. Your API responses will always be <strong>structured, predictable, and clean</strong>. This consistency not only improves your backend code quality but also makes integration with frontend and third-party systems <strong>much easier and safer</strong>.</p><h3><strong>Successful Response Example</strong></h3><p>This is what a clean and consistent response looks like when everything goes right. Your frontend always knows what to expect, which reduces friction in development and debugging.</p><figure><img alt="Successful Response Structure" src="https://cdn-images-1.medium.com/max/1024/1*_7VXzKWCjVugWIjnbi_pHA.gif" /><figcaption><strong>Successful</strong> <strong>Response</strong> Structure</figcaption></figure><pre>{<br>  &quot;data&quot;: {<br>    &quot;id&quot;: 7,<br>    &quot;username&quot;: &quot;John Doe&quot;<br>  },<br>  &quot;status&quot;: &quot;SUCCESS&quot;,<br>  &quot;message&quot;: &quot;Operation completed successfully.&quot;,<br>  &quot;error_code&quot;: null,<br>  &quot;description&quot;: &quot;User fetched successfully.&quot;<br>}</pre><h3><strong>Error Response Example</strong></h3><p>Even when something goes wrong — whether it’s a user input issue or an unexpected internal error — the structure <strong>stays the same</strong>.</p><p>This makes it easy to <em>parse, log,</em> and <em>act</em> on errors <strong>consistently</strong> without needing to handle multiple response shapes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*51TizoyQrhmDZQL2G8lUqQ.gif" /><figcaption><strong>Error Response</strong> Structure</figcaption></figure><pre>{<br>  &quot;data&quot;: null,<br>  &quot;status&quot;: &quot;FAIL&quot;,<br>  &quot;message&quot;: &quot;User not found.&quot;,<br>  &quot;error_code&quot;: &quot;USR-404&quot;,<br>  &quot;description&quot;: &quot;The user ID does not exist.&quot;<br>}</pre><p>So, if you like it so far,<strong> here’s how you can get started quickly:</strong></p><p>Firstly, you should download the library via pip.</p><pre>pip install apiexception</pre><figure><img alt="Installing the APIException" src="https://cdn-images-1.medium.com/max/1024/1*aY3p4oMqjWpfZoJ-uIIx5g.gif" /><figcaption>Installing the <a href="https://akutayural.github.io/APIException/"><strong>APIException</strong></a></figcaption></figure><p>After installing the library, you’re<strong> good to go.</strong></p><p>Let me walk you through a basic usage example to show how easy it is to integrate APIException into your FastAPI project:</p><pre>from APIException import register_exception_handlers<br>from fastapi import FastAPI<br>app = FastAPI()<br>register_exception_handlers(app=app)</pre><p>Just import the register_exception_handlers function from APIException and call it with your FastAPI app instance to set up global exception handling as shown above. <br>That’s it — copy, paste. So easy, innit?</p><p>Now all your endpoints will return consistent success and error responses, and your Swagger docs will be beautifully documented. Exception handling will be logged, and unexpected errors will return a clear JSON response instead of FastAPI’s default HTML error page.</p><h3>🔍 See It in Action!</h3><pre>from fastapi import FastAPI, Path<br>from APIException import (<br>APIException,<br>ExceptionStatus,<br>register_exception_handlers,<br>ResponseModel,<br>APIResponse,<br>BaseExceptionCode<br>)<br>from pydantic import BaseModel<br><br>app = FastAPI()<br><br># Register exception handlers globally to have the consistent<br># error handling and response structure<br>register_exception_handlers(app=app)<br><br># Create the validation model for your response<br>class UserResponse(BaseModel):<br>    id: int<br>    username: str<br><br># Define your custom exception codes extending BaseExceptionCode<br># You can create your own exception classes by:<br># class &lt;classname&gt;(BaseExceptionCode):<br>class CustomExceptionCode(BaseExceptionCode):<br>    USER_NOT_FOUND = (&quot;USR-404&quot;, &quot;User not found.&quot;, &quot;The user ID does not exist.&quot;)<br>    INVALID_API_KEY = (&quot;API-401&quot;, &quot;Invalid API key.&quot;, &quot;Provide a valid API key.&quot;)<br>    PERMISSION_DENIED = (&quot;PERM-403&quot;, &quot;Permission denied.&quot;, &quot;Access to this resource is forbidden.&quot;)<br><br><br>@app.get(&quot;/user/{user_id}&quot;,<br>    response_model=ResponseModel[UserResponse],<br>    responses=APIResponse.default()<br>)<br>async def user(user_id: int = Path()):<br>    if user_id == 1:<br>        raise APIException(<br>            error_code=CustomExceptionCode.USER_NOT_FOUND,<br>            http_status_code=401,<br>        )<br>    data = UserResponse(id=user_id, username=&quot;John Doe&quot;)<br>    return ResponseModel[UserResponse](<br>        data=data,<br>        description=&quot;User found and returned.&quot;<br>    )</pre><p>You can define <strong>semantic error codes</strong> using BaseExceptionCode. This gives you:</p><ul><li>An <strong>error code</strong> (e.g., “USR-404”)</li><li>A <strong>short message</strong> (e.g., “User not found.”)</li><li>A <strong>developer-friendly description</strong> (e.g., “The user ID does not exist.”)</li></ul><p>This improves <strong>readability</strong>, <strong>debugging</strong>, and also makes your <strong><em>Swagger UI</em></strong> look much more professional.</p><h4>Raising API Exceptions the Right Way</h4><pre>raise APIException(<br>    error_code=CustomExceptionCode.USER_NOT_FOUND,<br>    http_status_code=401,<br>)</pre><p>You simply raise APIException with your predefined error code. You don’t need to manually craft JSON responses or worry about response structure. The response will always follow your ResponseModel format, including in Swagger UI.</p><figure><img alt="APIException Exception" src="https://cdn-images-1.medium.com/max/1024/1*kqMy54iqbjBaKrkE_lV-TQ.gif" /><figcaption><strong>APIException</strong> <strong>Exception</strong> Case Example</figcaption></figure><h4>Returning a Successful Response</h4><pre>return ResponseModel[UserResponse](<br>    data=data,<br>    description=&quot;User found and returned.&quot;<br>)</pre><p>You return a structured success response using the ResponseModel. It includes:</p><ul><li><strong><em>data</em></strong>: The actual response payload (in this case, a user)</li><li><strong><em>status</em></strong>: Automatically defaults to SUCCESS</li><li><strong><em>description</em></strong>: An optional detail for better context</li></ul><p>This keeps your API output <strong>predictable, clean, and well-documented.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4P6gEnSo22s9wqzbNc5CfA.gif" /><figcaption><strong>APIException</strong> <strong>Success </strong>Case<strong> </strong>Response Model Example</figcaption></figure><h4>Improving Swagger UI with Response Models</h4><pre>response_model=ResponseModel[UserResponse],<br>responses=APIResponse.default()</pre><p>By including this, your Swagger UI now documents both:</p><ul><li>Standard success responses</li><li>Standardised error responses with code/message/description</li></ul><p>It means frontend devs, testers, and API consumers can <strong>instantly understand how your API behaves</strong> in both good and bad cases — without guessing or reading extra docs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4hAaq2IEsO0VaUK0_3mTKg.gif" /><figcaption><strong>Success and Error case Response Structure</strong></figcaption></figure><figure><img alt="Response Schema Example For Both Error and Success Cases" src="https://cdn-images-1.medium.com/max/400/1*D6lZvKJ3eQ_22uP6pJEmCg.gif" /><figcaption><strong>Response Schema</strong> Example For Both Error and Success Cases</figcaption></figure><blockquote><em>So, who wouldn’t want that level of </em><strong>standardisation</strong><em> in their </em><strong>server responses</strong><em>? I believe every developer has needed this at some point.</em></blockquote><p>Error cases are also logged as illustrated in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QASuxOR3xgPYg3g1cmVuTQ.png" /><figcaption>Example of <strong>APIException</strong> <strong>Automatic Logging</strong> When Exception cases</figcaption></figure><p>For more information about the project, I highly recommend that you check out the <a href="https://akutayural.github.io/APIException/">project documentation</a>.</p><h3><em>You can find the project on GitHub, install it via PyPI, and explore the documentation below:</em></h3><ul><li>🔗 GitHub: <a href="https://github.com/akutayural/APIException">github.com/akutayural/APIException</a></li><li>📦 PyPI: <a href="https://pypi.org/project/apiexception">pypi.org/project/apiexception</a></li><li>📚 Documentation: <a href="https://akutayural.github.io/APIException">akutayural.github.io/APIException</a></li></ul><h3>🛠️ How to Contribute to APIException</h3><p>Contributions are welcome and appreciated! Feel free to open an issue, submit a pull request, or <strong>star</strong> <a href="https://medium.com/github.com/akutayural/APIException"><strong>the repo</strong></a> if you find it helpful.</p><p>Here’s how you can get started:</p><ol><li><strong>Fork the Repository</strong></li><li>Go to the <a href="https://github.com/akutayural/APIException">GitHub repository</a> and click the Fork button to create your copy of the project.</li><li><strong>Clone Your Fork</strong></li><li>Open your terminal and run:</li></ol><pre>git clone https://github.com/your-username/APIException.git<br>cd APIException</pre><p><strong>5. Create a New Branch</strong></p><p>6. Always create a new branch for your changes:</p><pre>git checkout -b feature/your-feature-name</pre><p><strong>7. Make Your Changes</strong></p><p><strong>8.</strong> Implement your changes (code, docs, examples, etc.) and make sure to follow the existing style and structure.</p><p><strong>9. Test Your Changes</strong></p><p>Make sure everything works properly and doesn’t break existing functionality. If needed, add tests.</p><p><strong>10. Commit Your Work</strong></p><pre>git add .<br>git commit -m &quot;Add: description of your change&quot;</pre><p><strong>11.</strong> <strong>Push to Your Fork</strong></p><pre>git push origin feature/your-feature-name</pre><p><strong>12</strong>. <strong>Open a Pull Request</strong></p><p>Go to your fork on GitHub, and click Compare &amp; Pull Request. Write a clear and concise description of your changes.</p><h4>Developer Suggestion:</h4><p><em>If you’re building modern APIs with FastAPI and care about clean, consistent backend responses, this library might save you hours. Designed for production-grade APIs, microservices, and developer-friendly documentation.</em></p><blockquote><em>Let’s make error handling and API responses less painful and more predictable — together.</em></blockquote><blockquote><em>And hey, big thanks to </em><a href="https://github.com/tiangolo"><em>@tiangolo</em></a><em> (Sebastián Ramírez) for creating FastAPI — your work keeps inspiring us every day.</em></blockquote><h3>Final Note</h3><p>APIException is currently at <strong>v0.1.16</strong> and actively maintained. I’m committed to keeping it up to date with improvements and new features. The project is open to contributions — feel free to check out the <a href="https://github.com/akutayural/APIException">GitHub repository</a>. The documentation is also regularly updated to reflect the latest changes.</p><p>If you have suggestions, feature requests, or feedback, don’t hesitate to reach out via GitHub or even leave a comment here on Medium. If a feature makes sense and benefits the community, I’d be more than happy to add it!</p><p><strong>Cheers! 🍻</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=528b92f5bc4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Error Handling in FastAPI with APIException]]></title>
            <link>https://medium.com/@ahmetkutayural/simplify-error-handling-in-fastapi-with-apiexception-library-fd2f6123e482?source=rss-408cb033f970------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd2f6123e482</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ahmet Kutay Ural]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 13:58:58 GMT</pubDate>
            <atom:updated>2024-11-15T09:26:01.672Z</atom:updated>
            <content:encoded><![CDATA[<p>Error handling is a critical aspect of any application, especially in APIs where it’s essential to communicate issues clearly to end-users. With <strong>APIException</strong>, my new open-source Python library, you can take control of error handling in <strong>FastAPI</strong> applications, define custom error codes, and enhance the user experience with structured responses.</p><p>If you’re in a scenario where managing and customising the error messages displayed to end-users is essential, <strong>APIException</strong> provides a streamlined solution, giving you full control over exceptions raised by the backend. The library is easy to integrate, offering complete customisation options with support for response models, HTTP status codes, descriptions, messages, and status indicators. It also automatically logs exception details, making it both powerful and developer-friendly.</p><h3>Why Use APIException?</h3><p>FastAPI provides basic error handling, but <strong>APIException</strong> elevates this by enabling:</p><p>• <strong>Customisable error codes and messages:</strong> Tailor error responses to specific scenarios in your app.</p><p>• <strong>Standardised structure for errors:</strong> Consistent format across all error responses makes debugging and integration easier.</p><p>• <strong>Built-in logging:</strong> Automatically logs details (file and line) where exceptions occur.</p><p>• <strong>Enhanced control:</strong> Keep error handling in your backend, allowing for fine-grained control over what end-users see.</p><p>👉 <a href="https://pypi.org/project/APIException/"><strong>Check out APIException on PyPI</strong></a></p><h3><strong>Installation</strong></h3><p>Getting started with <strong>APIException</strong> is simple. Install the package using pip:</p><pre>pip install APIException</pre><p><strong>Step 1: Integrating APIException into FastAPI</strong></p><p>To start using <strong>APIException</strong> in your FastAPI project:</p><pre>from fastapi import FastAPI<br>from api_exception.exception import APIException<br>from custom_enum.enums import ExceptionCode, ExceptionStatus<br>from schemas.response_model import ResponseModel<br><br>app = FastAPI()<br><br>@app.get(&quot;/login&quot;)<br>async def login(username: str, password: str):<br>    if username != &quot;admin&quot; or password != &quot;admin&quot;:<br>        raise APIException(<br>            error_code=ExceptionCode.AUTH_LOGIN_FAILED,<br>            http_status_code=401<br>        )<br>    return ResponseModel(data={&quot;username&quot;: username})</pre><p>In this example:</p><p>• An <strong>APIException</strong> is raised if login fails, returning an error with a custom code, status, and message.</p><ul><li><strong>APIException</strong> handles the error consistently, providing a detailed response for clients.</li></ul><p><strong>Step 2: Customising Exception Codes</strong></p><p>Define custom error codes by creating a new class that extends BaseExceptionCode:</p><pre>from custom_enum.enums import BaseExceptionCode<br><br>class CustomExceptionCode(BaseExceptionCode):<br>    USER_NOT_FOUND = (&quot;USR-404&quot;, &quot;User not found.&quot;, &quot;This user doesn’t exist in our database.&quot;)<br>    INVALID_API_KEY = (&quot;API-401&quot;, &quot;Invalid API key.&quot;, &quot;Your API key is incorrect.&quot;)<br><br>@app.get(&quot;/user/{user_id}&quot;)<br>async def get_user(user_id: int):<br>    if user_id != 1:<br>        raise APIException(<br>            error_code=CustomExceptionCode.USER_NOT_FOUND<br>        )<br>    return ResponseModel(data={&quot;user_id&quot;: user_id, &quot;name&quot;: &quot;John Doe&quot;})</pre><p>📝 <strong>Tip</strong>: You can name this class (CustomExceptionCode) anything meaningful, like CustomExceptionCode, APIExceptionCode, and so on.</p><p><strong>Step 3: Setting up a Global Exception Handler</strong></p><p>You can set up a global exception handler to manage all APIException errors consistently across endpoints.</p><pre>from fastapi.responses import JSONResponse<br>from fastapi import Request<br><br>@app.exception_handler(APIException)<br>async def api_exception_handler(request: Request, exc: APIException):<br>    return JSONResponse(<br>        status_code=exc.http_status_code,<br>        content=exc.to_response()<br>    )</pre><p><strong>Step 4: Using ResponseModel for Consistent Success Responses</strong></p><p>To structure successful responses, use the provided ResponseModel:</p><pre>@app.get(&quot;/success&quot;)<br>async def success():<br>    return ResponseModel(<br>        data={&quot;message&quot;: &quot;Operation was successful&quot;},<br>        status=ExceptionStatus.SUCCESS,<br>        message=&quot;Success!&quot;<br>    )</pre><p><strong>Advanced Customisations: HTTP Status Codes and Response Models</strong></p><p><strong>APIException</strong> also allows you to customise HTTP status codes and response models as your application grows. Adjust the <em>http_status_code </em>in APIException or extend ResponseModel to match your application’s needs.</p><p><strong>Final Thoughts</strong></p><p><strong>💡 Key Benefits Recap:</strong></p><ul><li>Structured and standardised error responses</li><li>Enhanced control over error messaging for end-users</li><li>Simple integration and customizability</li></ul><p>Check out <strong>APIException</strong> on <a href="https://github.com/akutayural/APIException">GitHub</a>;</p><p><a href="https://github.com/akutayural/APIException">GitHub - akutayural/APIException: APIException is a customizable exception-handling library designed for Python and FastAPI applications, offering standardized error codes, messages, and HTTP status responses to improve error management and consistency across APIs.</a></p><p>or install it from <a href="https://pypi.org/project/APIException">PyPI</a>.</p><p><a href="https://pypi.org/project/APIException/">APIException</a></p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd2f6123e482" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Hackers Steal Your Authentication Tokens Using MITM (and Protect Against It): Step-by-Step…]]></title>
            <link>https://medium.com/@ahmetkutayural/how-hackers-steal-your-authentication-tokens-using-mitm-and-protect-against-it-step-by-step-e3401d42a181?source=rss-408cb033f970------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3401d42a181</guid>
            <dc:creator><![CDATA[Ahmet Kutay Ural]]></dc:creator>
            <pubDate>Sun, 10 Nov 2024 02:52:24 GMT</pubDate>
            <atom:updated>2024-11-10T02:52:24.484Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>How Hackers Steal Your Authentication Tokens Using MITM (and Protect Against It): Step-by-Step Explanation</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*R61ApuWBVu5DpaOC0oK2-g.jpeg" /></figure><p><strong><em>Alright, here’s the deal: </em></strong>APIs are the backbone of modern apps, and tokens are what keep them secure. But have you ever wondered how <strong>easily those precious tokens could end up in the wrong hands?</strong> In this article, we’re going to dive into the surprisingly simple yet dangerous world of <strong>Man-in-the-Middle (MITM) attacks</strong> and see exactly <strong>how hackers could nab your tokens</strong> — and how to keep your app safe!</p><blockquote>⚠️ <strong>Spoiler:</strong> This isn’t just theory. We’ll actually set up a MITM environment and try to intercept a request to another FastAPI backend app — also developed by me and deployed on a server — and store its authentication token in Redis. And don’t worry, this is strictly for educational purposes… unless you’re planning to put on a black hat (just kidding, please don’t!).</blockquote><p><strong>What You Need to Know About MITM Attacks</strong></p><p>Ever heard of a “Man-in-the-Middle”? No, it’s not that awkward person at a dinner party. In the tech world, it’s a type of cyberattack where someone secretly intercepts communication between two parties. Imagine logging into your favourite app, and someone’s there, reading every message you send. That’s MITM in a nutshell.</p><p>MITM attacks are a real threat for <strong>both web and mobile applications</strong>. Hackers can intercept API calls and grab <strong>authentication tokens</strong> if the network isn’t secure. The best part? All they need is for your app’s requests to flow through their proxy server, and suddenly, they’re holding your user’s access tokens like candy.</p><h3><strong>Project Highlights</strong></h3><p>In this project, we’ll explore both sides of the fence: how to build a secure backend and how to see where potential vulnerabilities could be exploited. Here’s what we set up:</p><p><strong>1. FastAPI Backend with Async PostgreSQL</strong></p><p>This backend application is built using FastAPI with an async PostgreSQL setup. It includes:</p><blockquote>• <strong>Asynchronous CRUD operations</strong> to handle user creation, retrieval, and authentication.</blockquote><blockquote>• <strong>JWT-based authentication</strong>: It issues tokens when users log in, just like a real-world app.</blockquote><blockquote>• <strong>Comprehensive boilerplate</strong> that developers can use to kickstart their projects. <a href="https://github.com/akutayural/async-fastapi-base-setup"><strong>Github Link</strong></a></blockquote><blockquote>• <strong>Documentation via Swagger</strong>: Hosted live <a href="https://user-auth-crru.onrender.com/docs#/"><strong>here</strong></a>. If the link doesn’t work try again 2 minutes later. Free hosting :)</blockquote><p>Think of this as the safe part of our experiment. It’s a real-world example of a secure backend with tokens, which are vulnerable if the network isn’t protected.</p><p><strong>2. Python Script MITM Proxy Server with Redis</strong></p><p>For the “attack” side of things, we’ve developed a Python script using <strong>mitmproxy</strong> to intercept specific API requests, like <em>/oauth/token</em> or /auth/token, and log the tokens. Here’s what it does:</p><blockquote>• <strong>Intercepts and listens to HTTP requests</strong>: Captures the token responses.</blockquote><blockquote>• <strong>Stores tokens in Redis</strong>: Uses Redis to stash tokens for “later use” (in a secure setup, this would be unauthorized access).</blockquote><blockquote>• <strong>Logs every step</strong>: Events are logged to keep track of interceptions, token storage, and more.</blockquote><p>You can explore the MITM proxy code on GitHub <a href="https://github.com/akutayural/Authentication-Token-Interception-MITM"><strong>here</strong></a>.</p><h3><strong>How It Works: Setting Up and Running the Attack</strong></h3><p><strong>Step 1: Setting Up the FastAPI Backend</strong></p><blockquote>1. <strong>Install FastAPI and PostgreSQL</strong>: The FastAPI backend setup includes JWT authentication, a User table, and standard CRUD endpoints.</blockquote><blockquote>2. <strong>Run the FastAPI App</strong>: Start the FastAPI server locally or deploy it to a host (we used Render) to make it publicly accessible.</blockquote><blockquote>3. <strong>Test Your Backend</strong>: Use the Swagger documentation <a href="https://user-auth-crru.onrender.com/docs#/"><strong>here</strong></a> to test authentication and CRUD functionalities.</blockquote><p><strong>Step 2: Configuring MITM Proxy Script</strong></p><blockquote>1. <strong>Install mitmproxy</strong>: You’ll need mitmproxy to intercept requests. Set it up and configure it as a proxy.</blockquote><blockquote>2. <strong>Set Up Redis</strong>: The MITM script requires Redis to store the captured tokens.</blockquote><blockquote>3. <strong>Run the MITM Script</strong>: Start mitmproxy with the custom script. When running, this script captures specific token requests (e.g., /oauth/token) and saves the tokens in Redis.</blockquote><p>Start the mitm script by the below code:</p><blockquote>mitmproxy — set console_eventlog_verbosity=debug -s path/to/your/proxy_server.py — set proxyauth=any</blockquote><p><strong>Step 3: Simulating a Token Interception</strong></p><p>• Send a request to the backend FastAPI server using a proxy set to the MITM proxy server.</p><p>• The MITM script intercepts the /oauth/token request, extracts the token, and stores it in Redis for “later access.”</p><p><strong>Common Ways Hackers Could Exploit MITM Attacks</strong></p><p>To make it real, here’s how hackers might pull this off in different scenarios:</p><p><strong>Fake VPN Apps</strong></p><p>Let’s say you download a free VPN. But wait! This VPN routes your requests through an MITM proxy server that we explained above. Now, whenever you log into an app, your /oauth/token request is intercepted, your access token is stashed, and — bam — they have control of your account for the token’s duration.</p><p><strong>Clone Websites with a MITM Twist</strong></p><p>An attacker might clone the front end of a popular site, then deploy it on a server running a MITM proxy script in the background. Users log in, unaware they’re on a cloned site, and — yep, you guessed it — their tokens are captured.</p><p><strong>Mobile Apps with Weak Encryption</strong></p><p>Mobile apps are easy to decompile, which exposes them to reverse-engineering. An attacker could observe network requests through tools like Burp Suite or mitmproxy, intercept the /oauth/token requests, and redirect them through our MITM script.</p><p><strong>Web Proxy Sites and Proxy Authentication</strong></p><p>Some malicious web proxy sites or browser extensions could route requests through a MITM setup. They monitor, capture, and store authentication tokens for any sites visited. If a token comes in, they can store it for unauthorized access.</p><p><strong>How to Protect Your App Against MITM Attacks?</strong></p><p>By now, we’re pretty convinced that MITM attacks are a risk, right? Here’s what you can do to secure your app:</p><blockquote>1. <strong>Use HTTPS Everywhere</strong>: Encrypting traffic helps protect data end-to-end. No more easy token snatches!</blockquote><blockquote>2. <strong>Enable Short Token Expiry with Refresh Tokens</strong>: Limit the lifespan of each token, reducing its usefulness in case it’s intercepted.</blockquote><blockquote>3. <strong>Implement IP and Device Monitoring</strong>: Track each token’s IP and device usage. If a login token is suddenly used from a new location or device, alert the user immediately to verify if it’s really them.</blockquote><blockquote>4. <strong>Enable IP and Device Monitoring</strong>: By tracking where tokens are used, you can detect unauthorized access faster.</blockquote><blockquote>5. <strong>Consider Using Certificate Pinning</strong>: Especially for mobile apps, SSL certificate pinning helps prevent interception by ensuring requests are only sent to trusted servers.</blockquote><blockquote>6. <strong>Limit Token Permissions</strong>: Give each token only the permissions it needs (e.g., read-only for certain APIs) to minimize exposure.</blockquote><p><strong>Final Thoughts: Build Securely and Stay Alert</strong></p><blockquote>MITM attacks aren’t just hypotheticals—they&#39;re real-world threats. Understanding how these attacks work gives you the insight to build more resilient, secure applications. Remember: securing tokens isn’t just a nice-to-have; it’s essential.</blockquote><p>Want to see the code in action? Check out the <strong>FastAPI boilerplate project</strong> <a href="https://github.com/akutayural/async-fastapi-base-setup"><strong>here</strong></a>, and dive into the <strong>MITM authentication token steal setup</strong> <a href="https://github.com/akutayural/Authentication-Token-Interception-MITM"><em>here</em></a>.</p><p>Build <strong>smart</strong>, stay <strong>secure</strong>, and <strong>keep learning</strong>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3401d42a181" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>