These past few days I've been diving into middleware in FastAPI — and honestly it clicked better than I expected. I implemented 4 types: → CORS — to control which frontends can talk to my API → GZip — to compress large responses and reduce payload size → HTTPS Redirect — to force secure connections automatically → Custom Timer Middleware — my favorite one, built from scratch using BaseHTTPMiddleware The custom one was the most interesting. I wrapped every request with a timer to measure how long each endpoint takes to respond. Something like this: start = time.time() response = await call_next(request) duration = time.time() - start Simple concept, but it made me realize how powerful middleware is — you intercept every request and response without touching a single endpoint. One thing that surprised me: even a basic loop of 10 million iterations is visible in the timing output. That's when I understood why performance monitoring at the middleware level actually matters in production. Still learning, but these small wins keep me going. Code here if you want to check it out 👇 https://lnkd.in/e773_smX #FastAPI #Python #WebDevelopment #BackendDevelopment #Learning
Implementing Middleware in FastAPI for Performance Monitoring
More Relevant Posts
-
🚀 Sync vs Async in FastAPI — What I finally understood When I started using FastAPI, I kept seeing "def" vs "async def"… But the real difference clicked only after I faced performance issues. 🔍 Here’s the simple breakdown: 👉 Sync (def) - Executes one request at a time (blocking) - If a task takes time, everything waits - Best for CPU-heavy operations 👉 Async (async def) - Handles multiple requests concurrently (non-blocking) - Doesn’t wait idle during I/O tasks - Perfect for DB calls, API calls, file operations 💡 Real insight: I had an API that was slow because of waiting operations. Switching to async reduced response time significantly. ⚡ Rule I follow now: - CPU work → use sync - I/O work → use async 📌 Biggest takeaway: Async doesn’t make your code “faster” — it makes your API handle more requests efficiently. --- If you're building APIs with FastAPI, understanding this is a game changer. #fastapi #python #backenddevelopment #webdevelopment #async #softwaredeveloper
To view or add a comment, sign in
-
-
Tired of scattering print() statements across your FastAPI code just to chase down one bug? You restart the server. Hit the endpoint. Squint at logs. Still no idea what broke. The real issue? Most tutorials show debugging on a single main.py. The moment you have a subdirectory structure, a .venv, and a .env file, the same config silently breaks. Breakpoints don't fire. VS Code loads the wrong interpreter. You get "Could not import module" and have no idea why. Once I got the setup right, everything changed: ✅ Breakpoints that actually trigger on every request ✅ Live variable inspection mid-request — no prints needed ✅ Call stack navigation to see exactly how you got there ✅ Conditional breakpoints that pause only when a specific condition is true Zero changes to your source code. Please commit launch.json once; your whole team will get it. I wrote a full guide covering: 🔧 The exact launch.json that works and the one field most configs get wrong. 🐛 A 5-step mental model: if debugging fails, one of these broke. 🐳 Remote debugging inside Docker with debugpy. ⚡ Logpoints, conditional breakpoints, and exception pausing. If your breakpoints never hit, you'll recognize the fix within the first two minutes of reading. 👉 https://lnkd.in/ew4ueC8Z #FastAPI #Python #VSCode #Debugging #BackendEngineering
To view or add a comment, sign in
-
-
Exploring FastAPI and tried applying it to a real-world problem. In many clinics, patient records are still stored on paper, making them hard to manage and update. So I began building a Patient Management System API. What I implemented: • Stored patient data in a JSON file (simulating a database) • Built a GET endpoint to retrieve all patient records • Understood how client-server interaction works What I learned: • Difference between static and dynamic software • CRUD operations and how they map to HTTP methods (GET, POST, PUT, DELETE) • How APIs power real-world applications This felt like a shift from just learning concepts to actually thinking in systems. Next step: Adding POST, PUT, DELETE endpoints and expanding functionality. #FastAPI #BackendDevelopment #Python #APIs #MachineLearning
To view or add a comment, sign in
-
-
𝗙𝗮𝘀𝘁𝗔𝗣𝗜 𝗶𝘀𝗻'𝘁 𝗳𝗮𝘀𝘁 𝗯𝗲𝗰𝗮𝘂𝘀𝗲 𝗼𝗳 𝗙𝗮𝘀𝘁𝗔𝗣𝗜. 𝗜𝘁'𝘀 𝗳𝗮𝘀𝘁 𝗯𝗲𝗰𝗮𝘂𝘀𝗲 𝗼𝗳 𝘄𝗵𝗮𝘁'𝘀 𝘂𝗻𝗱𝗲𝗿𝗻𝗲𝗮𝘁𝗵. Most people stop at "FastAPI is faster than Flask." Few ask 𝘸𝘩𝘺. Here's what's actually happening: 𝗙𝗹𝗮𝘀𝗸 runs on 𝗪𝗦𝗚𝗜. One request = one thread = blocked until done. Your thread waits while the DB responds. It does nothing. Just sits there. 𝗙𝗮𝘀𝘁𝗔𝗣𝗜 runs on 𝗔𝗦𝗚𝗜. One thread handles 𝘵𝘩𝘰𝘶𝘴𝘢𝘯𝘥𝘴 of connections. While one request waits for DB, the thread picks up another. No idle time. But FastAPI doesn't do this alone. The real stack: • 𝗨𝘃𝗶𝗰𝗼𝗿𝗻 — the ASGI server (built on uvloop) • 𝗦𝘁𝗮𝗿𝗹𝗲𝘁𝘁𝗲 — the async engine (handles requests, WebSockets, middleware) • 𝗙𝗮𝘀𝘁𝗔𝗣𝗜 — the developer layer (validation, docs, type hints) Think of it this way: Starlette = 𝘵𝘩𝘦 𝘦𝘯𝘨𝘪𝘯𝘦. FastAPI = 𝘵𝘩𝘦 𝘥𝘢𝘴𝘩𝘣𝘰𝘢𝘳𝘥. Uvicorn = 𝘵𝘩𝘦 𝘧𝘶𝘦𝘭. Flask was built for a 𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 world. FastAPI was built for an 𝗮𝘀𝘆𝗻𝗰-𝗳𝗶𝗿𝘀𝘁 world. The speed difference isn't a feature. It's a 𝗳𝗼𝘂𝗻𝗱𝗮𝘁𝗶𝗼𝗻 difference. Next time someone says "FastAPI is fast", ask them: 𝘐𝘴 𝘪𝘵 𝘍𝘢𝘴𝘵𝘈𝘗𝘐, 𝘰𝘳 𝘪𝘴 𝘪𝘵 𝘚𝘵𝘢𝘳𝘭𝘦𝘵𝘵𝘦? #FastAPI #Flask #Starlette #Python #AsyncProgramming #BackendEngineering #SystemDesign #SoftwareEngineering
To view or add a comment, sign in
-
The Request Lifecycle & Dependency Injection In FastAPI, the Depends() function is more than just a helper; it’s a system that manages the execution requirements of your endpoints. When you inject a dependency, FastAPI performs a few critical steps behind the scenes: 1. Sub-dependency Resolution: If your get_current_user dependency requires a get_db dependency, FastAPI resolves the entire tree before your endpoint logic ever executes. 2. Result Caching: By default, if multiple dependencies require the same sub-dependency (like a database session) within a single request, FastAPI executes it once and shares the result (cache). 3. Yield and Cleanup: Using yield instead of return allows you to execute "teardown" logic (like closing a database connection or a file) after the response has been sent to the client. This pattern ensures that resources are never leaked, even if the request fails mid-way. #FastAPI #Python #BackendEngineering #SoftwareArchitecture #API #SystemDesign
To view or add a comment, sign in
-
-
FastAPI handles so much under the hood that it’s easy to miss how powerful this is. Understanding how dependencies are resolved and managed really helps avoid a lot of hidden bugs. #FastAPI #Python #BackendDevelopment #APIDesign
The Request Lifecycle & Dependency Injection In FastAPI, the Depends() function is more than just a helper; it’s a system that manages the execution requirements of your endpoints. When you inject a dependency, FastAPI performs a few critical steps behind the scenes: 1. Sub-dependency Resolution: If your get_current_user dependency requires a get_db dependency, FastAPI resolves the entire tree before your endpoint logic ever executes. 2. Result Caching: By default, if multiple dependencies require the same sub-dependency (like a database session) within a single request, FastAPI executes it once and shares the result (cache). 3. Yield and Cleanup: Using yield instead of return allows you to execute "teardown" logic (like closing a database connection or a file) after the response has been sent to the client. This pattern ensures that resources are never leaked, even if the request fails mid-way. #FastAPI #Python #BackendEngineering #SoftwareArchitecture #API #SystemDesign
To view or add a comment, sign in
-
-
What if every node in your knowledge graph could talk, and what they say dictates how the network evolves? Holonic v0.3.0 is live 🚀 What's new? - 📦 pip install holonic (conda coming soon) - 📄Sphinx docs with full API reference -🧪 Expanded test coverage across backends and traversal paths -📓 New example notebooks (portal traversal, translation, visualization) Built on rdflib + Apache Jena Fuseki, with a pluggable GraphBackend protocol if you want to bring your own quad store (more coming soon!). Portals are RDF triples, discovered via SPARQL. Traversal runs CONSTRUCT queries. Nothing magic, nothing hidden, FULL provenance. Still early (5 ⭐ and 0 issues) so if you're doing anything in the knowledge graph / semantic web space and want to take a test drive, I'd genuinely appreciate it. 🔗 github.com/zwelz3/holonic #RDF #KnowledgeGraphs #SemanticWeb #Python #OpenSource
To view or add a comment, sign in
-
-
One pattern that changed how I build FastAPI backends: Stop returning raw database models from your endpoints. When your API response mirrors your ORM model 1:1, you're creating tight coupling between your database schema and your API contract. One schema change can break every client. The fix: dedicated Pydantic response models per endpoint. Here's what you get: 1. Auto-generated OpenAPI docs that actually match your responses 2. A clear data boundary - internal fields stay internal 3. Freedom to refactor your DB without touching your API contract Bonus: Pydantic's model_validator and computed fields let you shape responses exactly how your frontend needs them - no extra serialization logic scattered across your codebase. What patterns have saved you the most headaches in your backend work? #Python #FastAPI #WebDevelopment #SoftwareEngineering #FullStackDeveloper
To view or add a comment, sign in
-
Most operational software I encounter wasn't built to talk to anything else. With FastAPI, you can build a lightweight API layer on top of almost any system, whether it's a database, a legacy application, or a third-party platform. Once that layer is in place, other systems can pull data from it, push data to it, or trigger actions automatically. The result isn't just a technical improvement. It means processes that used to require manual exports, emails back and forth, or someone running a report every morning can simply run on their own. The only thing required is a small Python application. Deployed, maintained, and adapted when business requirements change. No large dev team needed. How many manual actions does your most painful data process require? Drop a number below! D-Data #Python #FastAPI #DataEngineering #SoftwareEngineering #BusinessAutomation #APIIntegration
To view or add a comment, sign in
-
🎯 Precision Engineering: Beyond Basic Queries "A great API doesn't just give you data—it gives you the right data, or a clear reason why it can't. 🛡️ Today I expanded my TodoApp by implementing Path Parameters. Moving beyond fetching 'all' records, I’ve added logic to retrieve specific tasks by their ID. Key technical highlights from this update: ✅ Input Validation: Used FastAPI’s Path to ensure only valid IDs (greater than 0) are processed. ✅ Robust Error Handling: Integrated HTTPException to return a clean 404 Not Found status if a user requests an ID that doesn't exist. ✅ Clean Code: Refactored using Annotated dependencies to keep the route handlers lean and readable. Building a backend isn't just about the 'Happy Path'—it's about handling every edge case with precision. Next: Implementing POST requests to allow users to create their own tasks! 🚀" #FastAPI #Python #BackendDevelopment #WebAPI #CleanCode #SoftwareEngineering
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development