Flask Interview Questions and Answers
Last updated 2026-11-19
Flask gives you routing and a request object and leaves the rest to you, which is why interviewers use it to see how you make design decisions. They ask about the application and request contexts, how you organise a growing project with blueprints and an app factory, how you manage a database session safely, and how you run it in production without the development server.
Answers here use Flask 3 and SQLAlchemy 2 style. For a comparison with the other Python web frameworks, see the Django and FastAPI pages, and read how to crack a Python interview for language-level preparation.
| Version covered | Flask 3.x, Werkzeug 3, SQLAlchemy 2 |
|---|---|
| Core topics | Contexts, blueprints, app factory, sessions, testing, deployment |
| Questions here | 17 |
The micro-framework question
Almost every Flask interview starts with "what does micro mean". It means the core stays small and you choose the database layer, form handling and authentication, usually through extensions such as Flask-SQLAlchemy, Flask-Migrate and Flask-Login. The trade-off is flexibility against having to decide and assemble things yourself, and a good answer names a project where each choice mattered.
Mistakes that show up in code reviews
- Building the app at import time in one file, which makes testing and configuration hard.
- Running app.run with debug enabled in production, which exposes an interactive debugger.
- Using a global database connection instead of a request-scoped session.
- Storing sensitive data in the session cookie, which is signed but not encrypted.
Flask Interview Questions and Answers: questions with worked answers
1 What is Flask and how does a minimal app look?
easyFlask is a WSGI micro-framework built on Werkzeug for routing and requests and Jinja for templates. You create an application object, register routes with decorators and return a string, a dict, which Flask serialises to JSON, or a Response. Start the development server with flask run. The development server is for local work only.
pythonfrom flask import Flask app = Flask(__name__) @app.get("/hello/<name>") def hello(name): return {"message": f"hello {name}"}2 How do you read request data in Flask?
easyThe request proxy exposes request.args for the query string, request.form for form fields, request.get_json() for a JSON body, request.files for uploads, request.headers and request.cookies. get_json returns None or raises a 415 or 400 error when the content type or body is wrong, depending on the options. Always validate input, because Flask does not do it for you.
3 Explain the application context and request context.
mediumThe request context holds request and session and exists while a request is handled. The application context holds current_app and g and is pushed with it, or by itself in a CLI command or a worker. They are stored in context variables, which is why you can use the request proxy as a global in a function without passing it around, and why using them outside a context raises "Working outside of application context". Use app.app_context() in scripts.
pythonwith app.app_context(): db.create_all() # current_app is available here4 What is the application factory pattern and why use it?
mediumA create_app function builds and configures an app instance, initialises extensions with init_app and registers blueprints. It lets you create separate apps with different configs for tests and production, avoids circular imports from a global app object and is what flask run discovers. The extension objects are created at module level without an app.
pythondb = SQLAlchemy() def create_app(config=None): app = Flask(__name__) app.config.from_object("config.Default") if config: app.config.update(config) db.init_app(app) from .users import bp as users_bp app.register_blueprint(users_bp, url_prefix="/users") return app5 What are blueprints?
mediumA blueprint groups routes, templates, static files and error handlers for one feature, and is registered on the app with an optional URL prefix. It makes large apps modular and reusable. Endpoint names are prefixed with the blueprint name, so url_for("users.profile") refers to the profile view in the users blueprint.
6 How do before_request, after_request and teardown_request differ?
mediumbefore_request runs before each view, and if it returns a response, the view is skipped, which suits authentication checks. after_request receives and must return the response, which suits adding headers. teardown_request and teardown_appcontext run at the end whether or not an exception occurred, which is the place to release resources such as a database session.
7 How do you manage a database session with SQLAlchemy 2 in Flask?
mediumUse Flask-SQLAlchemy, which provides a scoped session tied to the app context and removes it on teardown, or create one session per request manually. Use 2.0-style select statements and db.session.execute, commit explicitly, and roll back on error. Never share a session between threads or requests.
pythonfrom sqlalchemy import select @bp.get("/<int:user_id>") def show(user_id): user = db.session.get(User, user_id) or abort(404) posts = db.session.scalars(select(Post).where(Post.user_id == user.id).limit(20)).all() return {"name": user.name, "posts": [p.title for p in posts]}8 How do sessions work in Flask?
mediumThe default session stores data in a cookie that is signed with SECRET_KEY, so users can read it but not change it. It is not encrypted, so do not put secrets in it, and its size is limited to about 4 KB. Keep the secret key out of source control and rotate it with care. For server-side storage use Flask-Session with Redis. Set SESSION_COOKIE_SECURE, HTTPONLY and SAMESITE.
9 How do you handle errors in Flask?
mediumRegister handlers with @app.errorhandler for a status code or an exception class, returning JSON for API routes. abort(404) raises an HTTPException that the handler turns into a response. Unhandled exceptions return a 500, and with debug off Flask shows a generic page, so log the traceback. A blueprint can have its own handlers.
python@app.errorhandler(404) def not_found(e): return {"error": "not found"}, 404 @app.errorhandler(Exception) def unexpected(e): app.logger.exception("unhandled") return {"error": "internal error"}, 50010 How do you test a Flask app?
mediumCreate the app through the factory with testing config, use app.test_client() to make requests without a server, and use fixtures in pytest for the app, client and a temporary database. Assert on status codes and JSON. Use app.test_cli_runner for CLI commands. Isolate each test with a transaction rollback or a fresh in-memory database.
python@pytest.fixture def client(): app = create_app({"TESTING": True, "SQLALCHEMY_DATABASE_URI": "sqlite://"}) with app.app_context(): db.create_all() return app.test_client() def test_hello(client): r = client.get("/hello/asha") assert r.status_code == 200 and r.json["message"] == "hello asha"11 How do you deploy Flask in production?
mediumRun it under a production WSGI server such as Gunicorn or uWSGI, behind a reverse proxy like Nginx that handles TLS and static files. Use several workers, set the number from CPU count, turn debug off, load configuration from environment variables and use ProxyFix when behind a proxy so URLs and client IPs are right. Containerise it and add a health endpoint.
12 What is the g object and how does it differ from session?
hardg is a namespace on the application context that lives for one request, used to share data between functions during that request, such as the current user loaded by before_request or a database handle. session persists across requests in a cookie. Do not use g for data that must outlive the request, and note that in Flask 2.2 and later g belongs to the app context.
13 Can Flask handle async views?
hardYes, install flask[async] and define a route with async def. Flask runs it in a new event loop per request on a worker thread, so it supports await but does not become an async server. It helps when one request awaits several external calls with asyncio.gather. For high-concurrency async I/O across the whole stack, an ASGI framework such as FastAPI or Quart fits better.
14 How do you protect a Flask app against CSRF and XSS?
hardJinja auto-escapes variables in HTML templates, but not when you use the safe filter or Markup, so avoid those with user data. For CSRF use Flask-WTF CSRFProtect, which adds a token to forms and checks it on unsafe methods, and set SameSite on cookies. Add security headers with Flask-Talisman. Validate all input and use parameterised queries. See web security and OWASP questions.
15 How would you add authentication to a Flask API?
hardFor browser apps use Flask-Login with a server-side session, a user_loader callback and password hashes from werkzeug.security or Argon2. For APIs verify a bearer token in a decorator or before_request, check signature and expiry, and attach the user to g. Rate limit login with Flask-Limiter and return the same error for unknown user and wrong password.
pythondef login_required(fn): @wraps(fn) def wrapper(*a, **kw): token = request.headers.get("Authorization", "").removeprefix("Bearer ") try: g.user = decode_token(token) except InvalidToken: return {"error": "unauthorised"}, 401 return fn(*a, **kw) return wrapper16 Flask or FastAPI for a new service?
hardChoose FastAPI for a JSON API when you want automatic validation from type hints, generated OpenAPI documentation and native async. Choose Flask when you render server-side templates, want the largest extension ecosystem or have an existing codebase. Both are fine for small services. The deciding factors are team familiarity and whether you need async I/O.
Frequently asked questions
Is Flask still used in 2026?
Yes, for small services, internal tools, ML model serving and many existing products, though new API projects often choose FastAPI.
What do Flask interviews focus on?
Contexts, blueprints, the app factory, sessions, database handling, testing and deployment, plus general Python and REST questions.
Do I need to know Jinja2?
Yes, at a basic level: template inheritance, loops, filters and auto-escaping.
How is Flask different from Django?
Django is batteries-included with an ORM, admin and auth built in. Flask is minimal and you choose the components.
Related guides
More in Role-wise Interview Questions by Job and Tech Stack
- Flutter Interview Questions and Answers (Flutter 3, Dart 3)
- Frontend Developer Interview Questions and Answers
- Full Stack Developer Interview Questions and Answers
- Generative AI and LLM Interview Questions and Answers
- Google Cloud (GCP) Interview Questions and Answers
- GraphQL Interview Questions and Answers
- Hibernate and JPA Interview Questions and Answers
- HTML and CSS Interview Questions and Answers
- iOS and Swift Interview Questions and Answers
- Jenkins and CI/CD Interview Questions and Answers
- Kubernetes Interview Questions and Answers
- Machine Learning Interview Questions and Answers