Web Development: Flask / FastAPI Basics

ওয়েব ডেভেলপমেন্ট — Flask / FastAPI

Read: ~35 min Advanced 5 practice problems Install locally

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.

Python-এ web backend বানাতে দুটি আধুনিক framework dominant: Flask (সহজ, পরিপক্ব, synchronous) এবং FastAPI (আধুনিক, async, type-driven)। দুটোই micro-framework — ছোট ও focused। Full-stack কাজে Django আছে, কিন্তু Flask/FastAPI শেখার জন্য সঠিক জায়গা।
Install: 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

flask_app.py
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

fast_app.py
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) or uvicorn (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-dotenv for local dev).
  • Database: SQLAlchemy for SQL; hosted PostgreSQL (Supabase, Neon) is a good default.
  • Observability: structured logging (structlog), metrics, error tracking (Sentry).

7. Vocabulary (শব্দভাণ্ডার)

TermMeaningবাংলায়
RouteURL → function mapping.URL থেকে ফাংশনে mapping।
EndpointA specific URL a server handles.Server-এর handle করা একটি নির্দিষ্ট URL।
MiddlewareCode that runs around every request.প্রতিটি request-এর চারপাশে চলা কোড।
RESTConvention: HTTP + JSON resources.HTTP + JSON resource-এর convention।
WSGI / ASGIInterface between Python and web server.Python ও web server-এর মাঝের interface।

8. Practice Problems

  1. Sketch a Flask app with / returning HTML and /api/ping returning JSON.
    Flask app sketch করুন — / HTML দেবে, /api/ping JSON।
    ✨ Show Answer (উত্তর দেখুন)
    ans1.py
    from 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")
  2. Sketch a FastAPI endpoint that takes a name query param and returns a greeting.
    FastAPI endpoint লিখুন — query param name নিয়ে greeting দেবে।
    ✨ Show Answer (উত্তর দেখুন)
    ans2.py
    from fastapi import FastAPI
    app = FastAPI()
    
    @app.get("/greet")
    def greet(name: str = "world"):
        return {"msg": f"hello, {name}"}
    
    print("run: uvicorn ans2:app --reload")
  3. 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 করে।

  4. Describe what goes into a minimal production deployment of a Flask app.
    Flask app-এর minimal production deployment-এ কী কী লাগে?
    ✨ Show Answer (উত্তর দেখুন)

    1) gunicorn WSGI server, 2) nginx reverse proxy with TLS, 3) Dockerfile + a pinned requirements.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.

  5. Write a pydantic model for an Item(name, price, in_stock).
    Item(name, price, in_stock) — pydantic model লিখুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans5.py
    from 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.

Flask — পরিপক্ব ও সহজ WSGI framework; traditional web app-এ আদর্শ। FastAPI — আধুনিক async API-এর জন্য — type-driven, auto-documented, দ্রুত। production-এ gunicorn/uvicorn + nginx + container + database।

Next Module → APIs & Web Scraping — requests, httpx, BeautifulSoup।