Home Interview Flask vs FastAPI Interview Questions: Python Web Frameworks
Intermediate 6 min · July 13, 2026

Flask vs FastAPI Interview Questions: Python Web Frameworks

Master Flask and FastAPI interview questions with practical examples, debugging tips, and real-world production incidents.

N
Naren Founder & Principal Engineer

20+ years shipping production code across the stack, with years spent interviewing engineers. Written from production experience, not tutorials.

Follow
Production
production tested
July 13, 2026
last updated
2,165
articles · all by Naren
Before you start⏱ 15-20 min read
  • Basic understanding of Python
  • Familiarity with HTTP and REST APIs
  • Experience with at least one web framework (Flask or FastAPI)
 ● Production Incident 🔎 Debug Guide ⚙ Triage Commands
Quick Answer
  • 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.
✦ Definition~90s read
What is Flask and FastAPI Interview Questions?

Flask and FastAPI are Python web frameworks used to build RESTful APIs; Flask is a lightweight synchronous framework, while FastAPI is a modern asynchronous framework with automatic OpenAPI documentation and data validation.

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.
Plain-English First

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.

⚙ Browser compatibility
Latest versions — ✓ supported
ChromeFirefoxSafariEdge

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.'

app_flask.pyPYTHON
1
2
3
4
5
6
7
8
9
10
from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
    return jsonify({'item_id': item_id})

if __name__ == '__main__':
    app.run()
Output
Running on http://127.0.0.1:5000
💡Interview Tip
📊 Production Insight
In production, FastAPI's async nature can lead to subtle bugs if you mix synchronous code without proper thread pooling. Always use async database drivers (e.g., asyncpg) for true async benefits.
🎯 Key Takeaway
Flask is synchronous and flexible; FastAPI is async and auto-documented. Choose based on project needs.

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.

app_fastapi.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from fastapi import FastAPI, Query, Path
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.post('/items/')
async def create_item(item: Item):
    return item

@app.get('/items/{item_id}')
async def read_item(item_id: int = Path(..., ge=1), q: str = Query(None, max_length=50)):
    return {'item_id': item_id, 'q': q}
Output
FastAPI automatically generates OpenAPI docs at /docs
🔥Performance Note
📊 Production Insight
In production, always use Pydantic's BaseModel for request/response schemas to ensure data integrity. FastAPI's validation errors are detailed and can be customized.
🎯 Key Takeaway
FastAPI uses type hints for automatic validation and serialization, reducing boilerplate compared to Flask.

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.

middleware_example.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from fastapi import FastAPI, Request
from starlette.middleware.base import BaseHTTPMiddleware
import time

app = FastAPI()

class LoggingMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        start = time.time()
        response = await call_next(request)
        duration = time.time() - start
        print(f"{request.method} {request.url} - {duration:.2f}s")
        return response

app.add_middleware(LoggingMiddleware)
Output
Logs each request with method, URL, and duration.
⚠ Common Pitfall
📊 Production Insight
In production, avoid logging sensitive data in middleware. Use structured logging (e.g., JSON) for easier debugging.
🎯 Key Takeaway
FastAPI's middleware system is async and more flexible; error handling is built-in with HTTPException and custom handlers.

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.

dependency_example.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from fastapi import FastAPI, Depends, HTTPException, status
from typing import Optional

app = FastAPI()

async def get_db():
    db = Database()  # hypothetical
    try:
        yield db
    finally:
        await db.close()

async def get_current_user(token: str = Depends(oauth2_scheme)):
    user = await fake_decode_token(token)
    if not user:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)
    return user

@app.get('/users/me')
async def read_users_me(current_user: User = Depends(get_current_user)):
    return current_user
Output
Returns current user if token is valid.
💡Interview Tip
📊 Production Insight
In production, use dependency injection for database sessions to prevent connection leaks. Always use context managers (yield) to ensure cleanup.
🎯 Key Takeaway
FastAPI's dependency injection is a powerful tool for managing shared resources and cross-cutting concerns like authentication.

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.

async_vs_sync.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from fastapi import FastAPI
import asyncio

app = FastAPI()

@app.get('/sync')
def read_sync():
    # CPU-bound or blocking I/O
    return {'message': 'sync'}

@app.get('/async')
async def read_async():
    await asyncio.sleep(1)  # non-blocking
    return {'message': 'async'}
Output
Both endpoints work, but async handles more concurrent requests.
⚠ Performance Trap
📊 Production Insight
In production, monitor event loop lag. If you see high latency, check for blocking calls in async endpoints. Use tools like asyncio debug mode.
🎯 Key Takeaway
Use async for I/O-bound operations; use sync for CPU-bound or blocking code, but offload to thread pool if needed.

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.

