Flask interview questions and answers for Python developers

Flask interview questions check whether you can grow a micro-framework into a maintainable service: an application factory, blueprints for each feature, extensions initialized once, and tests that build a fresh app per run. Interviewers also probe the application and request contexts, because errors like "working outside of application context" reveal whether you know how current_app, g and request actually work. Expect a comparison with Django and FastAPI and a question on how you would deploy behind a WSGI server.

By Published 8 min read

Where Flask questions come from

Flask turns up in Python backend interviews, data and ML teams that serve models behind a small API, and companies with older internal services written before FastAPI existed. Because Flask gives you so little by default, interviewers use it to see your own structure: where config lives, how the database session is scoped, how you test. Expect to write a route live, to review a single-file app that has outgrown itself, and to explain what happens between the WSGI server and your view function.

  1. Short concept questionsRouting, HTTP methods, request.args versus request.form versus request.get_json, sessions, error handlers.
  2. Build a small endpointOften a CRUD resource with validation and a 404 path. Clean status codes and JSON errors matter as much as the happy path.
  3. Refactor discussionA 900-line app.py with global objects. They want the factory, blueprints and a test fixture.
  4. Production and trade-offsGunicorn workers, timeouts, logging, background work, and when you would have picked another framework.

Flask basics questions

Fundamentals for freshers and first screens
QuestionWhat it testsWhat a strong answer shows
Why is Flask called a micro-framework?PositioningThe core handles routing, requests, responses, templates (Jinja) and sessions. Database access, forms, auth and migrations come from extensions you choose, not from Flask itself.
How do you read query string, form and JSON data?Request objectrequest.args for the query string, request.form for form posts, request.get_json() for a JSON body. args and form are empty when nothing was sent; get_json() errors on a non-JSON body unless you pass silent=True. Validate everything.
How are sessions stored by default?SessionsIn a cookie signed with SECRET_KEY. The client can read it but not change it without breaking the signature, so never put secrets in it. Server-side sessions need an extension.
What does debug mode do and why is it dangerous in production?SafetyIt reloads on code changes and shows an interactive debugger on errors, which can run code in the browser. It must never be reachable on a public server.
Is the built-in server fine for production?DeploymentNo. flask run uses the Werkzeug development server. Production runs behind a WSGI server such as Gunicorn (Linux and macOS) or Waitress (also runs on Windows), usually behind a reverse proxy.
How do you return JSON and a status code?ResponsesReturn a dict or call jsonify, with a tuple for the status: return {"error": "not found"}, 404. Register error handlers so every error has the same JSON shape.
What is url_for and why use it?RoutingIt builds URLs from endpoint names, so templates and redirects survive a changed path and blueprint prefixes are applied for you.
How do variable rules work in routes?Routing/<int:order_id> converts and validates the segment; a non-integer gives a 404 before your view runs. Other converters include string, path and uuid.
Where does Jinja escape output?TemplatesAutoescaping is on for HTML templates, so user data is escaped. |safe and Markup turn that off and should never wrap user input.
Fundamentals for freshers and first screens. Scroll sideways on a small screen.

App factory, blueprints and extensions

Most intermediate Flask questions circle one pattern. Instead of a module-level app = Flask(__name__), a create_app function builds and configures the app, registers blueprints and binds extensions. Tests can then create an app with different settings, and you can run several configurations in one process.

# app/extensions.py
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()  # created once, bound to an app later in init_app


# app/__init__.py
from flask import Flask

from .extensions import db


def create_app(test_config=None):
    app = Flask(__name__)
    app.config.from_mapping(SQLALCHEMY_DATABASE_URI="sqlite:///orders.db")
    if test_config:
        app.config.update(test_config)

    db.init_app(app)

    from .orders import bp as orders_bp  # imported here to avoid import cycles
    app.register_blueprint(orders_bp, url_prefix="/orders")
    return app
