Web Framework Internals interview question · Most asked

Describe how FastAPI processes a request and where exceptions are handled.

Summary

ServerErrorMiddleware (outermost) → user middleware (last added runs first) → ExceptionMiddleware with your handlers → router → dependency resolution and Pydantic validation (422 on failure) → endpoint → response serialisation → dependency exit code and background tasks. Exceptions inside the ExceptionMiddleware layer use your handlers; an HTTPException raised in user middleware becomes a 500.

Longer Answer

Put authentication in dependencies, keep middleware for global protocol concerns, and never block the event loop inside async def endpoints.

Key Points

  • Server errors → middleware → exception handlers → router.
  • Dependencies and validation before the endpoint.
  • HTTPException in middleware → 500.
  • Auth in dependencies.

Deep dive: Request Lifecycle: FastAPI and Starlette: Middleware, Exceptions and Dependencies

Explanation

What interviewers look for

Layer order and the middleware exception pitfall.

More most-asked Web Framework Internals questions

← All Web Framework Internals questions