Getting Started with Flask: A Lightweight Web Framework for Python
Source: Dev.to
What Is Flask?
Flask is a lightweight web framework written in Python. It is often described as a microframework because it provides the essentials needed to build web applications while leaving decisions about structure and tools to the developer.
Core Features
- Routing – URLs and endpoints
- HTTP handling – Requests and responses
- Templating – Jinja2 integration
- Development server & debugging
Everything else is added only when you need it.
Why Choose Flask?
- Easy to learn – Minimal setup and clear syntax
- Flexible – No forced project structure
- Lightweight – Install only what you need
- Pythonic – Clean and readable code
- Great for APIs – Ideal for RESTful services
Flask is widely adopted because of its simplicity and flexibility, making it a common first step into web development for data scientists and backend developers.
Installation
Before installing Flask, it’s best practice to use a Python virtual environment.
pip install flask
Your First Flask App
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello, Flask!"
if __name__ == "__main__":
app.run(debug=True)
Run the app:
python app.py
Open your browser and navigate to http://127.0.0.1:5000/.
Routing
Routing maps URLs to Python functions.
@app.route("/about")
def about():
return "About Page"
Each route defines how the application responds to a specific URL.
Building REST APIs
Flask is commonly used to build REST APIs.
from flask import jsonify
@app.route("/api/status")
def status():
return jsonify({"status": "running"})
Typical Use Cases
- Machine‑learning inference APIs
- Backend services
- Microservices
Flask vs. Django (Quick Comparison)
| Aspect | Flask | Django |
|---|---|---|
| Scope | Lightweight, microframework | Full‑featured framework |
| Flexibility | Highly flexible, no opinionated structure | Opinionated, provides many built‑in components |
| Setup Speed | Quick setup | More configuration required |
| Best For | APIs, microservices, prototypes, ML model serving | Large applications with complex requirements |
Flask gives you control, while Django gives you structure.
When to Use Flask
- You need a simple backend.
- You’re building APIs or microservices.
- You want full control over architecture.
- You’re serving ML models or prototypes.
Scaling Flask for Larger Applications
- Use virtual environments to isolate dependencies.
- Organize code into modules (e.g.,
app/__init__.py,app/routes.py). - Handle configuration via environment variables.
- Disable debug mode in production.
- Deploy with Gunicorn, Docker, or other WSGI servers.
Conclusion
Flask lowers the barrier to web development in Python. Its simplicity makes it perfect for beginners, while its flexibility makes it powerful enough for production systems. Whether you’re a data scientist deploying models or a developer building APIs, Flask is a tool worth mastering.