app/__init__.py and app/extensions.py: the extension object is created once and bound to each app in the factory.
  • What problem does the application factory solve? Import-time side effects and circular imports. Without it, every module that needs the app imports it, config is fixed at import, and tests share one global app.
  • What is a blueprint? A group of routes, templates, static files and hooks registered on an app with an optional URL prefix. It is a unit of organization, not a separate application, and it can be registered on more than one app.
  • Why do extensions have init_app? So the extension object can live in its own module with no app attached, and be bound to whichever app the factory creates. That is what lets models import db without importing the app.
  • How do you manage config per environment? A base config plus overrides from environment variables or an instance folder file; app.config.from_prefixed_env() reads variables with a FLASK_ prefix in recent versions. Secrets come from the environment, not the repository.
  • How would you split a large single-file app? One blueprint per feature area, models and services in their own modules, the factory in __init__.py, and error handlers registered centrally so every blueprint returns the same error format.
  • Which extensions have you used and what did each give you? A typical answer: Flask-SQLAlchemy for the session per app context, Flask-Migrate for Alembic migrations, Flask-Login or a JWT extension for auth, and a validation library such as Marshmallow or Pydantic.

Request context questions

Flask makes request, session, current_app and g look like globals, yet each request sees its own values. They are proxies that point at the context currently pushed for this request, stored per thread or per async task. Interviewers love asking why the code below works, and why the same current_app.config line fails in a standalone script.

import uuid

from flask import Blueprint, abort, g, jsonify, request

from .extensions import db
from .models import Order

bp = Blueprint("orders", __name__)


@bp.before_app_request
def assign_request_id():
    g.request_id = request.headers.get("X-Request-ID", uuid.uuid4().hex)


@bp.after_app_request
def echo_request_id(response):
    response.headers["X-Request-ID"] = g.request_id
    return response


@bp.get("/<int:order_id>")
def get_order(order_id):
    order = db.session.get(Order, order_id)
    if order is None:
        abort(404)
    return jsonify(id=order.id, total_cents=order.total_cents)
app/orders.py: per-request data on g, hooks that run for every request, and a view that returns 404 cleanly.
Context and lifecycle questions
QuestionWhat it testsWhat a strong answer shows
Application context versus request context?ContextsThe app context carries current_app and g. The request context carries request and session. Flask pushes both for each request; CLI commands and scripts may need only with app.app_context():.
What causes "Working outside of application context"?DebuggingCode touched current_app, g or an extension that needs the app (such as a database session) with no context pushed, for example in a script, a thread or a background task. Push one explicitly.
What is g for, and how long does it live?Request-scoped dataStorage for one app context, which means one request in a web call: the current user, a database connection, a request ID. It is not shared across requests.
before_request, after_request and teardown_request?Hooksbefore_request can short-circuit by returning a response. after_request can modify the response but is not a cleanup hook, because it is skipped when an exception propagates. teardown runs either way, which is where you release resources.
Why can't you pass request to a background thread?ProxiesThe proxy points at a context that ends with the request. Copy the values you need, or use copy_current_request_context for a short-lived helper.
Context and lifecycle questions. Scroll sideways on a small screen.

Testing and deployment questions

import pytest

from app import create_app
from app.extensions import db
from app.models import Order


@pytest.fixture
def client():
    app = create_app({"TESTING": True, "SQLALCHEMY_DATABASE_URI": "sqlite://"})
    with app.app_context():
        db.create_all()
        db.session.add(Order(id=1, total_cents=4200))
        db.session.commit()
    return app.test_client()


def test_returns_order(client):
    res = client.get("/orders/1")
    assert res.status_code == 200
    assert res.get_json() == {"id": 1, "total_cents": 4200}


def test_missing_order_is_404(client):
    assert client.get("/orders/999").status_code == 404
test_orders.py: a fresh app with an in-memory database for every test, and the test client instead of a running server.
  • What does TESTING=True change? Exceptions propagate to the test instead of becoming 500 pages, so a failing view fails the test with a real traceback. Some extensions also change behavior under it.
  • What is WSGI, in one minute? A Python standard interface: the server calls your app with the request environment and a start_response callable, and gets back an iterable body. Flask apps are WSGI apps, which is why Gunicorn or Waitress can serve them.
  • How many Gunicorn workers, and what kind? Start near two times the CPU cores plus one for sync workers on CPU-light apps, then measure. Threaded or gevent workers help I/O-heavy apps; long requests need a timeout that matches reality.
  • Can Flask views be async? Yes, with the async extra installed, but Flask still runs as WSGI: each async view runs its own event loop inside the worker, so it helps concurrency inside one request, not request throughput. For async throughput across many requests, an ASGI framework is a better fit.
  • Where does slow work go? Out of the request: a task queue such as Celery or RQ, with the task given IDs and an app context of its own.
  • How do you log in production? Configure logging before the app is created, include the request ID from g in each line, and write to stdout so the platform collects it.

