Get ready for your next interview with our comprehensive question library
A basic Flask application requires creating a Flask instance and defining routes:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
The Flask(__name__) creates the application instance, @app.route() decorator defines URL endpoints, and app.run() starts the development server.
The __name__ parameter helps Flask determine the root path of the application, which is used for:
When run directly, __name__ equals '__main__', but when imported as a module, it contains the actual module name.
Specify HTTP methods using the methods parameter in the route decorator:
@app.route('/api/users', methods=['GET', 'POST'])
def handle_users():
if request.method == 'POST':
return create_user()
return get_users()
@app.route('/api/users/<int:user_id>', methods=['PUT', 'DELETE'])
def handle_user(user_id):
if request.method == 'PUT':
return update_user(user_id)
elif request.method == 'DELETE':
return delete_user(user_id)
URL variables capture dynamic parts of URLs and pass them as function arguments:
@app.route('/user/<username>')
def show_user(username):
return f'User: {username}'
@app.route('/post/<int:post_id>')
def show_post(post_id):
return f'Post ID: {post_id}'
@app.route('/path/<path:subpath>')
def show_subpath(subpath):
return f'Subpath: {subpath}'
Variable types include string (default), int, float, path, and uuid.
url_for() generates URLs for routes by endpoint name, providing URL reversal:
from flask import url_for
@app.route('/user/<username>')
def user_profile(username):
return f'Profile for {username}'
@app.route('/')
def index():
# Generate URL for user_profile endpoint
profile_url = url_for('user_profile', username='john')
return f'<a href="{profile_url}">John\'s Profile</a>'
Benefits include automatic URL updates when routes change and proper URL escaping.
Access query parameters using request.args:
from flask import request
@app.route('/search')
def search():
query = request.args.get('q', '')
page = request.args.get('page', 1, type=int)
category = request.args.getlist('category') # Multiple values
return f'Query: {query}, Page: {page}, Categories: {category}'
Use get() for single values with defaults, getlist() for multiple values.
Flask provides the request object to access various types of request data:
from flask import request
@app.route('/form', methods=['POST'])
def handle_form():
# Form data
username = request.form['username']
email = request.form.get('email', '')
# JSON data
if request.is_json:
data = request.get_json()
# Files
if 'file' in request.files:
file = request.files['file']
# Headers
auth_header = request.headers.get('Authorization')
# Cookies
session_id = request.cookies.get('session_id')
return 'Data processed'
These access different types of request data:
request.form: POST form data (application/x-www-form-urlencoded or multipart/form-data)request.args: URL query string parametersrequest.get_json(): JSON data from request body (application/json)# URL: /api?page=1
# Body: {"name": "John"}
# Form data: username=admin
@app.route('/api', methods=['POST'])
def api():
page = request.args.get('page') # "1"
name = request.get_json()['name'] # "John"
username = request.form.get('username') # "admin"
Upgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumAccess all premium content - interview questions, and other learning resources
We regularly update our features and content, to ensure you get the most relevant and updated premium content.
1000 monthly credits
Cancel anytime