<?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 Osirus Djodji on Medium]]></title>
        <description><![CDATA[Stories by Osirus Djodji on Medium]]></description>
        <link>https://medium.com/@osirusdjodji?source=rss-54d2da3e9958------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pFWgecwFM2DPM70VrVJ53g.jpeg</url>
            <title>Stories by Osirus Djodji on Medium</title>
            <link>https://medium.com/@osirusdjodji?source=rss-54d2da3e9958------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 08:02:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@osirusdjodji/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[Laravel Rust: How Laravel Is Embracing Async, Performance, and a New Era of Backend Development]]></title>
            <link>https://blog.devgenius.io/laravel-rust-how-laravel-is-embracing-async-performance-and-a-new-era-of-backend-development-109d53a31256?source=rss-54d2da3e9958------2</link>
            <guid isPermaLink="false">https://medium.com/p/109d53a31256</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[laravel-rust]]></category>
            <dc:creator><![CDATA[Osirus Djodji]]></dc:creator>
            <pubDate>Wed, 02 Dec 2026 12:28:30 GMT</pubDate>
            <atom:updated>2026-12-02T12:28:30.299Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X-YE8dK5dSU9Coiv.png" /></figure><p>For years, Laravel has been one of the most productive ways to build modern backend applications with PHP.</p><p>It gives developers an elegant syntax, a powerful ORM, built-in authentication, queues, events, notifications, testing tools, and almost everything needed to build a production-ready application.</p><p>But what happens when you take that same philosophy and combine it with Rust?</p><p>That is exactly what Laravel is exploring with <strong>Laravel Rust</strong>, a new full-stack web framework that brings Laravel’s conventions and developer experience to the Rust ecosystem.</p><p>And there is one major architectural difference worth paying attention to:</p><p><strong>Laravel Rust is asynchronous by design.</strong></p><p>This is not simply Laravel PHP with a different syntax. It is a new framework built around Rust’s type system, compiled execution, and an asynchronous runtime.</p><p>Let’s look at what has changed, why async matters, and what this could mean for backend developers.</p><h3>1. Laravel Rust Is More Than a PHP Rewrite</h3><p>The first thing to understand is that Laravel Rust is not a port of the existing PHP framework.</p><p>It is a new framework written in idiomatic Rust, designed to preserve the philosophy that made Laravel popular: developers should spend more time building applications and less time assembling infrastructure.</p><p>It already includes many familiar building blocks:</p><ul><li>Routing and middleware</li><li>Authentication and sessions</li><li>Database models and relationships</li><li>Migrations and query building</li><li>Typed validation</li><li>Queues and background jobs</li><li>Mail and notifications</li><li>Events and broadcasting</li><li>WebSockets</li><li>Durable workflows</li><li>Inertia support</li><li>Automated testing</li></ul><p>The framework is built on two important technologies:</p><p><strong>Axum</strong> handles the HTTP application layer, including routing and request handling.</p><p><strong>Tokio</strong> provides the asynchronous runtime responsible for scheduling tasks and managing non-blocking I/O.</p><p>The combination gives Laravel Rust a foundation designed for high concurrency without sacrificing the structured development experience Laravel developers expect.</p><p>The framework is currently in beta, so its APIs and ecosystem are still evolving.</p><h3>2. The Biggest Difference: Async Is Built Into the Architecture</h3><p>To understand why this matters, let’s look at how a typical Laravel PHP application handles requests.</p><h3>The traditional PHP request lifecycle</h3><p>Consider a conventional Laravel controller:</p><pre>public function show(int $id)<br>{<br>    $user = User::findOrFail($id);<br><br>    $response = Http::get(<br>        &quot;https://api.example.com/users/{$id}&quot;<br>    );<br><br>    return response()-&gt;json([<br>        &#39;user&#39; =&gt; $user,<br>        &#39;external&#39; =&gt; $response-&gt;json(),<br>    ]);<br>}</pre><p>The application retrieves a user from the database, calls an external API, waits for the response, and then returns the result.</p><p>In a conventional PHP-FPM deployment, the worker handling that request remains occupied while the synchronous operations complete.</p><p>This model is perfectly capable of powering production applications. PHP has mature scaling strategies, including worker pools, queues, caching, and horizontal scaling.</p><p>However, when an application spends a significant amount of time waiting for databases or external services, the number of concurrent requests it can handle becomes closely tied to the available workers and infrastructure.</p><h3>The Laravel Rust approach</h3><p>Laravel Rust uses asynchronous handlers.</p><p>In Rust, an asynchronous function is declared using async, while .await marks an operation that may suspend until its result is available.</p><p>For example:</p><pre>pub async fn store(<br>    Authenticated(user): Authenticated&lt;User&gt;,<br>    Valid(input): Valid&lt;StorePost&gt;,<br>) -&gt; laravel::Result&lt;Redirect&gt; {<br>    let post = create!(Post {<br>        user: &amp;user,<br>        ..input<br>    }).await?;<br><br>    Ok(redirect!(show, &amp;post))<br>}</pre><p>Notice that the database operation is awaited.</p><p>The important detail is what happens during that wait.</p><p>Instead of blocking the runtime thread until the operation finishes, the asynchronous task can suspend. Tokio can then schedule other tasks on the available runtime threads.</p><p>Imagine this sequence:</p><ol><li>Request A starts a database query.</li><li>Request A suspends while waiting for the database.</li><li>Request B arrives and gets scheduled.</li><li>Request C performs an external HTTP request.</li><li>The database result for Request A becomes available.</li><li>Request A resumes execution.</li></ol><p>The runtime can keep making progress on other work while individual operations wait for I/O.</p><p>This is the real advantage of async: <strong>better resource utilization when an application has many concurrent I/O-bound operations.</strong></p><p>It does not automatically make a single database query or HTTP request faster. It changes how efficiently the application handles waiting.</p><h3>3. Async Concurrency: Doing More Than One Thing at a Time</h3><p>One of the most interesting parts of Laravel Rust is that asynchronous execution goes beyond simply adding .await to database queries.</p><p>The framework also provides helpers for running independent operations concurrently.</p><p>Imagine building an API endpoint that returns dashboard statistics.</p><p>You need:</p><ul><li>The total number of users.</li><li>The total number of orders.</li><li>The total number of payments.</li></ul><p>A sequential implementation would wait for each query before starting the next one.</p><pre>let users = db::table(&quot;users&quot;).count().await?;<br>let orders = db::table(&quot;orders&quot;).count().await?;<br>let payments = db::table(&quot;payments&quot;).count().await?;</pre><p>Each operation is asynchronous, but the queries are still executed one after another.</p><p>Laravel Rust provides task::try_join! to execute independent asynchronous operations concurrently.</p><pre><br>use laravel::db;<br>use laravel::prelude::*;<br>use laravel::task;<br>use serde_json::json;<br><br>pub async fn show() -&gt; laravel::Result&lt;Json&lt;serde_json::Value&gt;&gt; {<br>    let (users, orders) = task::try_join!(<br>        db::table(&quot;users&quot;).count(),<br>        db::table(&quot;orders&quot;).count(),<br>    )?;<br><br>    Ok(Json(json!({<br>        &quot;users&quot;: users,<br>        &quot;orders&quot;: orders<br>    })))<br>}</pre><p>Instead of waiting for the first query to finish before starting the second, both operations can make progress concurrently.</p><p>This is particularly useful for:</p><ul><li>Analytics dashboards</li><li>API aggregation endpoints</li><li>External service integrations</li><li>Reporting systems</li><li>Applications that combine data from multiple sources</li></ul><p>The same module also provides other useful primitives:</p><ul><li>task::select! to race competing asynchronous operations.</li><li>task::spawn_blocking to run blocking or CPU-intensive work outside the async execution threads.</li><li>task::background to schedule lightweight background tasks.</li></ul><p>This is where async becomes an architectural advantage rather than just a language feature.</p><p><strong>1. HTTP Handlers</strong></p><p>Requests can suspend while waiting for I/O, allowing the runtime to process other tasks instead of keeping a thread occupied.</p><p><strong>2. Database Queries</strong></p><p>Database operations can execute asynchronously without blocking the runtime’s execution threads.</p><p><strong>3. HTTP Client</strong></p><p>External API calls can run concurrently, making it easier to integrate payment gateways, authentication providers, and third-party services.</p><p><strong>4. Redis</strong></p><p>Cache operations use asynchronous I/O, helping applications retrieve and store data without unnecessarily blocking other tasks.</p><p><strong>5. Queues</strong></p><p>Background jobs work with the asynchronous runtime, allowing applications to process tasks efficiently.</p><p><strong>6. S3 and SQS</strong></p><p>Cloud storage and messaging operations can use asynchronous I/O when interacting with external services.</p><p><strong>7. WebSockets</strong></p><p>Connections can be managed asynchronously, allowing applications to support real-time communication without requiring a dedicated blocking thread for every waiting connection.</p><p>There is an important distinction here.</p><p>Not every operation is naturally asynchronous. Password hashing, for example, is CPU-intensive. Local disk operations may also involve blocking APIs.</p><p>Laravel Rust handles certain blocking operations by offloading them to Tokio’s blocking thread pool.</p><p>This matters because running blocking work directly on an async runtime thread can prevent other tasks from making progress.</p><p>The framework’s architecture is designed to keep those two execution models from interfering unnecessarily.</p><h3>5. Durable Workflows: Beyond Traditional Background Jobs</h3><p>Laravel developers are already familiar with queues and background jobs.</p><p>But Laravel Rust introduces another interesting concept: durable workflows.</p><p>Consider a customer onboarding process:</p><ol><li>A user creates an account.</li><li>The application sends a welcome email.</li><li>The workflow waits three days.</li><li>It checks whether the user has created a project.</li><li>If not, it sends additional onboarding information.</li></ol><p>With traditional queues, developers might implement this using delayed jobs, status columns, chained tasks, and scheduled commands.</p><p>Laravel Rust allows developers to express this kind of process as an asynchronous workflow.</p><pre>use laravel::queue::Queueable;<br>use laravel::time::ToSpan;<br>use laravel::workflow::{Run, workflow};<br><br>#[derive(Queueable)]<br>pub struct OnboardUser {<br>    pub user_id: i64,<br>}<br><br>#[workflow]<br>impl OnboardUser {<br>    async fn handle(self, run: &amp;Run) -&gt; laravel::Result&lt;()&gt; {<br>        run.step(<br>            &quot;send welcome email&quot;,<br>            self.send_welcome_email()<br>        ).await?;<br><br>        run.sleep(3.days()).await?;<br><br>        if run.step(<br>            &quot;count projects&quot;,<br>            self.count_projects()<br>        ).await? == 0 {<br>            run.step(<br>                &quot;send tips&quot;,<br>                self.send_tips()<br>            ).await?;<br>        }<br><br>        Ok(())<br>    }<br>}<br><br></pre><p>The interesting part is that the workflow can persist completed steps and resume execution after waiting periods or application restarts.</p><p>A workflow waiting for three days does not need to occupy a worker during that entire period.</p><p>It resumes when the next step is due.</p><p>This is useful for:</p><ul><li>Customer onboarding</li><li>Payment follow-ups</li><li>Subscription lifecycle management</li><li>Approval processes</li><li>Multi-step integrations</li><li>Long-running business operations</li></ul><p>It takes background processing beyond the simple concept of dispatching a job and waiting for it to finish.</p><h3>6. Rust Brings Compile-Time Guarantees to Application Development</h3><p>Performance is only one part of the Laravel Rust story.</p><p>Another major difference is Rust’s type system.</p><p>In traditional Laravel PHP, developers rely on PHP types, validation rules, runtime checks, and tests to protect application behavior.</p><p>Laravel Rust goes further by using Rust’s compiler to verify more aspects of an application before it runs.</p><p>For example, request data can be described using a typed structure:</p><pre>use laravel::prelude::*;<br><br>use crate::models::Post;<br><br>#[laravel::input(fills = Post)]<br>#[validate(authenticated)]<br>pub struct StorePost {<br>    #[validate(required, max_length = 255)]<br>    pub title: String,<br><br>    #[validate(required)]<br>    pub body: String,<br>}<br><br></pre><p>The framework uses this structure to define the expected input and its validation rules.</p><p>There are several interesting guarantees:</p><ul><li>Input structures explicitly declare authorization requirements.</li><li>Validation happens before the handler executes.</li><li>Model fields and relationships are represented through typed APIs.</li><li>Database column references can be checked at compile time.</li><li>Sensitive values can use dedicated types to reduce accidental exposure.</li></ul><p>For example, Laravel Rust provides Password and PasswordHash types to help prevent plain-text passwords and password hashes from being exposed accidentally in logs or serialized responses.</p><p>This approach is particularly valuable in large applications where correctness and maintainability matter as much as raw performance.</p><p>The compiler becomes another layer of protection.</p><h3>7. What Do the Performance Numbers Actually Tell Us?</h3><p>Laravel’s announcement came with internal benchmarks comparing Laravel Rust and Laravel PHP.</p><p>The headline figure is impressive:</p><p><strong>1,774 requests per second for Laravel Rust versus 97 requests per second for Laravel PHP</strong> in the best qualifying 10-second window of the published test.</p><p>The benchmark used a read-only workload, with the same application functionality and instance size, deployed on Laravel Cloud.</p><p>At a steady load of 50 requests per second, the reported CPU usage was approximately:</p><ul><li>Laravel Rust: 4.2%</li><li>Laravel PHP: 52.4%</li></ul><p>The benchmark also measured memory consumption, latency, build times, and wake-from-sleep performance.</p><p>These figures are worth paying attention to, but they need context.</p><p>The benchmark application was deliberately simple, with two read-oriented API endpoints and a small MySQL dataset. It was designed to compare framework overhead and throughput under a controlled workload.</p><p>It does not mean every Laravel Rust application will automatically be 18 times faster than its PHP equivalent.</p><p>Real-world performance depends on database queries, application logic, external dependencies, caching, hardware, and workload patterns.</p><p>There is also a trade-off.</p><p>Rust applications must be compiled. In the published Laravel Cloud benchmark, the median cold build time was approximately three minutes for Laravel Rust, compared with 27 seconds for Laravel PHP.</p><p>Incremental local development builds were much faster, but compilation remains an important consideration.</p><p>The lesson is simple: benchmark your actual workload rather than adopting a framework based on a headline number.</p><h3>8. Should Laravel PHP Developers Move to Rust?</h3><p>Not necessarily.</p><p>Laravel Rust is a new framework, currently in beta. Its ecosystem and production practices will need time to mature.</p><p>An existing Laravel PHP application cannot simply switch runtimes and continue working unchanged.</p><p>Moving to Laravel Rust may require:</p><ul><li>Rewriting application logic in Rust.</li><li>Replacing or adapting PHP packages.</li><li>Learning ownership, borrowing, and lifetimes.</li><li>Updating deployment and build pipelines.</li><li>Adjusting testing and monitoring practices.</li><li>Training developers to work with asynchronous Rust.</li></ul><p>But this does not mean Laravel PHP is going away.</p><p>Laravel’s creator has made it clear that Laravel PHP will continue to be developed.</p><p>The two frameworks can serve different needs.</p><p>Laravel PHP remains a mature choice for existing applications and teams with established PHP expertise.</p><p>Laravel Rust may be worth evaluating for new services where high concurrency, resource efficiency, and compile-time guarantees are important.</p><p>There is also an interesting possibility: using both frameworks within the same broader architecture, rather than treating the decision as an all-or-nothing migration.</p><h3>9. What Should Developers Learn First?</h3><p>For developers coming from Laravel PHP, the learning curve is not just about understanding new framework APIs.</p><p>It requires becoming comfortable with Rust itself.</p><p>A practical learning path would look like this:</p><p><strong>1. Learn Rust fundamentals</strong></p><p>Start with ownership, borrowing, lifetimes, structs, enums, traits, and error handling.</p><p><strong>2. Understand async Rust</strong></p><p>Learn how async, .await, futures, and Tokio tasks work. Understand the difference between concurrency and parallelism.</p><p><strong>3. Explore Laravel Rust conventions</strong></p><p>Study routing, middleware, models, typed validation, authentication, and database queries.</p><p><strong>4. Understand concurrent operations</strong></p><p>Practice using task::try_join!, task::select!, and task::spawn_blocking.</p><p><strong>5. Build a complete application</strong></p><p>Create a small API with authentication, database models, background jobs, and automated tests.</p><p><strong>6. Learn production deployment</strong></p><p>Understand compilation, connection pools, observability, blocking operations, and resource management.</p><p>The goal is not to become a Rust expert overnight. It is to understand enough of the language and runtime to build applications safely and efficiently.</p><h3>Conclusion: Laravel Is Expanding Its Definition of Backend Development</h3><p>Laravel Rust is an interesting evolution of the Laravel philosophy.</p><p>It brings together the productivity of a batteries-included framework, the performance characteristics of compiled Rust applications, and an asynchronous architecture designed for modern backend workloads.</p><p>The biggest change is not simply that Laravel now supports another language.</p><p>It is that asynchronous execution becomes a foundation across the application stack.</p><p>Database queries, external HTTP calls, queues, WebSockets, and concurrent tasks can all make progress without unnecessarily blocking the runtime.</p><p>For developers, this opens a new way to think about backend architecture.</p><p>Laravel PHP is not disappearing, and Laravel Rust is not an automatic replacement for every PHP application. But the introduction of a Rust-native framework gives developers another option when performance, concurrency, and compile-time safety become important requirements.</p><p><strong>The real question is no longer whether Laravel can embrace Rust. It is how far the Laravel philosophy can go when the language and runtime are no longer limited to PHP.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=109d53a31256" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/laravel-rust-how-laravel-is-embracing-async-performance-and-a-new-era-of-backend-development-109d53a31256">Laravel Rust: How Laravel Is Embracing Async, Performance, and a New Era of Backend Development</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Flask Tricks to Write Cleaner, Smarter, and More Efficient Python Applications]]></title>
            <link>https://medium.com/django-unleashed/5-flask-tricks-to-write-cleaner-smarter-and-more-efficient-python-applications-168c5c70a630?source=rss-54d2da3e9958------2</link>
            <guid isPermaLink="false">https://medium.com/p/168c5c70a630</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[python-flask]]></category>
            <dc:creator><![CDATA[Osirus Djodji]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 12:00:41 GMT</pubDate>
            <atom:updated>2026-11-04T12:00:41.287Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IMte4Y6rmFPBjdBi.png" /></figure><p>Flask is one of Python’s most flexible web frameworks. Its lightweight philosophy makes it incredibly easy to get started, but that simplicity can become a challenge as your application grows.</p><p>A small project might begin with a single app.py file containing a few routes. A few weeks later, you have authentication, database models, API endpoints, background jobs, configuration settings, and several integrations.</p><p>Suddenly, that lightweight application isn’t so lightweight anymore.</p><p>The good news is that Flask already provides powerful features and patterns to help you manage this complexity.</p><p>You don’t necessarily need another framework or a complicated architecture. Sometimes, you just need to use Flask a little smarter.</p><p>Here are five practical tricks that can significantly improve the way you build Flask applications.</p><h3>1. Use Application Factories Instead of Global App Instances</h3><p>One of the most useful Flask patterns is the application factory.</p><p>A common beginner approach looks like this:</p><pre>from flask import Flask<br><br>app = Flask(__name__)<br><br>@app.route(&quot;/&quot;)<br>def home():<br>    return {&quot;message&quot;: &quot;Hello Flask&quot;}</pre><p>This works perfectly for small applications.</p><p>However, creating your Flask application globally can make testing, configuration management, and multiple application instances more difficult.</p><p>A better approach is to create your application through a function.</p><pre>from flask import Flask<br><br>def create_app(config_object=None):<br>    app = Flask(__name__)<br><br>    if config_object:<br>        app.config.from_object(config_object)<br><br>    return app</pre><p>Your application can now be initialized differently depending on the environment.</p><p>For example:</p><pre>app = create_app(&quot;config.DevelopmentConfig&quot;)</pre><p>Or:</p><pre>app = create_app(&quot;config.ProductionConfig&quot;)</pre><h3>Why is this useful?</h3><ul><li>Easier automated testing.</li><li>Separate development and production configurations.</li><li>Cleaner initialization of extensions.</li><li>Better support for modular applications.</li></ul><p>It also makes your project easier to maintain as it grows.</p><p>My recommendation: Start using application factories early. Refactoring a large application to adopt this pattern later can be unnecessarily painful.</p><h3>2. Organize Your Routes with Blueprints</h3><p>Another common mistake is keeping every route inside one Python file.</p><p>Imagine an application with:</p><ul><li>Authentication</li><li>Users</li><li>Products</li><li>Payments</li><li>Notifications</li><li>Reports</li></ul><p>Putting everything into app.py quickly becomes difficult to manage.</p><p>Flask Blueprints solve this problem.</p><p>Create a separate blueprint for each functional module.</p><p>For example:</p><pre>project/<br>│<br>├── app/<br>│   ├── __init__.py<br>│   │<br>│   ├── auth/<br>│   │   └── routes.py<br>│   │<br>│   ├── users/<br>│   │   └── routes.py<br>│   │<br>│   ├── products/<br>│   │   └── routes.py<br>│   │<br>│   └── reports/<br>│       └── routes.py<br>│<br>└── run.py</pre><p>A simple blueprint:</p><pre>from flask import Blueprint, jsonify<br><br>products_bp = Blueprint(<br>    &quot;products&quot;,<br>    __name__,<br>    url_prefix=&quot;/api/products&quot;<br>)<br><br>@products_bp.route(&quot;/&quot;, methods=[&quot;GET&quot;])<br>def list_products():<br>    return jsonify({&quot;message&quot;: &quot;Product list&quot;})</pre><p>Register it inside your application factory:</p><pre>def create_app():<br>    app = Flask(__name__)<br><br>    from app.products.routes import products_bp<br><br>    app.register_blueprint(products_bp)<br><br>    return app</pre><p>Now your endpoint becomes:</p><pre>GET /api/products/</pre><h3>The real benefit</h3><p>Blueprints allow you to separate responsibilities without introducing unnecessary complexity.</p><p>Each module can manage its own routes, serializers, services, and business logic.</p><p>Your application becomes easier to navigate, test, and extend.</p><h3>3. Initialize Extensions Once, Then Reuse Them Everywhere</h3><p>Flask has a rich extension ecosystem.</p><p>You might use:</p><ul><li>Flask-SQLAlchemy for database management.</li><li>Flask-Migrate for database migrations.</li><li>Flask-JWT-Extended for authentication.</li><li>Flask-Caching for caching.</li><li>Flask-Mail for email delivery.</li></ul><p>A common mistake is initializing extensions directly with the application instance inside multiple modules.</p><p>Instead, use the init_app() pattern.</p><p>First, create an extensions module:</p><pre>from flask_sqlalchemy import SQLAlchemy<br>from flask_migrate import Migrate<br>from flask_jwt_extended import JWTManager<br><br>db = SQLAlchemy()<br>migrate = Migrate()<br>jwt = JWTManager()</pre><p>Then initialize everything in your application factory:</p><pre>from flask import Flask<br>from app.extensions import db, migrate, jwt<br><br>def create_app():<br>    app = Flask(__name__)<br><br>    app.config.from_object(&quot;config.Config&quot;)<br><br>    db.init_app(app)<br>    migrate.init_app(app, db)<br>    jwt.init_app(app)<br><br>    return app</pre><p>Notice something important: the extensions are created independently of the Flask application.</p><p>This allows the same extension instances to be initialized with different application instances.</p><h3>Why does this matter?</h3><p>It improves:</p><ul><li>Testability.</li><li>Reusability.</li><li>Application initialization.</li><li>Separation of concerns.</li></ul><p>It also prevents circular imports, one of the most frustrating problems in growing Flask projects.</p><h3>4. Centralize Error Handling Instead of Repeating It Everywhere</h3><p>Let’s say you have several endpoints that interact with your database.</p><p>You might repeatedly write:</p><pre>try:<br>    # Business logic<br>    return {&quot;success&quot;: True}<br><br>except Exception as e:<br>    return {&quot;error&quot;: str(e)}, 500</pre><p>This quickly becomes repetitive and inconsistent.</p><p>A better approach is to centralize your error handling.</p><p>Flask provides error handlers that allow you to define how exceptions should be returned.</p><pre>from flask import jsonify<br><br>def register_error_handlers(app):<br><br>    @app.errorhandler(404)<br>    def not_found(error):<br>        return jsonify({<br>            &quot;success&quot;: False,<br>            &quot;message&quot;: &quot;Resource not found&quot;<br>        }), 404<br><br>    @app.errorhandler(500)<br>    def internal_error(error):<br>        return jsonify({<br>            &quot;success&quot;: False,<br>            &quot;message&quot;: &quot;Internal server error&quot;<br>        }), 500</pre><p>Register them in your factory:</p><pre>def create_app():<br>    app = Flask(__name__)<br><br>    register_error_handlers(app)<br><br>    return app</pre><p>You can also define custom exceptions:</p><pre>class BusinessException(Exception):<br>    def __init__(self, message, status_code=400):<br>        self.message = message<br>        self.status_code = status_code</pre><p>Then handle them consistently.</p><pre>@app.errorhandler(BusinessException)<br>def handle_business_exception(error):<br>    return {<br>        &quot;success&quot;: False,<br>        &quot;message&quot;: error.message<br>    }, error.status_code</pre><h3>One important security detail</h3><p>Never expose raw exception messages, database errors, stack traces, or internal implementation details to clients in production.</p><p>Log technical details on the server and return a safe, predictable error response.</p><p>Your frontend will thank you for consistent response structures, and debugging becomes much easier.</p><h3>5. Use Flask’s Test Client Before Reaching for External Testing Tools</h3><p>Testing is often postponed until an application becomes difficult to maintain.</p><p>But Flask already includes a useful testing client that allows you to simulate HTTP requests without starting an actual web server.</p><p>For example:</p><pre>def test_home_endpoint(client):<br>    response = client.get(&quot;/&quot;)<br><br>    assert response.status_code == 200<br>    assert response.json[&quot;message&quot;] == &quot;Hello Flask&quot;</pre><p>You can also test POST requests:</p><pre>def test_create_product(client):<br>    response = client.post(<br>        &quot;/api/products/&quot;,<br>        json={<br>            &quot;name&quot;: &quot;Wireless Mouse&quot;,<br>            &quot;price&quot;: 25<br>        }<br>    )<br><br>    assert response.status_code == 201</pre><p>With pytest, you can create a reusable fixture:</p><pre>import pytest<br><br>from app import create_app<br><br>@pytest.fixture<br>def app():<br>    app = create_app({<br>        &quot;TESTING&quot;: True,<br>        &quot;SQLALCHEMY_DATABASE_URI&quot;: &quot;sqlite://&quot;<br>    })<br><br>    yield app<br><br>@pytest.fixture<br>def client(app):<br>    return app.test_client()</pre><p>Now your tests can reuse the same application setup.</p><h3>What should you test?</h3><p>At minimum:</p><ul><li>Successful requests.</li><li>Invalid input.</li><li>Authentication failures.</li><li>Permission restrictions.</li><li>Missing resources.</li><li>Database operations.</li><li>Error responses.</li></ul><p>Testing early helps identify architectural problems before they become expensive to fix.</p><h3>Bonus: A Small Configuration Trick That Makes a Big Difference</h3><p>Never hardcode production secrets inside your application.</p><p>Instead of:</p><pre>app.config[&quot;SECRET_KEY&quot;] = &quot;my-secret-key&quot;</pre><p>Use environment variables:</p><pre>import os<br><br>class Config:<br>    SECRET_KEY = os.environ.get(&quot;SECRET_KEY&quot;)<br>    SQLALCHEMY_DATABASE_URI = os.environ.get(<br>        &quot;DATABASE_URL&quot;<br>    )</pre><p>This makes your application easier to deploy across different environments and prevents sensitive configuration from being committed to source control.</p><h3>What About Async in Flask?</h3><p>Flask supports asynchronous view functions, provided the async extra is installed:</p><pre>pip install &quot;flask[async]&quot;</pre><p>You can then write:</p><pre>@app.get(&quot;/external-data&quot;)<br>async def external_data():<br>    result = await fetch_external_data()<br>    return result</pre><p>This can be useful when performing concurrent I/O operations, such as calling multiple external APIs.</p><p>However, remember that Flask remains a WSGI framework. An async view still occupies one worker for its request lifecycle. Async doesn’t automatically increase the number of simultaneous requests your application can handle.</p><p>For workloads that are heavily asynchronous, evaluate whether an ASGI-first framework such as Quart or FastAPI would be more appropriate.</p><h3>Conclusion</h3><p>Flask’s simplicity is one of its greatest strengths, but writing a few routes is only the beginning of building a maintainable application.</p><p>These five techniques can make a real difference:</p><ol><li>Application Factories — Build applications that are easier to configure and test.</li><li>Blueprints — Organize routes into reusable modules.</li><li>Extension Initialization — Keep dependencies clean and avoid circular imports.</li><li>Centralized Error Handling — Make API responses consistent and secure.</li><li>Automated Testing — Catch problems before they reach production.</li></ol><p>You don’t need to implement everything at once.</p><p>Start with application factories and blueprints, then gradually introduce better configuration, error handling, and testing practices.</p><p>The objective isn’t to make Flask more complicated.</p><p>It’s to make your Flask applications easier to build, understand, and maintain as they grow.</p><p>A lightweight framework deserves a thoughtful architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=168c5c70a630" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-unleashed/5-flask-tricks-to-write-cleaner-smarter-and-more-efficient-python-applications-168c5c70a630">5 Flask Tricks to Write Cleaner, Smarter, and More Efficient Python Applications</a> was originally published in <a href="https://medium.com/django-unleashed">Django Unleashed</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 DRF Hacks to Build APIs Faster (Without Sacrificing Code Quality)]]></title>
            <link>https://medium.com/django-unleashed/5-drf-hacks-to-build-apis-faster-without-sacrificing-code-quality-214660ecefea?source=rss-54d2da3e9958------2</link>
            <guid isPermaLink="false">https://medium.com/p/214660ecefea</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[Osirus Djodji]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 14:12:48 GMT</pubDate>
            <atom:updated>2026-10-28T14:12:48.911Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*x5CBp7Q5pbCU4_Wj.png" /></figure><p>Django REST Framework is already a powerful toolkit for building APIs with Python. But if you’ve worked on a few production projects, you know that writing endpoints is rarely the hardest part.</p><p>The real challenge is building them quickly while keeping your code maintainable, secure, and performant.</p><p>Over time, I’ve found that some of the biggest productivity improvements don’t come from adding more libraries or introducing complex architectures. They come from using DRF’s existing features more effectively.</p><p>Here are five practical hacks to help you build Django REST Framework APIs faster, reduce repetitive code, and avoid common development bottlenecks.</p><h3>1. Let ModelViewSet Handle the Repetitive Work</h3><p>How many times have you written separate methods for listing, retrieving, creating, updating, and deleting resources?</p><p>For standard CRUD endpoints, DRF already provides a better solution.</p><p>Instead of writing a custom view for every operation:</p><pre>from rest_framework import viewsets<br>from rest_framework.permissions import IsAuthenticated<br><br>class ProductViewSet(viewsets.ModelViewSet):<br>    queryset = Product.objects.all()<br>    serializer_class = ProductSerializer<br>    permission_classes = [IsAuthenticated]</pre><p>With just a few lines, you get the standard CRUD actions:</p><ul><li>list()</li><li>retrieve()</li><li>create()</li><li>update()</li><li>partial_update()</li><li>destroy()</li></ul><p>Register the ViewSet with a router, and DRF generates the corresponding URL patterns.</p><pre>from rest_framework.routers import DefaultRouter<br><br>router = DefaultRouter()<br>router.register(&quot;products&quot;, ProductViewSet, basename=&quot;product&quot;)<br>urlpatterns = router.urls</pre><p>That’s a lot of boilerplate eliminated.</p><p><strong>The important part:</strong> don’t use ModelViewSet just because it&#39;s convenient. If your resource is read-only, use ReadOnlyModelViewSet. If you need only a few operations, use a more restricted ViewSet.</p><p>The goal is to write less code without exposing unnecessary functionality.</p><h3>2. Use get_queryset() for Dynamic Data Access</h3><p>One of the most common requirements in business APIs is returning different data depending on the authenticated user.</p><p>For example, a customer should see their own orders, while an administrator may need access to all orders.</p><p>Instead of creating separate views:</p><pre>class OrderViewSet(viewsets.ModelViewSet):<br>    serializer_class = OrderSerializer<br>    permission_classes = [IsAuthenticated]<br><br>def get_queryset(self):<br>        user = self.request.user<br>        if user.is_staff:<br>            return Order.objects.all()<br>        return Order.objects.filter(customer=user)</pre><p>Now the endpoint adapts to the current user.</p><p>You can extend the same pattern to support query parameters:</p><pre>def get_queryset(self):<br>    queryset = Order.objects.filter(<br>        customer=self.request.user<br>    )<br>    status = self.request.query_params.get(&quot;status&quot;)<br><br>    if status:<br>        queryset = queryset.filter(status=status)<br><br>    return queryset</pre><p>Your API can now support requests such as:</p><pre>GET /api/orders/?status=pending</pre><p>This pattern is useful for multi-tenant applications, dashboards, reporting APIs, and user-specific resources.</p><p><strong>Security reminder:</strong> never rely on frontend filtering to protect data. Enforce tenant boundaries and object access rules on the backend, and apply the same restrictions to custom actions.</p><h3>3. Use select_related() and prefetch_related() Before Optimizing Anything Else</h3><p>Your API may be perfectly functional and still be painfully slow.</p><p>One common reason is the N+1 query problem.</p><p>Imagine serializing 100 orders, each associated with a customer. If accessing each customer’s details triggers another query, the API may execute far more database queries than necessary.</p><p>A simple fix for foreign-key and one-to-one relationships is:</p><pre>def get_queryset(self):<br>    return (<br>        Order.objects<br>        .select_related(&quot;customer&quot;)<br>        .all()<br>    )</pre><p>For reverse relationships and many-to-many relationships, use prefetch_related():</p><pre>def get_queryset(self):<br>    return (<br>        Order.objects<br>        .select_related(&quot;customer&quot;)<br>        .prefetch_related(&quot;items&quot;)<br>    )</pre><p>The distinction matters:</p><ul><li>select_related() uses SQL joins for single-valued relationships.</li><li>prefetch_related() performs additional queries and joins the results in Python, making it suitable for multi-valued relationships.</li></ul><p>The result? Fewer database round trips and faster responses when your serializers access related objects.</p><p>However, don’t add every relationship blindly. Inspect the serializer, profile the queries, and optimize the relationships actually being used.</p><h3>4. Stop Using One Serializer for Everything</h3><p>A serializer that works perfectly for creating an object may be unnecessarily expensive or expose too much information when listing thousands of objects.</p><p>Consider a product resource.</p><p>A list endpoint might need only:</p><pre>{<br>  &quot;id&quot;: 42,<br>  &quot;name&quot;: &quot;Wireless Keyboard&quot;,<br>  &quot;price&quot;: &quot;35.00&quot;<br>}</pre><p>But a detail endpoint might also need the description, inventory history, and related reviews.</p><p>Instead of forcing one serializer to handle both cases, use different serializers where appropriate:</p><pre>class ProductListSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Product<br>        fields = [&quot;id&quot;, &quot;name&quot;, &quot;price&quot;]<br>class ProductDetailSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Product<br>        fields = [<br>            &quot;id&quot;,<br>            &quot;name&quot;,<br>            &quot;price&quot;,<br>            &quot;description&quot;,<br>            &quot;stock&quot;,<br>        ]</pre><p>Then select the serializer based on the action:</p><pre>def get_serializer_class(self):<br>    if self.action == &quot;list&quot;:<br>        return ProductListSerializer<br>return ProductDetailSerializer</pre><p>This keeps list responses lightweight while allowing detail endpoints to provide richer information.</p><p>It also helps you maintain clear API contracts.</p><p>One important caveat: serializer selection is not a substitute for permissions. Sensitive fields and related data must still be protected appropriately.</p><h3>5. Use Custom Actions Instead of Creating a New View for Every Operation</h3><p>Not every endpoint maps neatly to CRUD.</p><p>Sometimes you need to validate an invoice, approve a request, generate a report, or mark a notification as read.</p><p>You could create a separate API view for every operation. But when the operation belongs naturally to an existing resource, DRF’s @action decorator can keep the API organized.</p><pre>from rest_framework.decorators import action<br>from rest_framework.response import Response<br>from rest_framework import status, viewsets<br><br>class InvoiceViewSet(viewsets.ModelViewSet):<br>    queryset = Invoice.objects.all()<br>    serializer_class = InvoiceSerializer<br>    @action(detail=True, methods=[&quot;post&quot;])<br>    def validate(self, request, pk=None):<br>        invoice = self.get_object()<br>        invoice.status = &quot;validated&quot;<br>        invoice.save(update_fields=[&quot;status&quot;])<br>        return Response(<br>            {&quot;status&quot;: &quot;validated&quot;},<br>            status=status.HTTP_200_OK,<br>        )</pre><p>This exposes an endpoint such as:</p><pre>POST /api/invoices/42/validate/</pre><p>Custom actions are excellent for business operations that don’t fit ordinary CRUD.</p><p>For production code, make sure you also configure appropriate permissions, validate the requested transition, and enforce any required transaction boundaries. If the operation triggers external side effects, consider moving those effects to a background task.</p><p>The result is a clean ViewSet that groups related operations without forcing everything into a generic update() method.</p><h3>Bonus: Make These Five Hacks Work Together</h3><p>The real benefit comes from combining these techniques.</p><p>A well-designed DRF ViewSet can:</p><ul><li>Use ModelViewSet to eliminate repetitive CRUD code.</li><li>Apply user-specific restrictions through get_queryset().</li><li>Optimize database access with select_related() and prefetch_related().</li><li>Return lightweight list serializers.</li><li>Expose dedicated business actions through @action.</li></ul><p>You don’t need a complicated architecture to get these benefits.</p><p>Start with DRF’s built-in capabilities, measure the results, and introduce additional complexity only when the application actually requires it.</p><h3>Final Thoughts</h3><p>Building APIs faster isn’t about writing the fewest lines of code possible.</p><p>It’s about eliminating repetitive work, preventing avoidable performance problems, and creating patterns that remain easy to maintain as your application grows.</p><p>These five techniques are simple, but together they can make a meaningful difference in your daily development workflow.</p><p><strong>Write less boilerplate. Query smarter. Keep your API contracts clear. Let DRF do more of the heavy lifting.</strong></p><p>That’s how you build better APIs without slowing down your development process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=214660ecefea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-unleashed/5-drf-hacks-to-build-apis-faster-without-sacrificing-code-quality-214660ecefea">5 DRF Hacks to Build APIs Faster (Without Sacrificing Code Quality)</a> was originally published in <a href="https://medium.com/django-unleashed">Django Unleashed</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FastAPI Instead of Django REST Framework: When Should You Make the Switch?]]></title>
            <link>https://medium.com/django-unleashed/fastapi-instead-of-django-rest-framework-when-should-you-make-the-switch-f94776f55262?source=rss-54d2da3e9958------2</link>
            <guid isPermaLink="false">https://medium.com/p/f94776f55262</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Osirus Djodji]]></dc:creator>
            <pubDate>Fri, 11 Sep 2026 16:19:09 GMT</pubDate>
            <atom:updated>2026-09-11T16:19:09.736Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*IdxgL2x8sAaKGYq8EhhUTg@2x.jpeg" /></figure><p>Django REST Framework has been one of the most popular choices for building APIs with Python for years.</p><p>It is mature, well documented, and deeply integrated with Django’s ORM, authentication, permissions, serializers, and admin ecosystem.</p><p>But then FastAPI arrived.</p><p>FastAPI quickly became popular for building modern APIs, particularly for microservices, asynchronous applications, AI systems, and high-performance backends.</p><p>This raises an increasingly common question:</p><p>Should I use FastAPI instead of Django REST Framework?</p><p>The answer is more nuanced than simply comparing benchmark numbers.</p><p>The real question is:</p><p>What kind of application are you building?</p><p>Let’s compare the two from an architectural perspective.</p><p>Django REST Framework vs FastAPI</p><p>At first glance, they solve a similar problem.</p><p>Both allow you to build APIs with Python.</p><p>But they come from very different philosophies.</p><p>Django REST Framework extends Django.</p><p>Django</p><pre>Django<br>   │<br>   ├── ORM<br>   ├── Authentication<br>   ├── Admin<br>   ├── Middleware<br>   ├── Models<br>   └── Django REST Framework<br>             │<br>             └── API</pre><p>FastAPI takes a more lightweight approach:</p><pre>FastAPI<br>   │<br>   ├── Pydantic<br>   ├── Starlette<br>   ├── Dependency Injection<br>   └── Your database layer</pre><p>FastAPI doesn’t try to provide an entire application ecosystem.</p><p>And that’s precisely one of its strengths.</p><ol><li>Start With the Architecture</li><li>The biggest difference isn’t performance.</li><li>It’s architecture.</li><li>With Django REST Framework, you’re usually building inside a Django application.</li><li>For example:</li></ol><pre>class Order(models.Model):<br>    customer = models.ForeignKey(Customer, ...)<br>    amount = models.DecimalField(...)<br>    created_at = models.DateTimeField(...)</pre><p>Then your API sits naturally on top:</p><pre>class OrderViewSet(ModelViewSet):<br>    queryset = Order.objects.all()<br>    serializer_class = OrderSerializer</pre><p>You get a lot for free.</p><p>FastAPI doesn’t impose an ORM or application architecture.</p><p>You can choose:</p><ul><li>SQLAlchemy</li><li>SQLModel</li><li>Tortoise ORM</li><li>MongoDB</li><li>PostgreSQL directly</li><li>Another data access layer</li></ul><p>That flexibility is powerful.</p><p>But it also means you have more architectural decisions to make.</p><h3><strong>2. Django REST Framework Wins When Django Is Already Your Platform</strong></h3><p>If you’re already using Django, DRF is often the obvious choice.</p><p>Imagine your application already has:</p><pre>Users<br>Organizations<br>Permissions<br>Admin<br>Models<br>Billing<br>Notifications<br>Background jobs<br>Reports</pre><p>Replacing DRF with FastAPI doesn’t automatically make this application better.</p><p>You would potentially need to reproduce or integrate many existing Django capabilities.</p><p>DRF gives you direct access to:</p><pre>request.user</pre><p>Django permissions:</p><pre>permission_classes = [<br>    IsAuthenticated<br>]</pre><p>And the ORM:</p><pre>Order.objects.filter(<br>    customer=request.user<br>)</pre><p>That’s a tremendous productivity advantage.</p><h3>3. FastAPI Shines in Focused Services</h3><p>Now imagine you’re building a service whose only responsibility is:</p><pre>Receive event<br>      ↓<br>Process data<br>      ↓<br>Return result</pre><p>For example:</p><ul><li>AI inference</li><li>IoT gateway</li><li>Hardware micro-agent</li><li>Machine telemetry</li><li>Image processing</li><li>Real-time data processing</li><li>Internal microservice</li></ul><p>You may not need:</p><ul><li>Django Admin</li><li>Django templates</li><li>Django authentication</li><li>Django’s entire application stack</li><li>FastAPI becomes very attractive.</li></ul><p>A service can be incredibly small:</p><pre>from fastapi import FastAPI<br><br>app = FastAPI()<br><br>@app.get(&quot;/health&quot;)<br>async def health():<br>    return {&quot;status&quot;: &quot;ok&quot;}</pre><p>There is very little framework overhead.</p><h3>4. Async Changes the Conversation</h3><p>This is one of FastAPI’s strongest arguments.</p><p>FastAPI was designed with asynchronous Python applications in mind.</p><pre>@app.get(&quot;/devices&quot;)<br>async def devices():<br>    result = await read_devices()<br>    return result</pre><p>This is particularly useful for workloads involving a lot of I/O:</p><pre>API<br> │<br> ├── External API<br> ├── Database<br> ├── Hardware<br> ├── Message broker<br> └── Another service</pre><p>Instead of blocking while waiting for each operation, asynchronous code can efficiently manage concurrent I/O.</p><p>But there’s an important caveat.</p><p>Async doesn’t automatically make your application faster.</p><p>If your workload is primarily CPU-bound, simply adding async won’t solve the problem.</p><p>And Django has also evolved significantly in its support for asynchronous views and operations.</p><p>So the decision shouldn’t be based on the word “async” alone.</p><h3>5. Performance Isn’t the Only Metric</h3><p>FastAPI is frequently promoted through benchmarks.</p><p>And yes, FastAPI can deliver excellent performance.</p><p>But production API performance depends on much more than the framework.</p><p>Consider:</p><pre>Framework<br>   ↓<br>Database queries<br>   ↓<br>Serialization<br>   ↓<br>External APIs<br>   ↓<br>Caching<br>   ↓<br>Network</pre><p>An inefficient query can destroy the performance advantage of a lightweight framework.</p><p>This:</p><pre>Order.objects.all()</pre><p>followed by hundreds of unnecessary related-object queries can be far more damaging than the choice between DRF and FastAPI.</p><p>Good architecture beats framework benchmarks.</p><h3>6. Validation: Both Are Excellent</h3><p>FastAPI has a particularly elegant validation model.</p><p>Using Pydantic:</p><pre>from pydantic import BaseModel<br><br>class OrderCreate(BaseModel):<br>    customer_id: int<br>    amount: float</pre><p>FastAPI automatically validates incoming requests.</p><p>DRF has a similar concept with serializers:</p><pre>class OrderSerializer(serializers.ModelSerializer):<br><br>    class Meta:<br>        model = Order<br>        fields = [<br>            &quot;customer&quot;,<br>            &quot;amount&quot;<br>        ]</pre><p>Both approaches work well.</p><p>The difference is philosophy.</p><p>FastAPI heavily embraces Python type hints.</p><p>DRF is deeply integrated with Django models and serializers.</p><h3>7. Automatic API Documentation</h3><p>FastAPI is particularly impressive here.</p><p>Define:</p><pre>@app.post(&quot;/orders&quot;)<br>async def create_order(order: OrderCreate):<br>    ...</pre><p>FastAPI automatically generates OpenAPI documentation.</p><p>You get interactive documentation with minimal configuration.</p><p>DRF also provides excellent OpenAPI tooling, but depending on your project and tooling choices, documentation can require more configuration.</p><p>For teams that value API contracts heavily, FastAPI’s approach is extremely appealing.</p><h3>8. Authentication and Permissions</h3><p>This is where Django starts to pull ahead.</p><p>Django has an extensive ecosystem around:</p><ul><li>Users</li><li>Groups</li><li>Permissions</li><li>Sessions</li><li>Authentication</li><li>Admin</li><li>OAuth integrations</li><li>DRF builds directly on top of this.</li></ul><p>For example:</p><pre>class OrderViewSet(ModelViewSet):<br>    permission_classes = [<br>        IsAuthenticated<br>    ]</pre><p>You can then implement more sophisticated authorization:</p><pre>if request.user.role != &quot;admin&quot;:<br>    ...</pre><p>FastAPI has dependency injection, which is powerful:</p><pre>async def get_current_user():<br>    ...</pre><p>But you’re responsible for designing more of the authentication architecture.</p><p>This isn’t necessarily bad.</p><p>It simply means FastAPI gives you freedom instead of defaults.</p><h3>9. The Admin Interface Is a Major Django Advantage</h3><p>This is often underestimated.</p><p>Suppose your application contains:</p><pre>Customers<br>Orders<br>Invoices<br>Companies<br>Payments<br>Tickets<br>Notifications</pre><p>With Django, you can expose these through the admin interface relatively quickly.</p><pre>@admin.register(Order)<br>class OrderAdmin(admin.ModelAdmin):<br>    list_display = (<br>        &quot;id&quot;,<br>        &quot;customer&quot;,<br>        &quot;amount&quot;,<br>        &quot;status&quot;<br>    )</pre><p>You immediately get an operational interface.</p><p>FastAPI doesn’t provide an equivalent built-in administration system.</p><p>If your business needs an internal back office, Django’s ecosystem can save enormous development time.</p><h3>10. FastAPI Is Excellent for Microservices</h3><p>This is where the comparison becomes particularly interesting.</p><p>Instead of replacing Django completely, you can use both.</p><p>For example:</p><pre>                 Frontend<br>                    │<br>                    ▼<br>              Django / DRF<br>                    │<br>          ┌─────────┼──────────┐<br>          ▼         ▼          ▼<br>       FastAPI   FastAPI    FastAPI<br>        AI       IoT       Analytics</pre><p>Django becomes the main business platform.</p><p>FastAPI handles specialized workloads.</p><p>This is often more practical than choosing one framework for everything.</p><h3>11. A Hardware Example</h3><p>Django handles:</p><ul><li>Users</li><li>Organizations</li><li>Business logic</li><li>Permissions</li><li>Database</li><li>Reporting</li></ul><p>FastAPI handles:</p><ul><li>Hardware communication</li><li>Local device discovery</li><li>Real-time commands</li><li>Device events</li></ul><p>This separation makes a lot of sense.</p><h3>12. What About Analytics?</h3><p>The same principle applies to analytics.</p><p>Your Django application might contain your transactional models:</p><pre>Customer<br>Order<br>Payment<br>Invoice</pre><p>But a dedicated FastAPI service could provide:</p><pre>Analytics API<br>     │<br>     ├── Aggregations<br>     ├── Forecasting<br>     ├── Data processing<br>     └── External BI integration</pre><p>The frontend doesn’t necessarily care which framework powers the endpoint.</p><p>It only cares about the API contract.</p><h3>13. When Should You Choose DRF?</h3><p>Choose Django REST Framework when:</p><p><strong>Your application is already Django</strong></p><p>Don’t introduce another framework without a reason.</p><p><strong>You need a relational business application</strong></p><p>Especially when you have complex relationships and workflows.</p><p><strong>You need Django Admin</strong></p><p>This can dramatically reduce development time.</p><p><strong>You need mature authentication and permissions</strong></p><p>Django provides an extensive ecosystem.</p><p><strong>Your team knows Django</strong></p><p>Developer productivity matters more than theoretical benchmarks.</p><h3>14. When Should You Choose FastAPI?</h3><p>FastAPI is a strong choice when:</p><p><strong>You’re building a new API-only service</strong></p><p>Especially when you don’t need Django’s broader ecosystem.</p><p><strong>You have high I/O concurrency</strong></p><p>For example:</p><pre>API<br> ↓<br>External services<br> ↓<br>Message queues<br> ↓<br>Hardware</pre><p><strong>You need a lightweight microservice</strong></p><p>Small services benefit from minimal framework overhead.</p><p><strong>You want strong type-driven APIs</strong></p><p>Pydantic and Python type hints provide an excellent developer experience.</p><p><strong>You’re building AI or data services</strong></p><p>FastAPI has become particularly popular around ML inference and data-processing services.</p><h3>15. Don’t Choose Based on Performance Alone</h3><p>This is perhaps the most important lesson.</p><p>Don’t ask:</p><p>“Which framework is faster?”</p><p>Ask:</p><p>“Which framework makes this system easier to build, operate, and scale?”</p><p>A DRF application with:</p><pre>Good indexes<br>Efficient queries<br>Caching<br>Pagination<br>Background jobs<br>Proper architecture</pre><p>can outperform a poorly designed FastAPI application.</p><p>Likewise, a lightweight FastAPI service can be a much better choice for a focused high-concurrency workload.</p><h3>16. The Hybrid Approach</h3><p>For many organizations, the best answer isn’t:</p><p>Django or FastAPI.</p><p>It’s:</p><p>Django and FastAPI.</p><p>For example:</p><pre>                 Web / Mobile<br>                      │<br>                      ▼<br>                Django REST API<br>                      │<br>        ┌─────────────┼─────────────┐<br>        │             │             │<br>        ▼             ▼             ▼<br>    PostgreSQL    FastAPI       FastAPI<br>                  Analytics     Hardware<br>                      │             │<br>                      ▼             ▼<br>                  ML / BI       Devices</pre><p>Each technology does what it does best.</p><p>Django becomes the business platform.</p><p>FastAPI becomes the specialized service layer.</p><h3>The Real Question Isn’t “Which Is Better?”</h3><p>FastAPI isn’t the replacement for Django REST Framework.</p><p>And DRF isn’t necessarily the better choice simply because it is mature.</p><p>They optimize for different things.</p><pre>| Requirement            |   DRF | FastAPI |<br>| ---------------------- | ----: | ------: |<br>| Django application     | ⭐⭐⭐⭐⭐ |      ⭐⭐ |<br>| Built-in ecosystem     | ⭐⭐⭐⭐⭐ |     ⭐⭐⭐ |<br>| Admin interface        | ⭐⭐⭐⭐⭐ |       — |<br>| Authentication         | ⭐⭐⭐⭐⭐ |     ⭐⭐⭐ |<br>| Type-driven APIs       |   ⭐⭐⭐ |   ⭐⭐⭐⭐⭐ |<br>| Async-first services   |   ⭐⭐⭐ |   ⭐⭐⭐⭐⭐ |<br>| Microservices          |  ⭐⭐⭐⭐ |   ⭐⭐⭐⭐⭐ |<br>| AI/ML APIs             |  ⭐⭐⭐⭐ |   ⭐⭐⭐⭐⭐ |<br>| Rapid CRUD development | ⭐⭐⭐⭐⭐ |    ⭐⭐⭐⭐ |<br>| Specialized services   |  ⭐⭐⭐⭐ |   ⭐⭐⭐⭐⭐ |<br></pre><p>These aren’t absolute rankings — they’re architectural tendencies.</p><h3>Final Thoughts</h3><p>Choosing between Django REST Framework and FastAPI shouldn’t be a popularity contest.</p><p>DRF is excellent when your API is part of a larger Django application.</p><p>You get an ORM, authentication, permissions, administration, serializers, middleware, and a mature ecosystem.</p><p>FastAPI is excellent when your API is a focused service.</p><p>You get lightweight architecture, excellent type support, asynchronous capabilities, automatic OpenAPI documentation, and the freedom to choose the components around it.</p><p>And sometimes the best architecture uses both.</p><p>The interesting question isn’t:</p><p>“Should I replace DRF with FastAPI?”</p><p>It’s:</p><p>“Which part of my system actually needs FastAPI?”</p><p>That’s where the architectural decision becomes much more valuable than the framework debate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f94776f55262" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-unleashed/fastapi-instead-of-django-rest-framework-when-should-you-make-the-switch-f94776f55262">FastAPI Instead of Django REST Framework: When Should You Make the Switch?</a> was originally published in <a href="https://medium.com/django-unleashed">Django Unleashed</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Production-Ready Hardware Micro-Agents with FastAPI: Offline Sync, Security, and Device Management]]></title>
            <link>https://medium.com/django-unleashed/production-ready-hardware-micro-agents-with-fastapi-offline-sync-security-and-device-management-da58321caae1?source=rss-54d2da3e9958------2</link>
            <guid isPermaLink="false">https://medium.com/p/da58321caae1</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[micro-agent]]></category>
            <category><![CDATA[hardware]]></category>
            <dc:creator><![CDATA[Osirus Djodji]]></dc:creator>
            <pubDate>Wed, 12 Aug 2026 12:59:13 GMT</pubDate>
            <atom:updated>2026-08-12T12:59:13.138Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E_Rc-hq0ev4oxE0w7Vmh0Q.png" /><figcaption>Transform a simple FastAPI hardware bridge into a robust production-ready edge service.</figcaption></figure><p>In the last <a href="https://medium.com/@osirusdjodji/building-a-hardware-gateway-with-fastapi-connecting-web-applications-to-local-devices-a7234ea4811d">article</a>, we built a lightweight FastAPI micro-agent capable of exposing local hardware to a web application.</p><p>While that works well for prototypes, production systems require much more than a few REST endpoints.</p><p>Real deployments must survive network failures, reconnect automatically, authenticate requests, queue operations, and manage multiple devices simultaneously.</p><p>Let’s turn our simple hardware bridge into an enterprise-ready edge agent.</p><h3>The Challenges of Production</h3><p>Real-world environments introduce challenges such as:</p><ul><li>Internet outages</li><li>Hardware disconnects</li><li>Device discovery</li><li>Authentication</li><li>Automatic updates</li><li>Logging</li><li>Retry mechanisms</li><li>Multiple connected peripherals</li></ul><p>A production-ready micro-agent should handle all of these without user intervention.</p><h3>Registering the Agent</h3><p>When the agent starts, it can register itself with the central API.</p><p>Example payload:</p><pre>{<br>  &quot;device_id&quot;: &quot;agent-001&quot;,<br>  &quot;hostname&quot;: &quot;Warehouse-PC-03&quot;,<br>  &quot;version&quot;: &quot;1.2.0&quot;,<br>  &quot;devices&quot;: [<br>    &quot;printer&quot;,<br>    &quot;barcode_scanner&quot;,<br>    &quot;scale&quot;<br>  ]<br>}</pre><p>This allows the server to know which hardware is available.</p><h4>Device Discovery</h4><p>Instead of hardcoding device paths, detect them dynamically.</p><p>Examples include:</p><ul><li>USB enumeration</li><li>Serial port scanning</li><li>Network printer discovery</li><li>Bluetooth scanning</li></ul><p>The agent exposes:</p><pre>GET /devices</pre><p>Example response:</p><pre>{<br>  &quot;printers&quot;: [<br>    &quot;Brother QL-820NWB&quot;,<br>    &quot;EPSON TM-T88&quot;<br>  ],<br>  &quot;serial_ports&quot;: [<br>    &quot;COM3&quot;,<br>    &quot;COM5&quot;<br>  ]<br>}</pre><h3>Authentication</h3><p>Every request between Django and the agent should be authenticated.</p><p>A simple approach:</p><pre>Authorization: Bearer &lt;token&gt;</pre><p>Even on local networks, never trust unauthenticated requests.</p><h3>Queueing Commands Offline</h3><p>Suppose the internet connection drops while the server sends a print request.</p><p>Instead of failing immediately, store the job locally.</p><p>Example queue:</p><pre>Print #542<br>Print #543<br>Print #544</pre><p>Once connectivity is restored, the agent processes pending jobs automatically.</p><h3>Bidirectional Communication</h3><p>Sometimes the server initiates commands.</p><p>Other times, hardware generates events.</p><p>Examples:</p><ul><li>A barcode is scanned</li><li>A card is inserted</li><li>A scale measurement changes</li><li>A printer reports an error</li></ul><p>Instead of polling continuously, the agent can push events back to Django using webhooks or WebSockets.</p><h3>Logging Everything</h3><p>Operational visibility is essential.</p><p>Record:</p><ul><li>Commands received</li><li>Hardware responses</li><li>Errors</li><li>Device disconnects</li><li>Retry attempts</li></ul><p>Structured logs make troubleshooting much easier.</p><h3>Updating the Agent</h3><p>As your application evolves, so should the micro-agent.</p><p>Consider supporting:</p><ul><li>Automatic update checks</li><li>Version reporting</li><li>Graceful upgrades</li><li>Rollback mechanisms</li></ul><p>Keeping edge software current improves security and reliability.</p><h3>Scaling to Multiple Devices</h3><p>A single agent may manage several peripherals simultaneously:</p><pre>FastAPI Agent<br>     │<br> ├── Printer<br> ├── Scanner<br> ├── Scale<br> ├── RFID Reader<br> └── Camera</pre><p>By organizing each integration into dedicated services, you can extend the agent without affecting existing functionality.</p><h3>Monitoring and Health Checks</h3><p>Expose lightweight endpoints such as:</p><pre>GET /health<br>GET /status<br>GET /devices</pre><p>These allow the central server to verify that the agent and connected hardware are functioning correctly.</p><h3>Security Best Practices</h3><p>For production deployments:</p><ul><li>Restrict access to trusted hosts</li><li>Use API tokens or mutual authentication</li><li>Validate every command</li><li>Encrypt sensitive communication</li><li>Avoid exposing unnecessary endpoints</li><li>Rotate credentials periodically</li></ul><p>Security should be built into the architecture from the start.</p><h3>Conclusion</h3><p>A FastAPI micro-agent is much more than a local REST service. It becomes the edge layer connecting cloud applications to physical devices in a secure and reliable way.</p><p>By adding device discovery, authentication, offline queues, bidirectional communication, monitoring, and automatic updates, you can build a solution suitable for industrial systems, logistics platforms, healthcare applications, retail environments, and any scenario where web applications need to interact with local hardware.</p><p>Together, these two articles provide a complete roadmap — from the first prototype to a production-ready hardware gateway powered by FastAPI.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da58321caae1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-unleashed/production-ready-hardware-micro-agents-with-fastapi-offline-sync-security-and-device-management-da58321caae1">Production-Ready Hardware Micro-Agents with FastAPI: Offline Sync, Security, and Device Management</a> was originally published in <a href="https://medium.com/django-unleashed">Django Unleashed</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 Hardware Gateway with FastAPI: Connecting Web Applications to Local Devices]]></title>
            <link>https://medium.com/django-unleashed/building-a-hardware-gateway-with-fastapi-connecting-web-applications-to-local-devices-a7234ea4811d?source=rss-54d2da3e9958------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7234ea4811d</guid>
            <category><![CDATA[hardware]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Osirus Djodji]]></dc:creator>
            <pubDate>Wed, 29 Jul 2026 17:14:39 GMT</pubDate>
            <atom:updated>2026-07-29T17:14:39.426Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xIp7PwihqTg-0QXiocrmlQ.png" /></figure><p><em>How to use FastAPI as a lightweight micro-agent to bridge your Django or web application with printers, scanners, serial devices, and other local hardware.</em></p><p>Modern web applications increasingly need to interact with hardware located on users’ machines or inside local networks.</p><p>Consider a few examples:</p><ul><li>Printing invoices directly from a browser</li><li>Reading RFID badges</li><li>Controlling industrial equipment</li><li>Opening serial ports</li><li>Capturing data from USB devices</li><li>Communicating with weighing scales</li><li>Scanning barcodes</li><li>Reading biometric devices</li></ul><p>Unfortunately, browsers cannot directly access most local hardware for obvious security reasons.</p><p>This is where a <strong>micro-agent</strong> becomes incredibly useful.</p><p>Instead of forcing your web application to communicate directly with hardware, you deploy a lightweight local service that acts as a bridge.</p><p>In this article, we’ll build that bridge using <strong>FastAPI</strong>.</p><h3>Why Not Access Hardware Directly?</h3><p>Browsers intentionally restrict access to:</p><ul><li>USB devices</li><li>Serial ports</li><li>Local printers</li><li>Local files</li><li>Industrial protocols</li></ul><p>This protects users against malicious websites.</p><p>Your Django application might know that a receipt needs to be printed, but it cannot simply execute:</p><pre>Printer.print(invoice)</pre><p>because the printer exists on the client’s machine — not on your server.</p><h3>Introducing the Micro-Agent</h3><p>Think of the architecture like this:</p><pre>          Django API<br>               │<br>        HTTPS Requests<br>               │<br>      Local FastAPI Agent<br>               │<br>    ┌──────────┼──────────┐<br>    │          │          │<br> Printer    Barcode    USB Device<br>             Scanner</pre><p>The FastAPI application becomes a <strong>local hardware gateway</strong>.</p><h3>Why FastAPI?</h3><p>FastAPI is perfect for micro-agents because it is:</p><ul><li>Lightweight</li><li>Extremely fast</li><li>Asynchronous</li><li>Easy to package</li><li>Cross-platform</li><li>Easy to expose as a Windows/Linux service</li></ul><p>A complete hardware gateway often requires only a few hundred lines of Python.</p><h3>Basic Architecture</h3><p>The agent usually contains four layers:</p><pre>API Layer<br>     │<br>Hardware Service<br>     │<br>Drivers<br>     │<br>Physical Devices</pre><p>This separation keeps your code maintainable.</p><h3>Creating the Agent</h3><p>Installing dependencies:</p><pre>pip install fastapi uvicorn</pre><p>Simple API:</p><pre>from fastapi import FastAPI<br><br>app = FastAPI()<br><br>@app.get(&quot;/health&quot;)<br>async def health():<br>    return {&quot;status&quot;: &quot;running&quot;}</pre><p>Run:</p><pre>uvicorn main:app --reload</pre><p>Now your web application can verify that the local agent is online.</p><h3>Designing Hardware Services</h3><p>Instead of placing hardware code inside API routes:</p><p>Bad:</p><pre>@app.post(&quot;/print&quot;)<br>async def print():<br>    ...</pre><p>Create dedicated services:</p><pre>services/<br>    printer.py<br>    scanner.py<br>    serial.py<br>    usb.py</pre><p>Each service encapsulates one device type.</p><h3>Talking to Django</h3><p>Imagine your Django backend sends:</p><pre>{<br>    &quot;document&quot;: &quot;...&quot;,<br>    &quot;copies&quot;: 2<br>}</pre><p>The FastAPI agent receives it:</p><pre>@app.post(&quot;/print&quot;)<br>async def print_document(data: PrintRequest):<br>    ...</pre><p>The response:</p><pre>{<br>    &quot;success&quot;: true<br>}</pre><p>Simple, reliable.</p><h3>Local Authentication</h3><p>Even though the agent runs locally, don’t expose it without protection.</p><p>Recommended:</p><ul><li>API Keys</li><li>Local tokens</li><li>Loopback-only access</li><li>HTTPS when applicable</li></ul><h3>Packaging the Agent</h3><p>The FastAPI application can become:</p><ul><li>Windows Service</li><li>Linux daemon</li><li>Docker container</li><li>Standalone executable (PyInstaller)</li></ul><p>Users shouldn’t need a terminal to run it.</p><h3>Real-World Applications</h3><p>Micro-agents are commonly used for:</p><ul><li>POS systems</li><li>Warehouse scanners</li><li>Manufacturing equipment</li><li>Medical devices</li><li>Smart kiosks</li><li>Receipt printers</li><li>Label printers</li></ul><h3>Conclusion</h3><p>FastAPI makes an excellent foundation for building lightweight hardware gateways.</p><p>By introducing a local micro-agent, your web application gains secure access to hardware without compromising browser security.</p><p>In the next article, we’ll make this architecture production-ready by adding automatic discovery, authentication, offline queues, retries, logging, and bidirectional communication with Django.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7234ea4811d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-unleashed/building-a-hardware-gateway-with-fastapi-connecting-web-applications-to-local-devices-a7234ea4811d">Building a Hardware Gateway with FastAPI: Connecting Web Applications to Local Devices</a> was originally published in <a href="https://medium.com/django-unleashed">Django Unleashed</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Webhooks in Django REST Framework: Building Event-Driven APIs]]></title>
            <link>https://medium.com/django-unleashed/webhooks-in-django-rest-framework-building-event-driven-apis-9cf8c35bb26a?source=rss-54d2da3e9958------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cf8c35bb26a</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[webhooks]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[Osirus Djodji]]></dc:creator>
            <pubDate>Wed, 24 Jun 2026 14:44:01 GMT</pubDate>
            <atom:updated>2026-06-24T14:44:01.375Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x3zWGrMf7OlwQ0UqRRZu-A.png" /></figure><p>Modern APIs are no longer isolated systems.</p><p>When a payment succeeds, a shipment is delivered, or a user registers, other systems often need to know immediately. Polling an API every few seconds is inefficient and wasteful.</p><p>This is where <strong>webhooks</strong> come in.</p><p>Webhooks enable APIs to communicate automatically whenever important events occur, making integrations faster, more scalable, and truly event-driven.</p><p>In this article, we’ll explore how to implement webhooks in Django REST Framework (DRF), design reliable event delivery mechanisms, and build integrations that scale.</p><h4>What Is a Webhook?</h4><p>A webhook is an HTTP callback triggered by an event.</p><p>Instead of a client repeatedly asking:</p><blockquote><em>“Did something happen yet?”</em></blockquote><p>The server proactively sends a notification when it does.</p><p>Traditional polling:</p><pre>Client → API<br>Client → API<br>Client → API<br>Client → API</pre><p>Webhook approach:</p><pre>Event occurs<br>      ↓<br>API sends POST request<br>      ↓<br>Client receives notification</pre><p>This significantly reduces unnecessary traffic.</p><h4>Real-World Examples</h4><p>Many popular platforms rely on webhooks:</p><ul><li>Payment confirmations</li><li>Order status updates</li><li>User registration events</li><li>Document approval workflows</li><li>Support ticket updates</li><li>Push notification triggers</li></ul><p>For example:</p><p>When an order is validated:</p><pre>{<br>  &quot;event&quot;: &quot;order_validated&quot;,<br>  &quot;order_id&quot;: 1245,<br>  &quot;timestamp&quot;: &quot;2026-02-10T14:30:00Z&quot;<br>}</pre><p>The API automatically notifies subscribed systems.</p><h4>Designing a Webhook Model</h4><p>A common approach is to allow clients to register webhook endpoints.</p><p>Example model:</p><pre>from django.db import models<br><br>class WebhookSubscription(models.Model):<br>    url = models.URLField()<br>    event_type = models.CharField(max_length=100)<br>    is_active = models.BooleanField(default=True)<br>    created_at = models.DateTimeField(auto_now_add=True)</pre><p>This lets consumers subscribe to specific events.</p><p>Examples:</p><pre>order_created<br>order_validated<br>payment_received<br>ticket_closed</pre><h4>Registering Webhooks via DRF</h4><p>Expose an endpoint:</p><pre>from rest_framework.viewsets import ModelViewSet<br><br>class WebhookSubscriptionViewSet(ModelViewSet):<br>    queryset = WebhookSubscription.objects.all()<br>    serializer_class = WebhookSubscriptionSerializer</pre><p>Consumers can then register:</p><pre>POST /api/webhooks/</pre><p>Payload:</p><pre>{<br>  &quot;url&quot;: &quot;https://example.com/webhook&quot;,<br>  &quot;event_type&quot;: &quot;order_validated&quot;<br>}</pre><h4>Triggering a Webhook</h4><p>Imagine an order becomes validated.</p><pre>order.status = &quot;validated&quot;<br>order.save()</pre><p>After saving:</p><pre>subscriptions = WebhookSubscription.objects.filter(<br>    event_type=&quot;order_validated&quot;,<br>    is_active=True<br>)</pre><p>Prepare the payload:</p><pre>payload = {<br>    &quot;event&quot;: &quot;order_validated&quot;,<br>    &quot;order_id&quot;: order.id,<br>    &quot;status&quot;: order.status<br>}</pre><p>Then notify subscribers.</p><h4>Sending Webhook Requests</h4><p>Using Python’s requests library:</p><pre>import requests<br><br>requests.post(<br>    subscription.url,<br>    json=payload,<br>    timeout=10<br>)</pre><p>This sends a standard HTTP POST request to the subscriber.</p><h4>Moving Delivery to Background Tasks</h4><p>Never send webhooks directly inside critical business logic.</p><p>Bad:</p><pre>order.save()<br><br>requests.post(...)</pre><p>If the remote service is slow, your API becomes slow too.</p><p>A better solution uses Celery:</p><pre>@shared_task<br>def send_webhook(url, payload):<br>    requests.post(url, json=payload)</pre><p>Trigger:</p><pre>send_webhook.delay(subscription.url, payload)</pre><p>Benefits:</p><ul><li>Faster API responses</li><li>Retry support</li><li>Better scalability</li></ul><h4>Securing Webhooks</h4><p>Security is critical.</p><p>Anyone can expose an endpoint and claim to be your client.</p><p>A common solution is signing requests.</p><p>Generate a secret:</p><pre>import hmac<br>import hashlib</pre><p>Create a signature:</p><pre>signature = hmac.new(<br>    secret.encode(),<br>    payload_bytes,<br>    hashlib.sha256<br>).hexdigest()</pre><p>Send it in a header:</p><pre>X-Signature: abc123...</pre><p>The receiving system verifies the signature before trusting the payload.</p><h4>Handling Failures</h4><p>Webhook delivery is never guaranteed.</p><p>Possible failures:</p><ul><li>Timeout</li><li>DNS issues</li><li>Server unavailable</li><li>Network interruption</li></ul><p>Track delivery attempts:</p><pre>class WebhookDelivery(models.Model):<br>    webhook = models.ForeignKey(<br>        WebhookSubscription,<br>        on_delete=models.CASCADE<br>    )<br>    status_code = models.IntegerField(null=True)<br>    success = models.BooleanField(default=False)<br>    created_at = models.DateTimeField(auto_now_add=True)</pre><p>This creates a complete audit trail.</p><h4>Implementing Retry Logic</h4><p>A webhook should not fail permanently after one attempt.</p><p>Typical strategy:</p><ul><li>Attempt immediately</li><li>Retry after 1 minute</li><li>Retry after 5 minutes</li><li>Retry after 30 minutes</li><li>Mark as failed</li></ul><p>Celery retry support makes this straightforward.</p><pre>self.retry(countdown=60)</pre><p>This improves reliability significantly.</p><h4>Designing Event Payloads</h4><p>Keep payloads simple and predictable.</p><p>Good:</p><pre>{<br>  &quot;event&quot;: &quot;ticket_closed&quot;,<br>  &quot;ticket_id&quot;: 782,<br>  &quot;closed_at&quot;: &quot;2026-02-10T14:00:00Z&quot;<br>}</pre><p>Avoid:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;x&quot;: {<br>      &quot;y&quot;: {<br>        ...<br>      }<br>    }<br>  }<br>}</pre><p>Webhook consumers appreciate clean schemas.</p><h4>Event Versioning</h4><p>As APIs evolve, webhook payloads change.</p><p>Include a version:</p><pre>{<br>  &quot;version&quot;: &quot;1.0&quot;,<br>  &quot;event&quot;: &quot;payment_received&quot;<br>}</pre><p>This allows future changes without breaking integrations.</p><p>For most event-driven integrations, webhooks are the superior choice.</p><h3>Common Use Cases in DRF Projects</h3><h4>E-commerce</h4><ul><li>Order creation</li><li>Payment confirmation</li><li>Shipment updates</li></ul><h4>Elections</h4><ul><li>PV validation</li><li>Anomaly creation</li><li>Result publication</li></ul><h4>Support Platforms</h4><ul><li>Ticket assignment</li><li>Ticket closure</li><li>New comments</li></ul><h4>Analytics</h4><ul><li>KPI threshold alerts</li><li>Report generation</li><li>Dashboard notifications</li></ul><h4>Best Practices</h4><ul><li>Deliver asynchronously</li><li>Sign webhook payloads</li><li>Log all deliveries</li><li>Implement retries</li><li>Version event schemas</li><li>Keep payloads lightweight</li><li>Allow event-specific subscriptions</li></ul><h3>Conclusion</h3><p>Webhooks transform Django REST APIs from passive data providers into active participants in a broader ecosystem.</p><p>Instead of forcing external systems to repeatedly ask for updates, your API can instantly notify them when meaningful events occur.</p><p>When implemented with proper security, retries, and asynchronous delivery, webhooks become one of the most powerful integration mechanisms available in modern DRF applications.</p><p>They don’t just expose data — they enable systems to communicate in real time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cf8c35bb26a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-unleashed/webhooks-in-django-rest-framework-building-event-driven-apis-9cf8c35bb26a">Webhooks in Django REST Framework: Building Event-Driven APIs</a> was originally published in <a href="https://medium.com/django-unleashed">Django Unleashed</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Combining Map and Chart APIs for Geo-Analytics Dashboards]]></title>
            <link>https://medium.com/django-unleashed/combining-map-and-chart-apis-for-geo-analytics-dashboards-f132cd2de208?source=rss-54d2da3e9958------2</link>
            <guid isPermaLink="false">https://medium.com/p/f132cd2de208</guid>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[charts]]></category>
            <dc:creator><![CDATA[Osirus Djodji]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 18:34:56 GMT</pubDate>
            <atom:updated>2026-06-17T18:34:56.443Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Vs6CCcNMoCvpRUj7LH7zw.png" /></figure><p>Modern dashboards rarely rely on a single visualization.</p><p>A logistics platform might display deliveries on a map while showing daily volumes in a chart. An environmental monitoring system may track sensor locations geographically while visualizing trends over time. An election platform can display polling stations on a map alongside participation statistics.</p><p>Too often, these visualizations are powered by separate API calls. One endpoint returns geographic data, another returns chart data, and the frontend is responsible for stitching everything together.</p><p>A better approach is often to expose a <strong>single geo-analytics endpoint</strong> capable of returning both map data and chart data in a unified response.</p><p>In this article, we’ll explore how to design such APIs using Django REST Framework.</p><h3>The Problem with Separate Endpoints</h3><p>A common implementation looks like this:</p><pre>GET /api/stations/map<br>GET /api/stations/statistics</pre><p>The frontend must:</p><ol><li>Make multiple requests</li><li>Synchronize filters</li><li>Handle multiple loading states</li><li>Merge responses</li></ol><p>This increases complexity and can create inconsistencies.</p><p>Imagine a user filtering data by date:</p><pre>?start=2026-01-01&amp;end=2026-01-31</pre><p>If one request succeeds and another fails, the dashboard may show mismatched information.</p><h3>A Visualization-First Design</h3><p>Instead, think about the dashboard as a whole.</p><p>The API should answer:</p><blockquote><em>What does the dashboard need to render?</em></blockquote><p>Typically:</p><ul><li>Map markers</li><li>Summary KPIs</li><li>Chart series</li><li>Metadata</li></ul><p>A single endpoint might look like:</p><pre>GET /api/geo-analytics/dashboard</pre><h3>Example Response Structure</h3><pre>{<br>  &quot;map&quot;: {<br>    &quot;points&quot;: [<br>      {<br>        &quot;id&quot;: 1,<br>        &quot;name&quot;: &quot;Station A&quot;,<br>        &quot;latitude&quot;: 6.3703,<br>        &quot;longitude&quot;: 2.3912,<br>        &quot;value&quot;: 245<br>      },<br>      {<br>        &quot;id&quot;: 2,<br>        &quot;name&quot;: &quot;Station B&quot;,<br>        &quot;latitude&quot;: 6.4010,<br>        &quot;longitude&quot;: 2.4250,<br>        &quot;value&quot;: 198<br>      }<br>    ]<br>  },<br>  &quot;charts&quot;: {<br>    &quot;daily_activity&quot;: [<br>      {<br>        &quot;date&quot;: &quot;2026-02-01&quot;,<br>        &quot;value&quot;: 120<br>      },<br>      {<br>        &quot;date&quot;: &quot;2026-02-02&quot;,<br>        &quot;value&quot;: 145<br>      }<br>    ]<br>  }<br>}</pre><p>The frontend now has everything it needs.</p><h3>Building the Map Dataset</h3><p>Let’s imagine we have a model:</p><pre>class Station(models.Model):<br>    name = models.CharField(max_length=255)<br>    latitude = models.FloatField()<br>    longitude = models.FloatField()</pre><p>We can serialize locations as:</p><pre>stations = Station.objects.values(<br>    &quot;id&quot;,<br>    &quot;name&quot;,<br>    &quot;latitude&quot;,<br>    &quot;longitude&quot;<br>)</pre><p>Then transform them into map points:</p><pre>map_points = [<br>    {<br>        &quot;id&quot;: station[&quot;id&quot;],<br>        &quot;name&quot;: station[&quot;name&quot;],<br>        &quot;latitude&quot;: station[&quot;latitude&quot;],<br>        &quot;longitude&quot;: station[&quot;longitude&quot;]<br>    }<br>    for station in stations<br>]</pre><p>These points can be consumed by:</p><ul><li>Leaflet</li><li>Mapbox</li><li>Google Maps</li><li>OpenLayers</li></ul><h3>Building the Chart Dataset</h3><p>Now let’s generate chart data.</p><p>Suppose we track events:</p><pre>class Activity(models.Model):<br>    station = models.ForeignKey(Station, on_delete=models.CASCADE)<br>    created_at = models.DateTimeField()</pre><p>Daily aggregation becomes:</p><pre>from django.db.models import Count<br>from django.db.models.functions import TruncDay<br><br>daily_stats = (<br>    Activity.objects<br>    .annotate(day=TruncDay(&quot;created_at&quot;))<br>    .values(&quot;day&quot;)<br>    .annotate(total=Count(&quot;id&quot;))<br>    .order_by(&quot;day&quot;)<br>)</pre><p>Convert to chart format:</p><pre>chart_data = [<br>    {<br>        &quot;date&quot;: item[&quot;day&quot;],<br>        &quot;value&quot;: item[&quot;total&quot;]<br>    }<br>    for item in daily_stats<br>]</pre><p>Perfect for:</p><ul><li>Chart.js</li><li>Recharts</li><li>ApexCharts</li><li>ECharts</li></ul><h3>Combining Both in a Single DRF Endpoint</h3><p>The ViewSet becomes straightforward:</p><pre>from rest_framework.response import Response<br>from rest_framework.viewsets import ViewSet<br><br>class GeoAnalyticsViewSet(ViewSet):<br><br>    def list(self, request):<br><br>        map_points = get_map_points()<br><br>        chart_data = get_chart_data()<br><br>        return Response({<br>            &quot;map&quot;: {<br>                &quot;points&quot;: map_points<br>            },<br>            &quot;charts&quot;: {<br>                &quot;daily_activity&quot;: chart_data<br>            }<br>        })</pre><p>One request. One response. One dashboard.</p><h3>Supporting Filters</h3><p>The real power comes when filters affect both datasets simultaneously.</p><p>Example:</p><pre>GET /api/geo-analytics/dashboard?region=north</pre><p>Or:</p><pre>GET /api/geo-analytics/dashboard?start=2026-01-01&amp;end=2026-01-31</pre><p>The backend applies the same filters to:</p><ul><li>Map points</li><li>Charts</li><li>KPIs</li></ul><p>This guarantees consistency.</p><h3>Adding KPI Cards</h3><p>Many dashboards also include summary metrics.</p><p>Example:</p><pre>{<br>  &quot;kpis&quot;: {<br>    &quot;total_locations&quot;: 124,<br>    &quot;total_events&quot;: 5420,<br>    &quot;active_locations&quot;: 117<br>  }<br>}</pre><p>Now the endpoint powers:</p><ul><li>KPI cards</li><li>Maps</li><li>Charts</li></ul><p>From a single source.</p><h3>Performance Considerations</h3><p>As dashboards grow, performance becomes critical.</p><p>Best practices include:</p><h3>Cache aggregated results</h3><pre>cache.get_or_set(<br>    cache_key,<br>    expensive_function,<br>    timeout=300<br>)</pre><h3>Use database aggregations</h3><p>Prefer:</p><pre>Count()<br>Sum()<br>Avg()</pre><p>Over Python loops.</p><h3>Paginate large map datasets</h3><p>Thousands of points can overwhelm browsers.</p><p>Consider:</p><ul><li>clustering</li><li>bounding box filtering</li><li>GeoJSON simplification</li></ul><h3>GeoJSON Compatibility</h3><p>If your frontend consumes GeoJSON, your endpoint can return:</p><pre>{<br>  &quot;type&quot;: &quot;FeatureCollection&quot;,<br>  &quot;features&quot;: [...]<br>}</pre><p>Alongside chart data:</p><pre>{<br>  &quot;geojson&quot;: {...},<br>  &quot;charts&quot;: {...}<br>}</pre><p>This works exceptionally well with modern mapping libraries.</p><h3>Real-World Use Cases</h3><p>This pattern is useful for:</p><h4>Logistics</h4><ul><li>Delivery routes on maps</li><li>Deliveries per day in charts</li></ul><h4>Elections</h4><ul><li>Polling stations on maps</li><li>Participation rates in charts</li></ul><h4>Environmental Monitoring</h4><ul><li>Sensor locations</li><li>Temperature trends</li></ul><h4>Public Infrastructure</h4><ul><li>Facilities on maps</li><li>Usage statistics in charts</li></ul><h3>Conclusion</h3><p>Geo-analytics dashboards become much more powerful when maps and charts work together.</p><p>Instead of forcing the frontend to orchestrate multiple requests, design APIs around what the dashboard actually needs.</p><p>A single endpoint that returns:</p><ul><li>Map data</li><li>Chart data</li><li>KPI metrics</li></ul><p>creates a cleaner architecture, improves performance, and simplifies frontend development.</p><p>The best analytics APIs aren’t designed around databases — they’re designed around visualizations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f132cd2de208" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-unleashed/combining-map-and-chart-apis-for-geo-analytics-dashboards-f132cd2de208">Combining Map and Chart APIs for Geo-Analytics Dashboards</a> was originally published in <a href="https://medium.com/django-unleashed">Django Unleashed</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Soft Deletes in Django REST APIs: Keeping Data Without Losing Control]]></title>
            <link>https://medium.com/django-unleashed/soft-deletes-in-django-rest-apis-keeping-data-without-losing-control-309055e92449?source=rss-54d2da3e9958------2</link>
            <guid isPermaLink="false">https://medium.com/p/309055e92449</guid>
            <category><![CDATA[data-deletion]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[soft-delete]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[Osirus Djodji]]></dc:creator>
            <pubDate>Fri, 01 May 2026 16:46:52 GMT</pubDate>
            <atom:updated>2026-05-01T16:46:52.721Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CpIp2Pw-S4sZHsQqzoYLGQ.png" /></figure><p>Deleting data sounds simple. But in real systems, deleting often means losing:</p><ul><li>audit trails</li><li>business history</li><li>relationships</li><li>analytics consistency</li></ul><p>That’s why many production systems use <strong>soft deletes</strong>. Instead of removing records, you mark them as deleted.</p><p>In this article, we’ll implement soft deletes cleanly in Django REST Framework.</p><h4>What Is Soft Delete?</h4><p>Hard delete:</p><pre>object.delete()</pre><p>Record disappears.</p><p>Soft delete:</p><pre>object.is_deleted = True<br>object.save()</pre><p>Record stays.</p><h3>Why Soft Deletes Matter</h3><p>They help with:</p><ul><li>restoring mistakes</li><li>preserving analytics</li><li>auditability</li><li>historical reporting</li></ul><p>Critical in finance, elections, healthcare, logistics.</p><h3>Creating a Reusable Base Model</h3><p>Start with a shared abstract model:</p><pre>class SoftDeleteModel(models.Model):<br>    is_deleted = models.BooleanField(default=False)<br>    deleted_at = models.DateTimeField(null=True, blank=True)<br><br>    class Meta:<br>        abstract = True</pre><p>Now inherit:</p><pre>class Order(SoftDeleteModel):<br>    name = models.CharField(max_length=255)</pre><h3>Overriding Delete Logic</h3><p>Instead of removing:</p><pre>from django.utils.timezone import now<br><br>def delete(self, *args, **kwargs):<br>    self.is_deleted = True<br>    self.deleted_at = now()<br>    self.save()</pre><p>Now deletes become reversible.</p><h3>Filtering Deleted Records</h3><p>Default queryset:</p><pre>Order.objects.filter(is_deleted=False)</pre><p>Better with custom manager:</p><pre>class ActiveManager(models.Manager):<br>    def get_queryset(self):<br>        return super().get_queryset().filter(is_deleted=False)</pre><p>Attach it:</p><pre>objects = ActiveManager()<br>all_objects = models.Manager()</pre><h3>DRF Integration</h3><p>Your ViewSet remains simple:</p><pre>class OrderViewSet(ModelViewSet):<br>    queryset = Order.objects.all()</pre><p>Since objects excludes deleted records.</p><h3>Adding Restore Support</h3><p>Useful endpoint:</p><pre>@action(detail=True, methods=[&quot;post&quot;])<br>def restore(self, request, pk=None):<br>    order = Order.all_objects.get(pk=pk)<br>    order.is_deleted = False<br>    order.deleted_at = None<br>    order.save()</pre><p>Now records can come back.</p><h3>Analytics Impact</h3><p>Hard deletes distort analytics.</p><h4>Example:</h4><p>Revenue last month becomes lower if old orders are deleted. Soft deletes preserve business history. Critical for dashboards.</p><h3>When NOT to Use Soft Deletes</h3><p>Avoid for:</p><ul><li>temporary cache tables</li><li>logs you rotate</li><li>disposable data</li></ul><p>Not everything needs recovery.</p><h3>Conclusion</h3><p>Soft delete is one of those patterns that feels unnecessary until it saves your system.</p><p>It protects history, analytics, and trust.</p><p>And in mature APIs, trust matters.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=309055e92449" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-unleashed/soft-deletes-in-django-rest-apis-keeping-data-without-losing-control-309055e92449">Soft Deletes in Django REST APIs: Keeping Data Without Losing Control</a> was originally published in <a href="https://medium.com/django-unleashed">Django Unleashed</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pagination Strategies in Django REST APIs: Beyond Page Numbers]]></title>
            <link>https://medium.com/django-unleashed/pagination-strategies-in-django-rest-apis-beyond-page-numbers-f28557939b30?source=rss-54d2da3e9958------2</link>
            <guid isPermaLink="false">https://medium.com/p/f28557939b30</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Osirus Djodji]]></dc:creator>
            <pubDate>Fri, 01 May 2026 16:31:02 GMT</pubDate>
            <atom:updated>2026-05-01T16:31:02.776Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ZB6Dn-DXVoCWlw31J-8Zw.png" /></figure><p>Most developers think pagination is solved. Add pagination, return page numbers, done.</p><p>But in production systems — especially analytics APIs, activity feeds, logs, and dashboards — pagination design directly impacts <strong>performance, user experience, and scalability</strong>.</p><p>In this article, we’ll explore smarter pagination strategies in Django REST Framework (DRF) and when to use each.</p><h3>Why Pagination Matters</h3><p>Without pagination:</p><ul><li>payloads become huge</li><li>response times grow</li><li>frontend rendering slows</li><li>database load increases</li></ul><p>A good API controls how much data leaves the server.</p><h3>The Classic Page Number Pagination</h3><p>The most common approach:</p><pre>GET /api/orders?page=2</pre><p>Response:</p><pre>{<br>  &quot;count&quot;: 4200,<br>  &quot;next&quot;: &quot;...&quot;,<br>  &quot;previous&quot;: &quot;...&quot;,<br>  &quot;results&quot;: [...]<br>}</pre><p>DRF makes this simple:</p><pre>from rest_framework.pagination import PageNumberPagination<br><br>class DefaultPagination(PageNumberPagination):<br>    page_size = 20</pre><p>Easy. But not always optimal.</p><h3>The Problem with Page Numbers</h3><p>Page number pagination becomes inefficient on large datasets.</p><p>Why?</p><p>To fetch page 200:</p><pre>OFFSET 3980 LIMIT 20</pre><p>The database skips thousands of rows first.</p><p>This gets expensive.</p><h3>Cursor Pagination: Better for Large Data</h3><p>Cursor pagination uses position instead of page numbers.</p><p>Example:</p><pre>GET /api/orders?cursor=abc123</pre><p>Benefits:</p><ul><li>faster on large tables</li><li>stable ordering</li><li>better for infinite scroll</li></ul><p>DRF supports it:</p><pre>from rest_framework.pagination import CursorPagination<br><br>class OrderCursorPagination(CursorPagination):<br>    page_size = 20<br>    ordering = &quot;-created_at&quot;</pre><p>Perfect for:</p><ul><li>activity feeds</li><li>logs</li><li>notifications</li></ul><h3>Limit-Offset Pagination</h3><p>Another common style:</p><pre>GET /api/orders?limit=20&amp;offset=40</pre><p>Good for:</p><ul><li>BI tools</li><li>custom frontend controls</li><li>reporting tables</li></ul><p>DRF:</p><pre>from rest_framework.pagination import LimitOffsetPagination</pre><p>Flexible, but still suffers from offset performance issues.</p><h3>Optimizing Paginated Endpoints</h3><p>Pagination alone is not enough.</p><p>Also:</p><h3>Use select_related</h3><pre>queryset.select_related(&quot;customer&quot;)</pre><h3>Use prefetch_related</h3><pre>queryset.prefetch_related(&quot;items&quot;)</pre><p>Keep list endpoints lightweight. <br>Analytics data behaves differently.<br>Instead of paginating raw sales:</p><pre>/api/sales?page=2</pre><p>Paginate aggregated periods:</p><pre>/api/sales?group_by=day&amp;page=2</pre><p>This reduces payload size dramatically.<br>Pagination is not just a UI concern. It’s an API architecture decision. The right strategy keeps your Django API fast, scalable, and user-friendly.</p><p>Choose carefully.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f28557939b30" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-unleashed/pagination-strategies-in-django-rest-apis-beyond-page-numbers-f28557939b30">Pagination Strategies in Django REST APIs: Beyond Page Numbers</a> was originally published in <a href="https://medium.com/django-unleashed">Django Unleashed</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>