test_example.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from fastapi.testclient import TestClient
from app import app

client = TestClient(app)

def test_read_item():
    response = client.get('/items/1?q=test')
    assert response.status_code == 200
    assert response.json() == {'item_id': 1, 'q': 'test'}

def test_create_item():
    response = client.post('/items/', json={'name': 'Foo', 'price': 10.5})
    assert response.status_code == 200
    assert response.json()['name'] == 'Foo'
Output
Tests pass if endpoints work correctly.
💡Interview Tip
📊 Production Insight
In production, run tests in CI/CD pipeline. Use coverage tools to ensure high code coverage. For FastAPI, test automatic validation by sending invalid data.
🎯 Key Takeaway
Both frameworks provide test clients; FastAPI's dependency injection makes it easier to mock dependencies.

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.

docker-compose.ymlYAML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
version: '3'
services:
  web:
    build: .
    command: uvicorn app:app --host 0.0.0.0 --port 8000
    ports:
      - "8000:8000"
    environment:
      - DATABASE_URL=postgresql+asyncpg://user:pass@db/dbname
  db:
    image: postgres:13
    environment:
      POSTGRES_USER: user
      POSTGRES_PASSWORD: pass
Output
Starts FastAPI app with PostgreSQL.
🔥Production Tip
📊 Production Insight
In production, set up health check endpoints (e.g., /health) and use orchestration tools like Kubernetes for scaling. Monitor request latency and error rates.
🎯 Key Takeaway
FastAPI is deployed with ASGI servers (Uvicorn); Flask with WSGI servers (Gunicorn). Both can be containerized.

8. Common Interview Questions and Answers

  1. 'Explain the request lifecycle in Flask vs FastAPI.'
  2. - Flask: WSGI server receives request -> creates request context -> calls WSGI app -> before_request hooks -> route handler -> after_request hooks -> returns response.
  3. - FastAPI: ASGI server receives request -> creates ASGI scope -> middleware chain -> route handler (with dependency injection) -> returns response.
  4. 'How do you handle database sessions in FastAPI?'
  5. - Use dependency injection with a generator that yields the session and closes it in finally block. Example: async def get_db(): async with async_session() as session: yield session.
  6. 'What is the difference between @app.route and APIRouter in FastAPI?'
  7. - APIRouter allows modular organization of endpoints. You can include routers with app.include_router().
  8. 'How do you implement authentication in FastAPI?'
  9. - Use OAuth2PasswordBearer or APIKeyHeader dependencies. Validate token and return user.
  10. 'How do you handle CORS in Flask?'
  11. - Use flask-cors extension: from flask_cors import CORS; CORS(app).
  12. 'What are background tasks in FastAPI?'
  13. - BackgroundTasks allow you to run tasks after returning a response. Example: from fastapi import BackgroundTasks.
  14. 'How do you optimize a FastAPI application for high concurrency?'
  15. - Use async endpoints, async database drivers, connection pooling, and avoid blocking calls. Use Gunicorn with multiple Uvicorn workers.
  16. 'How do you test a FastAPI application?'
  17. - Use TestClient from starlette.testclient. Override dependencies for mocking.

In an interview, provide code snippets and explain trade-offs.

auth_example.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer

oauth2_scheme = OAuth2PasswordBearer(tokenUrl='token')

app = FastAPI()

async def get_current_user(token: str = Depends(oauth2_scheme)):
    user = await fake_decode_token(token)
    if not user:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)
    return user

@app.get('/users/me')
async def read_users_me(current_user = Depends(get_current_user)):
    return current_user
Output
Returns user info if token is valid.
💡Interview Tip
📊 Production Insight
In production, use JWT tokens with expiration and refresh tokens. Store secrets securely (e.g., environment variables, vault).
🎯 Key Takeaway
Be prepared to discuss request lifecycle, database sessions, authentication, and testing in both frameworks.
● Production incidentPOST-MORTEMseverity: high

The Async Database Pool Exhaustion

Symptom
Users experienced intermittent 500 errors and timeouts on API requests.
Assumption
The developer assumed that async endpoints automatically handle database connections efficiently.
Root cause
Each request created a new database session without closing it, leading to connection pool exhaustion.
Fix
Implemented dependency injection with FastAPI's Depends to manage session lifecycle, ensuring sessions are closed after each request.
Key lesson
  • 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.
