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
FastAPI Dependency Injection Explained
More Relevant Posts
-
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
-
-
VectorForge tracks query latency percentiles without storing every query time. Here is the structure that makes that possible: Tracking latency percentiles like p50, p95, and p99 is essential for understanding system behavior under real load. p50 (median) tells you what the typical user experiences, while p95 and p99 tell you how bad the slowest requests get. If your p99 latency is two orders of magnitude higher than p50, you have a long tail problem that averages mask. The naive approach would be to log every query time to a database and compute percentiles on demand. That creates write overhead and unbounded storage growth. Instead I use a fixed size rolling window with `collections.deque(maxlen=1000)`. A deque is a double ended queue, and with `maxlen` set it automatically evicts the oldest entry when new items are added. This gives me the last 1000 query times at constant memory cost. When the metrics endpoint is called I compute percentiles on demand using `numpy.percentile()` over the current deque contents. This is cheap enough to run per request and accurate enough for operational dashboards. The window is large enough to smooth out short spikes but small enough to reflect current behavior rather than ancient history. VectorForge stores this deque in the `EngineMetrics` dataclass alongside lifetime counters. The deque is session scoped (it resets on restart), while counters are persisted to SQLite. This separation reflects their different purposes: counters track total activity over time, the deque tracks recent latency distribution. This pattern is simple, memory efficient, and gives actionable observability without complexity or cost. #VectorForge #Observability #Percentiles #Python #Metrics #PerformanceEngineering #Deque
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
-
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
-
One of the most common FastAPI mistakes is reusing SQLAlchemy models as Pydantic response schemas. This doesn't just couple your layers—it makes it easy to accidentally expose fields like hashed passwords. In my latest post, I share 8 Sections of battle-tested patterns for structuring your FastAPI applications: 1️⃣ Centralized Config: Using pydantic-settings instead of scattered os.environ calls. 2️⃣ Dependency Injection: Leveraging Depends() for cleaner auth and DB sessions. 3️⃣ Business Logic: Moving core logic into pure Python service functions for easier unit testing. 4️⃣ Error Handling: Using app-level exception handlers to remove "try/except" noise from routes. Swipe through the PDF for the code examples and folder structures! ➡️ #FastAPI #Python #BackendDevelopment #WebDevelopment #CleanCode
To view or add a comment, sign in
-
Most semantic layers require you to define everything manually. Table name. Join paths. Time dimension. Filter fields. Tags. One by one, in YAML, hoping you don't miss anything. With the OnlyMetrix Open Source Python SDK, you hand it a SQL query. It hands you back a complete metric definition, source tables extracted, time column detected, filters inferred, tags generated. The compiler reads the SQL. Finds users and events as source tables. Identifies event_date as the time column. Extracts e.event_date and u.status as filterable fields. Tags it as cardinality, customers, engagement. You wrote the query. The SDK built the semantic layer. This is what it means to have a compiler underneath your metrics, not just a definition store, but something that understands what your SQL is actually doing. #onlymetrix #contextengineering #semanticlayer #dataengineering #dbt
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 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
-
-
🚀 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
-
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