Web Development: Flask / FastAPI Basics
ওয়েব ডেভেলপমেন্ট — Flask / FastAPI
1. Web in Python — Two Great Choices
For building web backends in Python, two modern frameworks dominate: Flask (simple, mature, synchronous) and FastAPI (modern, async, type-driven). Both are micro-frameworks — small, focused, and easy to reason about. Django exists for full-stack, batteries-included projects, but Flask/FastAPI are the right starting point.
pip install flask fastapi uvicorn. Run the sandbox snippets locally — the
browser executor cannot start a live server.
2. HTTP in One Minute
- Client (your browser or app) sends a request — method (GET, POST, PUT, DELETE), path (
/users/42), headers, body. - Server (your Python code) sends back a response — status code (200, 404, 500), headers, body (HTML or JSON).
- A REST API is a server that speaks HTTP + JSON, exposing resources at URLs like
/users,/users/42.
3. Hello World in Flask
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route("/")
def home():
return "<h1>Welcome to ABCL TECH Flask demo</h1>"
@app.route("/hello/<name>")
def hello(name):
return f"Hello, {name}!"
@app.route("/api/users", methods=["GET", "POST"])
def users():
if request.method == "POST":
data = request.get_json()
return jsonify({"created": data}), 201
return jsonify([{"id": 1, "name": "Asif"}])
if __name__ == "__main__":
app.run(debug=True, port=5000)
# Run: python flask_app.py → http://localhost:5000/
4. Same Idea in FastAPI
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
name: str
age: int
@app.get("/")
def home():
return {"message": "Welcome to ABCL TECH FastAPI demo"}
@app.get("/hello/{name}")
def hello(name: str):
return {"greeting": f"Hello, {name}!"}
@app.post("/api/users")
def create_user(u: User):
return {"created": u.model_dump()}
# Run: uvicorn fast_app:app --reload
# Auto-docs at http://localhost:8000/docs and /redoc
Notice how FastAPI uses type hints to validate input and auto-generate OpenAPI docs — a huge productivity win.
This single script gives you interactive API docs at /docs with zero extra code.
5. Templates (Flask + Jinja2)
Flask ships with Jinja2 templates. You keep HTML in templates/ and render it with
render_template, passing variables in.
templates/home.html
--------------------
<!doctype html>
<html>
<head><title>{{ title }}</title></head>
<body>
<h1>Hello, {{ name }}!</h1>
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
</body>
</html>
app.py
------
from flask import render_template
@app.route("/home/<name>")
def home(name):
return render_template("home.html",
title="ABCL TECH", name=name,
items=["Python", "Flask", "Bangla"])
6. Deploying — Production Essentials
- WSGI server: use
gunicorn(Flask) oruvicorn(FastAPI); never run Flask's dev server in production. - Reverse proxy: nginx or Caddy in front — TLS, static files, rate limits.
- Containerize: Dockerfile with a slim base (
python:3.12-slim); expose one port. - Environment: secrets via env vars (
python-dotenvfor local dev). - Database: SQLAlchemy for SQL; hosted PostgreSQL (Supabase, Neon) is a good default.
- Observability: structured logging (
structlog), metrics, error tracking (Sentry).
7. Vocabulary (শব্দভাণ্ডার)
| Term | Meaning | বাংলায় |
|---|---|---|
| Route | URL → function mapping. | URL থেকে ফাংশনে mapping। |
| Endpoint | A specific URL a server handles. | Server-এর handle করা একটি নির্দিষ্ট URL। |
| Middleware | Code that runs around every request. | প্রতিটি request-এর চারপাশে চলা কোড। |
| REST | Convention: HTTP + JSON resources. | HTTP + JSON resource-এর convention। |
| WSGI / ASGI | Interface between Python and web server. | Python ও web server-এর মাঝের interface। |
8. Practice Problems
-
Sketch a Flask app with
/returning HTML and/api/pingreturning JSON.Flask app sketch করুন —/HTML দেবে,/api/pingJSON।✨ Show Answer (উত্তর দেখুন)
ans1.pyfrom flask import Flask, jsonify app = Flask(__name__) @app.route("/") def home(): return "<h1>hi</h1>" @app.route("/api/ping") def ping(): return jsonify({"ok": True}) print("run locally with: flask --app ans1 run") -
Sketch a FastAPI endpoint that takes a
namequery param and returns a greeting.FastAPI endpoint লিখুন — query paramnameনিয়ে greeting দেবে।✨ Show Answer (উত্তর দেখুন)
ans2.pyfrom fastapi import FastAPI app = FastAPI() @app.get("/greet") def greet(name: str = "world"): return {"msg": f"hello, {name}"} print("run: uvicorn ans2:app --reload") -
In two sentences, explain why FastAPI is often preferred for new APIs.দুই বাক্যে বলুন — নতুন API-এ FastAPI কেন prefer করা হয়।
✨ Show Answer (উত্তর দেখুন)
Answer: FastAPI uses Python type hints and Pydantic to validate inputs and auto-generate interactive OpenAPI docs — you get robust request parsing and documentation essentially for free. It is also async-native, so I/O-heavy endpoints (DB, external APIs) scale far better than a synchronous Flask app for equivalent hardware.
FastAPI Python type hint ও Pydantic দিয়ে input validate করে এবং auto-generate করে OpenAPI interactive docs — request parsing ও documentation প্রায় বিনামূল্যে মেলে। এটি async-native, তাই I/O-heavy endpoint (DB, external API) সমান হার্ডওয়্যারে synchronous Flask-এর চেয়ে অনেক ভালো scale করে।
-
Describe what goes into a minimal production deployment of a Flask app.Flask app-এর minimal production deployment-এ কী কী লাগে?
✨ Show Answer (উত্তর দেখুন)
1)
gunicornWSGI server, 2) nginx reverse proxy with TLS, 3) Dockerfile + a pinnedrequirements.txt, 4) env-var configuration, 5) external DB (PostgreSQL), 6) basic logging and an error tracker (Sentry), 7) a domain pointing at the load balancer. Most cloud providers (Fly.io, Railway, Render) give you these in one click. -
Write a pydantic model for an
Item(name, price, in_stock).Item(name, price, in_stock)— pydantic model লিখুন।✨ Show Answer (উত্তর দেখুন)
ans5.pyfrom pydantic import BaseModel class Item(BaseModel): name: str price: float in_stock: bool = True i = Item(name="rice", price=75.0) print(i.model_dump())
Summary — Module 37
Flask is a mature, simple WSGI framework perfect for traditional web apps. FastAPI is the modern choice for
async APIs — type-driven, auto-documented, fast. Both are a pip install away. Ship your app through
gunicorn/uvicorn behind nginx, containerized, with a real database and secret management. That is production.