Production debug guideSymptom to Action5 entries
Symptom · 01
Slow response times
Fix
Check for blocking I/O in async endpoints; use async database drivers.
Symptom · 02
500 Internal Server Error
Fix
Enable detailed error logging; check exception handlers.
Symptom · 03
Memory leak
Fix
Verify that database sessions and file handles are closed; use context managers.
Symptom · 04
CORS errors
Fix
Configure CORS middleware properly; check allowed origins.
Symptom · 05
Authentication failures
Fix
Inspect token validation logic; ensure middleware order is correct.
★ Quick Debug Cheat SheetCommon issues and immediate actions for Flask/FastAPI
Endpoint returns 405 Method Not Allowed
Immediate action
Check route decorator methods
Commands
flask routes (Flask) or app.routes (FastAPI)
Check if OPTIONS method is handled
Fix now
Add the missing HTTP method to the route decorator.
Request hangs indefinitely+
Immediate action
Check for synchronous blocking code in async endpoint
Commands
Use asyncio.to_thread or run_in_executor
Check database query execution time
Fix now
Convert blocking I/O to async or use thread pool.
JSON decode error on POST+
Immediate action
Verify Content-Type header is application/json
Commands
print(request.headers) in Flask; print(request.headers) in FastAPI
Check request body with curl -v
Fix now
Set Content-Type header in client request.
CORS error in browser+
Immediate action
Check CORS middleware configuration
Commands
flask-cors or fastapi.middleware.cors
Verify allowed origins, methods, headers
Fix now
Add CORS middleware with appropriate settings.
Database connection pool exhausted+
Immediate action
Check for unclosed sessions
Commands
SHOW PROCESSLIST (MySQL) or pg_stat_activity (PostgreSQL)
Review session management code
Fix now
Use context managers or Depends to close sessions.
FeatureFlaskFastAPI
TypeWSGI (synchronous)ASGI (async)
Auto DocumentationNo (requires extensions)Yes (OpenAPI, Swagger UI)
Data ValidationManualAutomatic via Pydantic
Dependency InjectionNo built-inYes (Depends)
PerformanceLower concurrencyHigh concurrency
Learning CurveLowModerate
CommunityLarge, matureGrowing rapidly
⚙ Quick Reference
8 commands from this guide
FileCommand / CodePurpose
app_flask.pyfrom flask import Flask, jsonify, request1. Core Differences Between Flask and FastAPI
app_fastapi.pyfrom fastapi import FastAPI, Query, Path2. Request Handling and Routing
middleware_example.pyfrom fastapi import FastAPI, Request3. Middleware and Error Handling
dependency_example.pyfrom fastapi import FastAPI, Depends, HTTPException, status4. Dependency Injection in FastAPI vs Flask
async_vs_sync.pyfrom fastapi import FastAPI5. Async vs Sync
test_example.pyfrom fastapi.testclient import TestClient6. Testing Flask and FastAPI Applications
docker-compose.ymlversion: '3'7. Deployment and Production Considerations
auth_example.pyfrom fastapi import FastAPI, Depends, HTTPException, status8. Common Interview Questions and Answers

Key takeaways

1
Flask is a synchronous micro-framework; FastAPI is an async framework with automatic docs and validation.
2
FastAPI's dependency injection simplifies resource management and testing.
3
Use async endpoints for I/O-bound tasks; offload CPU-bound tasks to thread pools.
4
Proper session management is critical to avoid connection pool exhaustion.
5
Both frameworks have robust testing support; FastAPI's dependency overrides make mocking easy.

Common mistakes to avoid

5 patterns
×

Using 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 PREP · PRACTICE MODE

Interview Questions on This Topic

Q01SENIOR
Explain the request lifecycle in Flask and FastAPI.
Q02SENIOR
How do you implement a database session dependency in FastAPI?
Q03JUNIOR
What are the advantages of FastAPI over Flask?
Q04SENIOR
How do you handle authentication in FastAPI?
Q05SENIOR
How do you test a FastAPI application?
Q01 of 05SENIOR

Explain the request lifecycle in Flask and FastAPI.

ANSWER
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.
FAQ · 5 QUESTIONS

Frequently Asked Questions

01
What is the main difference between Flask and FastAPI?
02
Can Flask handle async requests?
03
How does FastAPI handle request validation?
04
What is dependency injection in FastAPI?
05
How do you deploy a FastAPI application?
COMPLETE GUIDE
FastAPI Complete Guide — Interactive Tutorial for Production APIs →

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.

N
Naren Founder & Principal Engineer

20+ years shipping production code across the stack, with years spent interviewing engineers. Written from production experience, not tutorials.

Follow
Verified
production tested
July 13, 2026
last updated
2,165
articles · all by Naren
🔥

That's Python Interview. Mark it forged?

6 min read · try the examples if you haven't

Previous
Python Async/Await Interview Questions
6 / 6 · Python Interview
Next
Top 50 JavaScript Interview Q