---
title: "Python Web Framework Examples"
description: "Code examples for Flask and FastAPI web applications including API structure, async patterns, SQLAlchemy integration, and configuration management with dataclasses."
type: reference
domain: development
tags: [python, flask, fastapi, sqlalchemy, web-api, async]
---

# Python Web Framework Examples

## Flask API Structure

```python
# app.py
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
import logging

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
db = SQLAlchemy(app)

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

@app.route('/api/users', methods=['GET'])
def get_users():
    try:
        users = User.query.all()
        return jsonify([{'id': u.id, 'username': u.username, 'email': u.email} for u in users])
    except Exception as e:
        logger.error(f"Error fetching users: {e}")
        return jsonify({'error': 'Internal server error'}), 500

@app.route('/api/users', methods=['POST'])
def create_user():
    try:
        data = request.get_json()
        user = User(username=data['username'], email=data['email'])
        db.session.add(user)
        db.session.commit()
        return jsonify({'id': user.id}), 201
    except Exception as e:
        logger.error(f"Error creating user: {e}")
        return jsonify({'error': 'Bad request'}), 400

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(debug=True)
```

## FastAPI Async Pattern

```python
# main.py
from fastapi import FastAPI, HTTPException, Depends
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
import logging

app = FastAPI()

# Database setup
DATABASE_URL = "sqlite+aiosqlite:///./app.db"
engine = create_async_engine(DATABASE_URL)
AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

async def get_db():
    async with AsyncSessionLocal() as session:
        yield session

@app.get("/api/users")
async def get_users(db: AsyncSession = Depends(get_db)):
    try:
        # Database query logic here
        return {"users": []}
    except Exception as e:
        logging.error(f"Error: {e}")
        raise HTTPException(status_code=500, detail="Internal server error")
```

## Configuration Management

```python
# config.py
import os
from dataclasses import dataclass

@dataclass
class Config:
    SECRET_KEY: str = os.getenv('SECRET_KEY', 'dev-secret-key')
    DATABASE_URL: str = os.getenv('DATABASE_URL', 'sqlite:///app.db')
    DEBUG: bool = os.getenv('DEBUG', 'False').lower() == 'true'
    LOG_LEVEL: str = os.getenv('LOG_LEVEL', 'INFO')

config = Config()
```