Flask is a lightweight Python web framework used for building web applications and REST APIs.
It is simple, flexible, and gives developers full control over application structure.
What is Flask?
Flask is a micro web framework written in Python that allows you to build web apps quickly with minimal setup.
It does not come with built-in tools like Django, making it lightweight and highly customizable.
Why Use Flask?
Flask is easy to learn and ideal for small to medium-sized applications.
It is widely used for APIs, prototypes, and microservices due to its simplicity.
Installing Flask
pip install flaskCreating a Simple Flask App
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello Flask!'This simple code creates a basic web server using Flask.
Running a Flask App
flask runFlask starts a local development server to run your application.
What is a Route?
A route defines the URL that triggers a specific function in Flask.
@app.route('/about')
def about():
return 'About Page'HTTP Methods in Flask
Flask supports different HTTP methods like GET and POST for handling requests.
@app.route('/submit', methods=['POST'])
def submit():
return 'Data Submitted'What is Request and Response?
The request object contains data sent by the client.
The response is what the server sends back to the client.
from flask import request
@app.route('/data')
def data():
name = request.args.get('name')
return f'Hello {name}'Flask as a Microframework
Flask provides only the essentials, allowing developers to add libraries as needed.
This makes it flexible and lightweight compared to full-stack frameworks.
Templates in Flask
Flask uses Jinja2 template engine for rendering HTML pages dynamically.
<h1>Hello {{ name }}</h1>Rendering Templates
from flask import render_template
@app.route('/user')
def user():
return render_template('user.html', name='John')Static Files in Flask
Flask allows serving static files like CSS, JavaScript, and images.
These files are usually stored in the 'static' folder.
Advantages of Flask
Flask is simple, flexible, and gives full control over application design.
It is ideal for beginners and developers building small or medium backend systems.
Common Beginner Mistakes
Beginners often forget to handle HTTP methods properly in routes.
Another mistake is mixing business logic directly inside route functions.
Best Practices
Keep routes clean and move logic into separate service layers.
Use virtual environments to manage dependencies properly.
Real-World Importance
Flask is widely used for building REST APIs, microservices, and backend systems.
Many startups prefer Flask for its simplicity and fast development speed.
Summary
Flask is a lightweight Python framework used to build web applications and APIs.
Understanding Flask basics is the first step toward backend development with Python.