Security and API design questions

  • Does Flask protect forms against CSRF? Not by itself. Flask-WTF adds CSRF tokens for form posts; a JSON API authenticated by a bearer token instead of a cookie does not need them.
  • How do you allow a browser app on another origin to call your API? Send the right CORS headers, usually through Flask-CORS, limited to the origins and methods you expect rather than a wildcard with credentials.
  • How do you validate a JSON body? With a schema library such as Marshmallow or Pydantic in front of the view, returning a 400 with field-level messages. Never pass request data straight into a query or a model.
  • How do you version a Flask API? Register the same or a new blueprint under a /v1 or /v2 prefix, keep old versions running until clients move, and share services underneath.
  • How do you store passwords? Hash them with a slow algorithm, for example Werkzeug's generate_password_hash and check_password_hash, and never log them or keep them in the session cookie.

Flask versus Django versus FastAPI

The comparison question, answered by trade-offs
NeedFlaskDjangoFastAPI
Built-insRouting, templates, sessions. You add the rest.ORM, admin, auth, forms, migrations included.Routing, validation from type hints, generated OpenAPI docs.
InterfaceWSGIWSGI or ASGIASGI, async first
ValidationAn extension or a library you chooseForms, model validation, DRF serializersPydantic models on every request and response
Good fitSmall services, model serving, apps where you want to choose every partData-heavy products with admin needs and a relational databaseJSON APIs with many concurrent I/O calls and typed contracts
Cost of the choiceYou own the structure and the glueConventions to learn and acceptAsync pitfalls: one blocking call stalls the event loop
The comparison question, answered by trade-offs. Scroll sideways on a small screen.

Fictional example

Answering "Why did your team use Flask and not Django?"
Interviewer
Your résumé says you built the pricing service in Flask. Why not Django?
Candidate
The service had four endpoints and no admin users. It loaded a model at startup and answered quotes, so Django's ORM, admin and auth would have been weight we never used. We kept it disciplined with an app factory, one blueprint for quotes and one for health checks, and pytest fixtures that built a fresh app per test. If I were starting it today I would look hard at FastAPI, because most of our bugs were bad input and we wrote validation by hand. The thing I would not change is keeping it small; when it started needing user accounts, we moved that part into the main Django product instead of growing the Flask service.

Flask practice plan

  • Session 1: write a single-file app with three routes, then refactor it into a factory with two blueprints without changing behavior.
  • Session 2: add Flask-SQLAlchemy and a migration tool, then write pytest fixtures that create a fresh in-memory database per test.
  • Session 3: trigger "working outside of application context" in a script and fix it; explain g, current_app and teardown in your own words.
  • Session 4: run the app under Gunicorn or Waitress, add JSON error handlers and request IDs, and time a slow endpoint.
  • Session 5: prepare a two-minute answer comparing Flask, Django and FastAPI for a project you know.

For the heavier framework, read Django interview questions. If you serve models or data pipelines through Flask, data engineer interview questions and backend developer interview questions cover the rounds around it.

Practice the refactor out loud, since that is where candidates ramble. Natively, an AI interview assistant for Mac and Windows, keeps a transcript of a mock Flask round on your computer, so you can see whether you mentioned the factory and the test fixture or only talked about folders. In practice sessions it can read a traceback or a task from a screenshot and offer code, and Pro or the free trial lets it draw on your résumé and the job description you add. The notes are kept for review.

Questions people ask

What Flask questions are asked in interviews?

Routing and the request object, sessions, the application factory, blueprints, extensions with init_app, application and request contexts, g and current_app, testing with the test client, WSGI deployment and comparisons with Django and FastAPI.

What is the Flask application factory?

A create_app function that builds and configures the app, binds extensions and registers blueprints. It avoids circular imports and lets tests create apps with different settings.

What causes 'working outside of application context' in Flask?

Code used current_app, g or an app-bound extension without an active app context, often in a script, thread or background task. Push one with app.app_context().

Should I learn Flask, Django or FastAPI for interviews?

Learn the one the job lists. Flask shows how you structure a small service yourself, Django tests the ORM and conventions, and FastAPI tests async and typed validation.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP