0
0
FastAPIframework~20 mins

Connection lifecycle management in FastAPI - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Connection Lifecycle Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
lifecycle
intermediate
2:00remaining
What happens when a FastAPI dependency uses yield?

Consider a FastAPI dependency function that uses yield to provide a database connection. What is the behavior of this dependency during a request?

FastAPI
from fastapi import Depends, FastAPI
from contextlib import asynccontextmanager

app = FastAPI()

@asynccontextmanager
def get_db():
    db = "db connection"
    try:
        yield db
    finally:
        print("Closing db connection")

@app.get("/items/")
async def read_items(db=Depends(get_db)):
    return {"db": db}
AThe code opens the connection before the request and closes it after the response is sent.
BThe connection is opened and closed multiple times during the request processing.
CThe connection is never closed because yield does not support cleanup.
DThe connection is opened after the response is sent.
Attempts:
2 left
💡 Hint

Think about how yield works in Python generators and how FastAPI uses it for dependencies.

state_output
intermediate
2:00remaining
What is the output when a FastAPI dependency raises an exception after yield?

Given this FastAPI dependency that yields a resource and then raises an exception in the cleanup code, what happens when the endpoint is called?

FastAPI
from fastapi import Depends, FastAPI

app = FastAPI()

def resource():
    print("Setup resource")
    yield "resource"
    print("Cleanup resource")
    raise RuntimeError("Error during cleanup")

@app.get("/test")
async def test(dep=Depends(resource)):
    return {"message": "success"}
AThe endpoint returns {"message": "success"} and logs the cleanup error after response.
BThe endpoint never runs the cleanup code because of the exception.
CThe endpoint returns an error response with status 500 immediately.
DThe endpoint raises RuntimeError and does not return a response.
Attempts:
2 left
💡 Hint

Consider when the cleanup code after yield runs in FastAPI dependencies.

🔧 Debug
advanced
2:00remaining
Why does this FastAPI dependency not close the connection?

Examine this FastAPI dependency that tries to open and close a connection. Why does the connection never close?

FastAPI
from fastapi import Depends, FastAPI

app = FastAPI()

def get_conn():
    conn = "open connection"
    return conn
    print("Closing connection")

@app.get("/data")
async def data(conn=Depends(get_conn)):
    return {"conn": conn}
AThe dependency must use yield to open and close connections properly.
BFastAPI requires async functions for dependencies to close connections.
CThe print statement after return never runs, so connection is never closed.
DThe connection closes automatically after the request without explicit code.
Attempts:
2 left
💡 Hint

Think about what happens to code after a return statement in Python functions.

🧠 Conceptual
advanced
2:00remaining
How does FastAPI manage lifespan events for connections?

FastAPI allows defining lifespan events to manage resources like database connections. Which statement best describes how lifespan events work?

ALifespan events run before and after every request to open and close connections.
BLifespan events run code once when the app starts and once when it shuts down, managing global resources.
CLifespan events are deprecated and replaced by dependencies with yield.
DLifespan events only run if the app uses synchronous endpoints.
Attempts:
2 left
💡 Hint

Think about app startup and shutdown phases versus request handling.

component_behavior
expert
3:00remaining
What is the behavior of nested FastAPI dependencies with yield?

Given two nested dependencies where the outer depends on the inner, both using yield to manage connections, what is the order of opening and closing connections during a request?

FastAPI
from fastapi import Depends, FastAPI

app = FastAPI()

def inner_conn():
    print("Open inner connection")
    yield "inner"
    print("Close inner connection")

def outer_conn(inner=Depends(inner_conn)):
    print("Open outer connection")
    yield f"outer uses {inner}"
    print("Close outer connection")

@app.get("/nested")
async def nested(dep=Depends(outer_conn)):
    return {"connection": dep}
AOpen outer, open inner, close inner, close outer
BOpen inner, open outer, close inner, close outer
COpen outer, open inner, close outer, close inner
DOpen inner, open outer, close outer, close inner
Attempts:
2 left
💡 Hint

Consider how Python generators and context managers nest when using yield in dependencies.