Top 40 Flask Interview Questions 2026
Flask is Python's lightweight, unopinionated web framework favored for microservices, REST APIs, and ML model serving. Candidates report that routing,...

What changed in 2026 drives
Mass-recruiter offer letters are flatter for 2026 batch - the 4-5 LPA ASE band has barely budged in three years while inflation eats real wages. Premium tracks (Digital, Pro, Elite, Specialist) are still where the differential lives, and they are entirely test-driven. If you are aiming higher than the default offer, the coding round is not optional pageantry - it is the entire interview.
What I'd actually study for this
- 01Two solid coding-round answers (1 medium-hard DSA each, with edge-case discussion) > five half-baked ones
- 02One real project you can defend end-to-end - file paths, design decisions, and what you would change
- 03One DBMS schema you actually built (not a textbook ER diagram), with at least 3 join-heavy queries written from memory
- 04Three behavioural STAR stories: failure recovered, conflict handled, ownership taken
Where most candidates trip up
The single biggest mistake is treating company-specific guides as primary prep and DSA as secondary. It is the opposite. Mass recruiters use the test as a filter, but premium tracks at every IT services company use coding to allocate offer band. Spend 70% of prep time on DSA + system fundamentals, 20% on company-specific patterns, 10% on HR rehearsal. Reverse that ratio and you collect the default offer.
Editorial commentary by Aditya Sharma · written for PapersAdda · not generated, not aggregated.
Last Updated: June 2026 | Level: Freshers to 3 Years Experience | Read Time: ~18 min
Flask is Python's lightweight, unopinionated web framework favored for microservices, REST APIs, and ML model serving. Candidates report that routing, blueprints, application factory pattern, and Flask-SQLAlchemy are the most frequently tested topics in Flask developer interviews.
Pair with Python Interview Questions 2026 and FastAPI Interview Questions 2026. Confirm current interview requirements on the official careers portal of your target company.
Table of Contents
- Flask Basics (Q1-Q12)
- Request Handling and Blueprints (Q13-Q22)
- Flask-SQLAlchemy and Database (Q23-Q30)
- Authentication and Security (Q31-Q36)
- Deployment and Architecture (Q37-Q40)
- Mock Interview: 5 Questions
- FAQ
Flask Basics
Q1. What is Flask and what is it used for? Easy
Common uses:
- REST APIs and microservices
- ML model serving endpoints
- Lightweight web applications
- Prototyping
Q2. What is a minimal Flask application? Easy
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True) # debug=True: auto-reload + error details
Run: python app.py or flask run
Q3. How does routing work in Flask? Easy
# Basic routes
@app.route('/about')
def about():
return 'About page'
# URL variables
@app.route('/users/<int:user_id>')
def get_user(user_id):
return f'User {user_id}'
@app.route('/files/<path:filename>')
def get_file(filename):
return send_from_directory('files', filename)
# Methods
@app.route('/users', methods=['GET', 'POST'])
def users():
if request.method == 'POST':
return create_user()
return list_users()
# URL building
url_for('get_user', user_id=42) # '/users/42'
Q4. What are URL converters? Easy
| Converter | Matches | Example |
|---|---|---|
string | Any text without slash (default) | /users/<name> |
int | Positive integers | /users/<int:id> |
float | Positive floats | /prices/<float:amount> |
path | Any text including slashes | /files/<path:filename> |
uuid | UUID strings | /items/<uuid:item_id> |
Q5. What is request in Flask? Medium
from flask import request
@app.route('/search')
def search():
q = request.args.get('q', '') # ?q=python
page = request.args.get('page', 1, type=int)
return f'Searching for {q} page {page}'
@app.route('/users', methods=['POST'])
def create_user():
data = request.json # JSON body
form_data = request.form # form data
files = request.files # uploaded files
headers = request.headers # HTTP headers
token = request.headers.get('Authorization')
return jsonify({'created': data['name']})
Q6. What is jsonify? Easy
from flask import jsonify
@app.route('/api/user/<int:id>')
def get_user(id):
user = User.query.get_or_404(id)
return jsonify({
'id': user.id,
'name': user.name,
'email': user.email
})
# Or return dict directly (Flask 2.2+)
@app.route('/api/status')
def status():
return {'status': 'ok', 'version': '1.0'} # auto-jsonified
Q7. What are HTTP status codes in Flask responses? Easy
# Default: 200 OK
return jsonify({'created': True}), 201 # CREATED
return jsonify({'error': 'not found'}), 404
return jsonify({'error': 'bad request'}), 400
# With headers
from flask import make_response
response = make_response(jsonify({'data': result}), 200)
response.headers['X-Custom-Header'] = 'value'
return response
# Redirect
from flask import redirect, url_for
return redirect(url_for('login'))
return redirect('https://example.com', 301)
Q8. What is the application factory pattern? Medium
# Instead of creating app at module level (hard to test/configure)
# Use a factory function
def create_app(config_name='default'):
app = Flask(__name__)
app.config.from_object(config[config_name])
from .extensions import db, migrate, login_manager
db.init_app(app)
migrate.init_app(app, db)
login_manager.init_app(app)
from .blueprints.api import api_bp
from .blueprints.auth import auth_bp
app.register_blueprint(api_bp, url_prefix='/api')
app.register_blueprint(auth_bp, url_prefix='/auth')
return app
# run.py
app = create_app(os.getenv('FLASK_ENV', 'default'))
Q9. What is application context vs request context? Medium
# Application context: pushed for every request and CLI command
# - g: per-request global storage
# - current_app: proxy to the current app
from flask import current_app, g
def get_db():
if 'db' not in g:
g.db = connect_database() # cached per request
return g.db
@app.teardown_appcontext
def close_db(error):
db = g.pop('db', None)
if db is not None:
db.close()
# Request context: active during request handling
# - request, session
from flask import request, session
Q10. What is Flask.config? Medium
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard-to-guess'
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')
SQLALCHEMY_TRACK_MODIFICATIONS = False
MAX_CONTENT_LENGTH = 16 * 1024 * 1024 # 16MB max upload
class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///dev.db'
class ProductionConfig(Config):
DEBUG = False
config = {
'development': DevelopmentConfig,
'production': ProductionConfig,
'default': DevelopmentConfig
}
app.config.from_object(Config) # from class
app.config.from_pyfile('config.py') # from file
app.config.from_envvar('APP_CONFIG') # from env var pointing to file
Q11. What are Flask error handlers? Medium
@app.errorhandler(404)
def not_found(error):
return jsonify({'error': 'Resource not found', 'code': 404}), 404
@app.errorhandler(500)
def internal_error(error):
return jsonify({'error': 'Internal server error'}), 500
@app.errorhandler(ValidationError)
def handle_validation(error):
return jsonify({'error': str(error)}), 400
# Abort
from flask import abort
abort(404) # raises 404
abort(403) # raises 403
Q12. Predict the output: Easy
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/users/<int:id>/profile')
def user_profile(id):
pass
with app.test_request_context():
print(url_for('user_profile', id=42))
print(url_for('user_profile', id=42, _external=True))
Output:
/users/42/profile
http://localhost/users/42/profile
Request Handling and Blueprints
Q13. What are blueprints? Medium
# blueprints/users.py
from flask import Blueprint, jsonify
users_bp = Blueprint('users', __name__, url_prefix='/api/users')
@users_bp.route('/')
def list_users():
return jsonify(users)
@users_bp.route('/<int:id>')
def get_user(id):
return jsonify(user)
# app.py
from blueprints.users import users_bp
from blueprints.auth import auth_bp
app.register_blueprint(users_bp)
app.register_blueprint(auth_bp, url_prefix='/auth')
Blueprints organize routes into logical groups, each with its own URL prefix, error handlers, and templates.
Q14. What are before_request and after_request hooks? Medium
@app.before_request
def authenticate():
if request.endpoint in ('login', 'health'):
return None # skip auth for these endpoints
token = request.headers.get('Authorization')
if not validate_token(token):
return jsonify({'error': 'Unauthorized'}), 401
@app.after_request
def add_cors_headers(response):
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['X-Request-ID'] = g.get('request_id', '')
return response
@app.teardown_request
def log_request(error=None):
if error:
app.logger.error(f"Request failed: {error}")
Q15. How do you handle file uploads? Medium
from werkzeug.utils import secure_filename
import os
UPLOAD_FOLDER = '/uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'pdf'}
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/upload', methods=['POST'])
def upload():
if 'file' not in request.files:
return jsonify({'error': 'No file provided'}), 400
file = request.files['file']
if file.filename == '' or not allowed_file(file.filename):
return jsonify({'error': 'Invalid file'}), 400
filename = secure_filename(file.filename)
file.save(os.path.join(UPLOAD_FOLDER, filename))
return jsonify({'filename': filename}), 201
Q16. What is Flask session? Medium
from flask import session
app.secret_key = 'your-secret-key' # required for sessions
@app.route('/login', methods=['POST'])
def login():
user = authenticate(request.json['email'], request.json['password'])
if user:
session['user_id'] = user.id
session.permanent = True # persist across browser close
return jsonify({'status': 'logged in'})
return jsonify({'error': 'Invalid credentials'}), 401
@app.route('/logout')
def logout():
session.pop('user_id', None)
return jsonify({'status': 'logged out'})
Flask sessions are signed cookies (not encrypted by default). Never store sensitive data in sessions.
Q17. How do you handle CORS in Flask? Medium
from flask_cors import CORS
app = Flask(__name__)
CORS(app) # allow all origins (development only)
# Production: restrict origins
CORS(app, resources={
r'/api/*': {
'origins': ['https://yourfrontend.com'],
'methods': ['GET', 'POST', 'PUT', 'DELETE'],
'allow_headers': ['Authorization', 'Content-Type']
}
})
Q18. What is flask_restful? Medium
from flask_restful import Api, Resource, reqparse
api = Api(app)
class UserResource(Resource):
def get(self, user_id):
user = User.query.get_or_404(user_id)
return {'id': user.id, 'name': user.name}
def delete(self, user_id):
user = User.query.get_or_404(user_id)
db.session.delete(user)
db.session.commit()
return '', 204
class UserListResource(Resource):
def get(self):
return [{'id': u.id, 'name': u.name} for u in User.query.all()]
api.add_resource(UserListResource, '/api/users')
api.add_resource(UserResource, '/api/users/<int:user_id>')
Q19. How do you validate request data? Medium
from marshmallow import Schema, fields, ValidationError
class CreateUserSchema(Schema):
name = fields.Str(required=True, validate=lambda n: len(n) >= 2)
email = fields.Email(required=True)
age = fields.Int(load_default=None, validate=lambda a: 18 <= a <= 120)
@app.route('/api/users', methods=['POST'])
def create_user():
schema = CreateUserSchema()
try:
data = schema.load(request.json)
except ValidationError as err:
return jsonify({'errors': err.messages}), 400
user = User(**data)
db.session.add(user)
db.session.commit()
return jsonify({'id': user.id}), 201
Q20. What is Flask signals? Advanced
from flask import got_request_exception
from blinker import Namespace
# Built-in signals
from flask import request_started, request_finished
@request_started.connect_via(app)
def on_request_started(sender, **kwargs):
print(f"Request started: {request.url}")
# Custom signal
my_signals = Namespace()
user_created = my_signals.signal('user-created')
def create_user(user_data):
user = User(**user_data)
db.session.add(user)
db.session.commit()
user_created.send(app, user=user) # fire signal
return user
Q21. What is response streaming? Advanced
def generate_large_response():
for chunk in read_large_file():
yield chunk
@app.route('/download/large')
def download():
return Response(
generate_large_response(),
mimetype='application/octet-stream',
headers={'Content-Disposition': 'attachment;filename=large.bin'}
)
# Server-Sent Events
def sse_events():
while True:
data = get_latest_data()
yield f"data: {json.dumps(data)}\n\n"
time.sleep(1)
@app.route('/events')
def events():
return Response(sse_events(), mimetype='text/event-stream')
Q22. Predict the output: Medium
app = Flask(__name__)
app.config['TESTING'] = True
@app.route('/greet/<name>')
def greet(name):
return f'Hello, {name}!', 200
with app.test_client() as client:
response = client.get('/greet/Aditya')
print(response.status_code)
print(response.data.decode())
Output:
200
Hello, Aditya!
Flask-SQLAlchemy and Database
Q23. How do you set up Flask-SQLAlchemy? Medium
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
active = db.Column(db.Boolean, default=True)
created_at = db.Column(db.DateTime, server_default=db.func.now())
orders = db.relationship('Order', backref='user', lazy='dynamic')
def __repr__(self):
return f'<User {self.name}>'
# In create_app
db.init_app(app)
with app.app_context():
db.create_all() # create tables
Q24. How do you query with Flask-SQLAlchemy (SQLAlchemy 2.x)? Medium
from sqlalchemy import select
# All users
users = db.session.execute(db.select(User)).scalars().all()
# Filter
active_users = db.session.execute(
db.select(User).where(User.active == True)
).scalars().all()
# Get by primary key
user = db.session.get(User, user_id)
# or
user = db.get_or_404(User, user_id)
# Order, limit
recent = db.session.execute(
db.select(User)
.order_by(User.created_at.desc())
.limit(10)
).scalars().all()
# Count
count = db.session.execute(db.select(db.func.count()).select_from(User)).scalar()
Q25. How do you run database migrations? Medium
# Flask-Migrate wraps Alembic
from flask_migrate import Migrate
migrate = Migrate(app, db)
# CLI commands:
# flask db init # create migrations folder
# flask db migrate -m "add users table" # generate migration
# flask db upgrade # apply migrations
# flask db downgrade # revert last migration
# flask db history # show migration history
Q26. What are database transactions in Flask-SQLAlchemy? Medium
@app.route('/transfer', methods=['POST'])
def transfer():
try:
source = db.session.get(Account, request.json['from_id'])
target = db.session.get(Account, request.json['to_id'])
amount = request.json['amount']
if source.balance < amount:
return jsonify({'error': 'Insufficient funds'}), 400
source.balance -= amount
target.balance += amount
db.session.commit() # atomic commit
return jsonify({'status': 'transferred'})
except Exception as e:
db.session.rollback() # rollback on error
return jsonify({'error': str(e)}), 500
Q27. What is lazy loading in Flask-SQLAlchemy? Medium
class User(db.Model):
# lazy='select' (default): loads when accessed (lazy)
orders = db.relationship('Order', backref='user', lazy='select')
# lazy='joined': JOIN in same query (eager)
profile = db.relationship('Profile', backref='user', lazy='joined')
# lazy='dynamic': returns query object (for large collections)
posts = db.relationship('Post', backref='author', lazy='dynamic')
# usage: user.posts.filter(Post.active == True).all()
# lazy='subquery': separate subquery (better than N+1)
tags = db.relationship('Tag', secondary=user_tags, lazy='subquery')
Q28. How do you paginate results? Medium
@app.route('/api/users')
def list_users():
page = request.args.get('page', 1, type=int)
per_page = request.args.get('per_page', 20, type=int)
pagination = db.paginate(
db.select(User).order_by(User.name),
page=page,
per_page=per_page,
error_out=False
)
return jsonify({
'users': [{'id': u.id, 'name': u.name} for u in pagination.items],
'total': pagination.total,
'pages': pagination.pages,
'current_page': pagination.page,
'has_next': pagination.has_next,
'has_prev': pagination.has_prev,
})
Q29. What is the db.event listener? Advanced
from sqlalchemy import event
@event.listens_for(User, 'before_insert')
def set_created_at(mapper, connection, target):
target.created_at = datetime.utcnow()
@event.listens_for(User, 'after_delete')
def archive_user(mapper, connection, target):
connection.execute(
archived_users.insert().values(
id=target.id, name=target.name, deleted_at=datetime.utcnow()
)
)
Q30. Predict the output: Medium
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
with app.app_context():
user = User(name='Aditya')
print(user.id) # before add
db.session.add(user)
db.session.flush() # flush without commit
print(user.id) # after flush
db.session.rollback()
print(user.id) # after rollback
Output:
None
1
1
Explanation: Before add, id is None (not yet assigned). After flush, Hibernate/SQLAlchemy assigns the ID from the sequence even before commit. After rollback, the transaction is rolled back in the DB, but the Python object still has the assigned ID in memory.
Authentication and Security
Q31. How do you implement JWT auth in Flask? Medium
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity
app.config['JWT_SECRET_KEY'] = 'super-secret'
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(hours=1)
jwt = JWTManager(app)
@app.route('/login', methods=['POST'])
def login():
email = request.json.get('email')
password = request.json.get('password')
user = User.query.filter_by(email=email).first()
if not user or not user.check_password(password):
return jsonify({'error': 'Invalid credentials'}), 401
token = create_access_token(identity=user.id)
return jsonify({'access_token': token})
@app.route('/profile')
@jwt_required()
def profile():
user_id = get_jwt_identity()
user = db.session.get(User, user_id)
return jsonify({'id': user.id, 'name': user.name})
Q32. How do you hash passwords in Flask? Easy
from werkzeug.security import generate_password_hash, check_password_hash
class User(db.Model):
password_hash = db.Column(db.String(256))
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
# Usage
user = User(name='Aditya')
user.set_password('mypassword123')
db.session.add(user)
db.session.commit()
# Verify
user.check_password('mypassword123') # True
user.check_password('wrong') # False
Q33. What is Flask-Login? Medium
from flask_login import LoginManager, login_user, login_required, current_user, logout_user
login_manager = LoginManager(app)
login_manager.login_view = 'auth.login'
@login_manager.user_loader
def load_user(user_id):
return db.session.get(User, int(user_id))
@app.route('/login', methods=['POST'])
def login():
user = User.query.filter_by(email=request.form['email']).first()
if user and user.check_password(request.form['password']):
login_user(user, remember=True)
return redirect(url_for('dashboard'))
flash('Invalid credentials')
return redirect(url_for('login'))
@app.route('/dashboard')
@login_required
def dashboard():
return f'Hello, {current_user.name}'
Q34. How do you protect against SQL injection in Flask? Medium
# WRONG: string formatting (SQL injection vulnerable)
users = db.session.execute(
text(f"SELECT * FROM users WHERE name = '{name}'")
)
# CORRECT: parameterized queries
from sqlalchemy import text
users = db.session.execute(
text("SELECT * FROM users WHERE name = :name"),
{'name': name}
)
# ORM (safest): no raw SQL at all
user = User.query.filter_by(name=name).first()
Q35. What is rate limiting in Flask? Medium
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
limiter = Limiter(
key_func=get_remote_address,
app=app,
default_limits=["100 per day", "20 per hour"]
)
@app.route('/api/login', methods=['POST'])
@limiter.limit("5 per minute") # per-route override
def login():
return authenticate()
Q36. What are secure headers in Flask? Medium
from flask_talisman import Talisman
Talisman(app,
content_security_policy={
'default-src': "'self'",
'script-src': "'self' https://cdn.example.com",
},
force_https=True,
strict_transport_security=True,
referrer_policy='strict-origin-when-cross-origin'
)
Deployment and Architecture
Q37. How do you deploy Flask in production? Medium
# Development server (NOT for production)
app.run(debug=True)
# Production: use a WSGI server
# Gunicorn
# gunicorn -w 4 -b 0.0.0.0:8000 "app:create_app()"
# uWSGI
# uwsgi --http 0.0.0.0:8000 --module app:app --processes 4 --threads 2
# With Nginx proxy
# Nginx -> Gunicorn/uWSGI -> Flask
Q38. What is Flask testing? Medium
import pytest
from app import create_app, db
@pytest.fixture
def client():
app = create_app('testing')
with app.test_client() as client:
with app.app_context():
db.create_all()
yield client
db.drop_all()
def test_create_user(client):
response = client.post('/api/users', json={
'name': 'Test User',
'email': '[email protected]'
})
assert response.status_code == 201
data = response.get_json()
assert data['name'] == 'Test User'
Q39. What is async Flask (Flask 2.0+)? Advanced
from flask import Flask
import asyncio
app = Flask(__name__)
@app.route('/async-endpoint')
async def async_view():
data = await fetch_data_async()
return jsonify(data)
async def fetch_data_async():
await asyncio.sleep(0.1) # non-blocking wait
return {'result': 'data'}
# async views require an ASGI server like hypercorn
# hypercorn app:app --bind 0.0.0.0:8000
Q40. What is Flask CLI? Medium
import click
@app.cli.command('create-admin')
@click.argument('email')
@click.argument('password')
def create_admin(email, password):
"""Create an admin user."""
user = User(email=email, role='admin')
user.set_password(password)
db.session.add(user)
db.session.commit()
click.echo(f'Admin {email} created.')
# flask create-admin [email protected] securepassword123
# Built-in commands
# flask run -- start development server
# flask shell -- Python REPL with app context
# flask routes -- show all registered routes
Mock Interview: 5 Questions
- What is the application factory pattern and why do you use it instead of a module-level
app = Flask(__name__)? - You have an endpoint that crashes in production with a database error but succeeds in development. How do you debug it?
- Implement a decorator that checks if the current user is an admin before allowing access to a view.
- What is the difference between
session,g, and request globals in Flask? - Your Flask API is slow because a database query runs for every request. How would you add caching?
FAQ
Q: Flask vs FastAPI - which should I learn for 2026? A: FastAPI for new API projects (better performance, built-in async, automatic OpenAPI docs). Flask for existing Flask projects, ML model serving (familiar ecosystem), and when simplicity is the priority.
Q: Does Flask support WebSockets? A: Not natively. Use Flask-SocketIO (which wraps Socket.IO) or switch to FastAPI/Starlette for native WebSocket support.
Q: What is the difference between Flask and Django? A: Flask is micro (bring your own ORM, auth, forms). Django is batteries-included (built-in ORM, admin, auth, forms). For APIs, both work; for content-heavy web apps, Django's admin and ORM save significant time.
Related reading: FastAPI Interview Questions 2026 | Python Interview Questions 2026 | Django Interview Questions 2026 | SQL Interview Questions 2026
Methodology applied to this articlelast verified 8 Jun 2026
- No fabricated salary numbers or success rates. If we quote a range, it's sourced.
- No noun-substituted templates. This article was not generated by swapping company names in a stock prompt.
- No paid placements, sponsored coaching links, or affiliate-shilled course pushes.
topic cluster
More resources in Interview Questions
Use the category hub to browse similar questions, exam patterns, salary guides, and preparation resources related to this topic.
paid contributor programme
Sat this this year? Share your story, earn ₹500.
First-person experience reports help future candidates prep smarter. We pay verified contributors ₹500 via UPI per accepted story with byline.
Submit your story →ready to practice?
Take a free timed mock test
Put what you learned into practice. Our mock tests match the 2026 pattern with timer, navigator, reveal, and score breakdown. No signup.