Flask vs FastAPI Interview Questions: Python Web Frameworks
Master Flask and FastAPI interview questions with practical examples, debugging tips, and real-world production incidents.
20+ years shipping production code across the stack, with years spent interviewing engineers. Written from production experience, not tutorials.
- ✓Basic understanding of Python
- ✓Familiarity with HTTP and REST APIs
- ✓Experience with at least one web framework (Flask or FastAPI)
- Flask is a micro-framework with flexibility; FastAPI is modern, async, and auto-generates OpenAPI docs.
- Key differences: Flask uses WSGI, FastAPI uses ASGI; FastAPI has built-in validation with Pydantic.
- Common interview topics: routing, request handling, middleware, dependency injection, async vs sync.
- Performance: FastAPI is faster due to async; Flask is simpler for small apps.
- Both support RESTful APIs, but FastAPI is preferred for high-concurrency services.
Think of Flask as a basic toolbox where you pick each tool yourself, while FastAPI is a smart toolbox that organizes your tools and even writes instructions for others to use them. Flask gives you freedom; FastAPI gives you speed and automatic documentation.
| Chrome | Firefox | Safari | Edge |
|---|---|---|---|
| ✓ | ✓ | ✓ | ✓ |
When interviewing for Python backend roles, you'll likely face questions about Flask and FastAPI—two of the most popular web frameworks. Flask has been a staple for years, known for its simplicity and flexibility. FastAPI, a newer entrant, has gained massive traction for its performance, automatic OpenAPI documentation, and async support. Interviewers want to know not just the syntax but your understanding of architectural differences, request lifecycle, middleware, dependency injection, and error handling. They'll probe how you'd design a REST API, handle database sessions, manage authentication, and optimize for concurrency. This guide covers the most common interview questions, with code examples, complexity analysis, and tips to stand out. You'll learn how to explain the trade-offs between Flask and FastAPI, when to use each, and how to debug production issues. We'll also walk through a real-world production incident where a simple async mistake caused a cascade failure. By the end, you'll be ready to tackle any Flask or FastAPI interview question with confidence.
1. Core Differences Between Flask and FastAPI
Flask is a WSGI micro-framework that has been around since 2010. It's minimalistic, giving you the freedom to choose your own components (ORM, authentication, etc.). FastAPI, released in 2018, is an ASGI framework built on Starlette and Pydantic. It supports asynchronous request handling out of the box, automatic OpenAPI and JSON Schema documentation, and data validation via Pydantic models. In an interview, you should highlight that Flask is synchronous by default, while FastAPI is async-first. Flask can be made async with extensions like Quart, but FastAPI is natively async. FastAPI also has built-in dependency injection, which simplifies tasks like database session management and authentication. Flask requires manual setup for such features. Performance-wise, FastAPI can handle more concurrent requests due to its async nature, making it suitable for I/O-bound applications. However, Flask's simplicity makes it ideal for small projects, prototypes, or when you need maximum control. Interviewers often ask: 'When would you choose Flask over FastAPI?' A good answer: 'Flask for simple APIs or when team is more familiar with synchronous code; FastAPI for high-performance, data-intensive APIs with automatic docs.'
2. Request Handling and Routing
Both frameworks handle HTTP requests, but with different paradigms. Flask uses decorators to map URLs to functions. FastAPI also uses decorators but leverages Python type hints for automatic request validation and serialization. For example, in FastAPI, you can define query parameters, path parameters, and request bodies using Pydantic models. Flask requires manual parsing of request data. In an interview, you might be asked to write a simple CRUD endpoint. Show how FastAPI reduces boilerplate. Also discuss how FastAPI supports dependency injection for shared logic (e.g., database sessions). Flask has decorators for before_request and after_request, but they are less structured. FastAPI's dependencies can be reused across endpoints and even nested. Another common question: 'How do you handle file uploads?' Flask uses request.files; FastAPI uses UploadFile from Starlette. FastAPI's UploadFile is async and provides a file-like interface. For routing, both support path parameters and query parameters. FastAPI automatically validates types and generates errors. Flask requires manual validation. In an interview, emphasize that FastAPI's automatic validation reduces bugs and speeds up development.
3. Middleware and Error Handling
Middleware in Flask is typically implemented using before_request and after_request hooks, or by subclassing the WSGI app. FastAPI uses Starlette's middleware system, which is more flexible and supports async. Common middleware includes CORS, authentication, logging, and request timing. In an interview, you might be asked to implement a simple logging middleware. Show how to do it in both frameworks. For error handling, Flask uses @app.errorhandler decorator; FastAPI uses exception handlers with @app.exception_handler. FastAPI also allows you to raise HTTPException with status codes and detail messages. A key difference: FastAPI's exception handlers can be async. Also, FastAPI automatically handles validation errors (422 Unprocessable Entity) from Pydantic. In production, you should customize error responses to avoid leaking internal details. Another common question: 'How do you handle CORS?' Both frameworks have extensions: Flask-CORS and FastAPI's CORSMiddleware. FastAPI's middleware is built-in. Discuss how to configure allowed origins, methods, and headers. Interviewers may ask about rate limiting or authentication middleware. For authentication, FastAPI's dependency injection makes it easy to create reusable auth dependencies. Flask often uses decorators or before_request hooks.
4. Dependency Injection in FastAPI vs Flask
FastAPI's dependency injection system is one of its standout features. It allows you to define reusable components (e.g., database sessions, authentication, configuration) that can be injected into path operation functions. Dependencies can be functions or classes, and they can have their own dependencies, creating a hierarchy. Flask does not have built-in dependency injection; you typically use global variables, application context, or Flask's g object. In an interview, you might be asked to implement a database session dependency. Show how FastAPI's Depends ensures that sessions are properly closed after each request. For Flask, you'd use a before_request hook to create a session and an after_request hook to close it. FastAPI's system is more testable because you can override dependencies during testing. Another common question: 'How do you handle authentication?' In FastAPI, you can create a dependency that extracts and validates a token, then returns the current user. In Flask, you'd use a decorator or before_request. Dependency injection also simplifies permission checks. Interviewers appreciate when you mention that FastAPI's dependencies can be async, allowing for async database queries or external API calls during injection.
5. Async vs Sync: When and How to Use
FastAPI supports both async and sync path operations. If you define a function with async def, it runs in the event loop. If you use def, it runs in a thread pool. This is crucial for performance: I/O-bound tasks (database queries, HTTP calls) should be async, while CPU-bound tasks should be sync or offloaded to a thread pool. Flask is synchronous by default, but you can use Quart (an async version of Flask) or run Flask with Gunicorn and gevent for async-like behavior. In an interview, you might be asked: 'How do you handle long-running tasks in FastAPI?' You can use BackgroundTasks or Celery. FastAPI has built-in BackgroundTasks for simple post-processing. For heavy tasks, use a task queue. Another common question: 'What happens if you call a synchronous library inside an async endpoint?' It blocks the event loop, reducing concurrency. Use asyncio.to_thread or run_in_executor to offload. Interviewers may ask about the Global Interpreter Lock (GIL) in Python. Explain that async I/O bypasses the GIL for I/O-bound tasks, but CPU-bound tasks still suffer. For CPU-bound, use multiprocessing or async with thread pool. Also discuss that FastAPI's async support is built on Starlette, which uses asyncio. Flask's WSGI is synchronous, so it handles one request per thread. For high concurrency, FastAPI is superior.
6. Testing Flask and FastAPI Applications
Testing is a critical part of the interview. For Flask, you can use the built-in test client: app.test_client(). For FastAPI, use TestClient from Starlette (or httpx). Both allow you to simulate HTTP requests without running a server. In an interview, you might be asked to write a test for an endpoint. Show how to test status codes, response bodies, and headers. For FastAPI, you can also test dependency overrides. Another common question: 'How do you test database interactions?' Use a test database or mock the database session. FastAPI's dependency injection makes it easy to swap out the database dependency for a test version. Flask's app context can be used to push a test context. Also discuss integration tests vs unit tests. For async endpoints in FastAPI, the TestClient handles async internally, but you can also use async tests with pytest-asyncio. Interviewers appreciate when you mention that you should test error cases (e.g., invalid input, missing authentication). For Flask, you can test error handlers. For FastAPI, test validation errors (422). Also discuss how to test middleware. In production, you should have a comprehensive test suite that covers all endpoints. Mention that you can use pytest fixtures for reusable test setup.
7. Deployment and Production Considerations
Deploying Flask vs FastAPI involves different servers. Flask typically runs with Gunicorn (WSGI) or uWSGI. FastAPI runs with Uvicorn (ASGI) or Gunicorn with Uvicorn workers. In an interview, you might be asked: 'How do you deploy a FastAPI app in production?' Use Uvicorn with Gunicorn as a process manager: gunicorn -k uvicorn.workers.UvicornWorker app:app. For Flask, use gunicorn app:app. Also discuss environment variables, configuration management, and logging. Another common question: 'How do you handle database migrations?' Both frameworks can use Alembic (SQLAlchemy) or other migration tools. FastAPI's async support requires async database drivers; for SQLAlchemy, use asyncpg or aiosqlite. Discuss connection pooling and session management. Also talk about containerization with Docker. Both frameworks can be containerized easily. For production, you should set up reverse proxy (Nginx), SSL, and monitoring. Interviewers may ask about scaling: FastAPI's async nature allows it to handle more concurrent connections with fewer resources. Flask can be scaled horizontally with multiple workers. Discuss health checks, graceful shutdowns, and logging. Mention that FastAPI's automatic OpenAPI docs can be disabled in production for security. Also discuss rate limiting, authentication, and input validation as security measures.
8. Common Interview Questions and Answers
Here are some frequently asked questions with concise answers:
- 'Explain the request lifecycle in Flask vs FastAPI.'
- - Flask: WSGI server receives request -> creates request context -> calls WSGI app -> before_request hooks -> route handler -> after_request hooks -> returns response.
- - FastAPI: ASGI server receives request -> creates ASGI scope -> middleware chain -> route handler (with dependency injection) -> returns response.
- 'How do you handle database sessions in FastAPI?'
- - Use dependency injection with a generator that yields the session and closes it in finally block. Example: async def
get_db(): async withasync_session()as session: yield session. - 'What is the difference between @app.route and APIRouter in FastAPI?'
- - APIRouter allows modular organization of endpoints. You can include routers with
app.include_router(). - 'How do you implement authentication in FastAPI?'
- - Use OAuth2PasswordBearer or APIKeyHeader dependencies. Validate token and return user.
- 'How do you handle CORS in Flask?'
- - Use flask-cors extension: from flask_cors import CORS; CORS(app).
- 'What are background tasks in FastAPI?'
- - BackgroundTasks allow you to run tasks after returning a response. Example: from fastapi import BackgroundTasks.
- 'How do you optimize a FastAPI application for high concurrency?'
- - Use async endpoints, async database drivers, connection pooling, and avoid blocking calls. Use Gunicorn with multiple Uvicorn workers.
- 'How do you test a FastAPI application?'
- - Use TestClient from starlette.testclient. Override dependencies for mocking.
In an interview, provide code snippets and explain trade-offs.
The Async Database Pool Exhaustion
- Always manage database sessions explicitly in async endpoints.
- Use FastAPI's Depends to inject and close resources automatically.
- Monitor connection pool metrics in production.
- Test under load to catch resource leaks.
- Prefer async database drivers (e.g., asyncpg, databases) with FastAPI.
flask routes (Flask) or app.routes (FastAPI)Check if OPTIONS method is handled| File | Command / Code | Purpose |
|---|---|---|
| app_flask.py | from flask import Flask, jsonify, request | 1. Core Differences Between Flask and FastAPI |
| app_fastapi.py | from fastapi import FastAPI, Query, Path | 2. Request Handling and Routing |
| middleware_example.py | from fastapi import FastAPI, Request | 3. Middleware and Error Handling |
| dependency_example.py | from fastapi import FastAPI, Depends, HTTPException, status | 4. Dependency Injection in FastAPI vs Flask |
| async_vs_sync.py | from fastapi import FastAPI | 5. Async vs Sync |
| test_example.py | from fastapi.testclient import TestClient | 6. Testing Flask and FastAPI Applications |
| docker-compose.yml | version: '3' | 7. Deployment and Production Considerations |
| auth_example.py | from fastapi import FastAPI, Depends, HTTPException, status | 8. Common Interview Questions and Answers |
Key takeaways
Common mistakes to avoid
5 patternsUsing synchronous database drivers in async endpoints
Not closing database sessions after request
Mixing sync and async code incorrectly
Forgetting to add CORS middleware
Hardcoding configuration values
Interview Questions on This Topic
Explain the request lifecycle in Flask and FastAPI.
Frequently Asked Questions
Every FastAPI concept with runnable in-browser examples — params, Pydantic, dependency injection, JWT auth, async, SQLAlchemy, testing, WebSockets, and Docker deployment. The interactive reference for production engineers.
20+ years shipping production code across the stack, with years spent interviewing engineers. Written from production experience, not tutorials.
That's Python Interview. Mark it forged?
6 min read · try the examples if you haven't