Category: Uncategorized

  • Python Fastapi Beginner Guide

    FastAPI has quickly become the go‑to framework for building modern, high‑performance APIs with Python. If you’re a developer who wants to create fast, reliable, and scalable web services without drowning in boilerplate code, this beginner guide will walk you through everything you need to know—from installation to building your first endpoint, handling requests, and deploying your app. By the end of this tutorial, you’ll have a solid foundation to start crafting production‑ready APIs with Python FastAPI.

    Why Choose FastAPI for Your First Python API?

    • Speed: Powered by Starlette and Pydantic, FastAPI delivers performance comparable to Node.js and Go.
    • Automatic documentation: Interactive Swagger UI and ReDoc are generated automatically.
    • Type‑safety: Leverages Python type hints for validation, autocomplete, and error reduction.
    • Asynchronous support: Built‑in async/await support makes handling concurrent requests a breeze.
    • Developer friendliness: Minimal boilerplate, clear error messages, and excellent community support.

    Getting Started: Install FastAPI and Uvicorn

    Before you write any code, set up a clean Python environment. We recommend using venv or conda to avoid version conflicts.

    python -m venv fastapi-env
    source fastapi-env/bin/activate   # On Windows use `fastapi-env\Scripts\activate`
    pip install fastapi uvicorn
    

    uvicorn is an ASGI server that runs FastAPI applications. With these two packages installed, you’re ready to create your first API.

    Creating Your First FastAPI Application

    Step 1: Project structure

    A simple project can start with a single file, but it’s good practice to keep things organized:

    my_fastapi_app/
    │
    ├─ app/
    │   ├─ __init__.py
    │   └─ main.py
    └─ requirements.txt
    

    Step 2: Write a basic endpoint

    Open app/main.py and add the following code:

    from fastapi import FastAPI
    
    app = FastAPI()
    
    @app.get("/")
    def read_root():
        return {"message": "Welcome to FastAPI! 🎉"}
    

    This tiny snippet does three things:

    1. Creates a FastAPI instance.
    2. Defines a GET route at /.
    3. Returns a JSON response automatically.

    Step 3: Run the server

    Launch the app with Uvicorn:

    uvicorn app.main:app --reload
    

    The --reload flag enables hot‑reloading—perfect for development. Open http://127.0.0.1:8000 in your browser and you’ll see the JSON message. Navigate to /docs for the interactive Swagger UI, or /redoc for ReDoc.

    Understanding Path Operations and HTTP Methods

    FastAPI calls each route a path operation. You can define any standard HTTP method using decorators like @app.get, @app.post, @app.put, @app.delete, and @app.patch. Here’s a quick example that demonstrates GET and POST operations for a simple todo list.

    from fastapi import FastAPI, HTTPException
    from pydantic import BaseModel
    from typing import List
    
    app = FastAPI()
    
    class TodoItem(BaseModel):
        id: int
        title: str
        completed: bool = False
    
    # In‑memory storage (just for demo)
    todos: List[TodoItem] = []
    
    @app.get("/todos", response_model=List[TodoItem])
    def list_todos():
        return todos
    
    @app.post("/todos", response_model=TodoItem, status_code=201)
    def create_todo(item: TodoItem):
        # Simple duplicate check
        if any(t.id == item.id for t in todos):
            raise HTTPException(status_code=400, detail="Todo with this ID already exists")
        todos.append(item)
        return item
    

    Key points to notice:

    • Type hints (e.g., List[TodoItem]) tell FastAPI how to validate and serialize data.
    • Pydantic models (like TodoItem) provide automatic request body parsing and response validation.
    • HTTPException lets you return custom error codes and messages.

    Leveraging Pydantic for Data Validation

    Pydantic is the engine behind FastAPI’s data handling. By defining models, you get:

    • Automatic request parsing.
    • JSON schema generation for OpenAPI docs.
    • Runtime validation with clear error messages.

    Example of a more complex model with validation rules:

    from pydantic import BaseModel, Field, EmailStr, validator
    
    class UserCreate(BaseModel):
        username: str = Field(..., min_length=3, max_length=30)
        email: EmailStr
        password: str = Field(..., min_length=8)
    
        @validator('password')
        def password_strength(cls, v):
            if not any(c.isdigit() for c in v):
                raise ValueError('Password must contain at least one digit')
            return v
    

    When this model is used as a request body, FastAPI will automatically reject invalid payloads and return a detailed 422 Unprocessable Entity response.

    Async vs. Sync Path Operations

    FastAPI supports both synchronous and asynchronous functions. Use async def when you need to call other async libraries (e.g., async database drivers, HTTP clients). For CPU‑bound tasks, stay synchronous to avoid blocking the event loop.

    # Synchronous example
    @app.get("/sync")
    def sync_endpoint():
        return {"msg": "This runs in a normal thread"}
    
    # Asynchronous example
    @app.get("/async")
    async def async_endpoint():
        await some_async_io()
        return {"msg": "This runs without blocking"}
    

    Dependency Injection Made Simple

    FastAPI’s dependency injection system lets you define reusable components—like database sessions, authentication logic, or configuration values—once and inject them into any path operation.

    from fastapi import Depends
    
    def get_query_param(q: str = None):
        return q
    
    @app.get("/items/")
    def read_items(q: str = Depends(get_query_param)):
        return {"query": q}
    

    Complex dependencies can be layered, making your code clean and testable.

    Handling Errors and Custom Exception Handlers

    While HTTPException covers most cases, you can create custom exception classes and register handlers to return consistent JSON error structures.

    from fastapi import Request, HTTPException
    from fastapi.responses import JSONResponse
    
    class ItemNotFoundException(Exception):
        def __init__(self, item_id: int):
            self.item_id = item_id
    
    @app.exception_handler(ItemNotFoundException)
    async def item_not_found_handler(request: Request, exc: ItemNotFoundException):
        return JSONResponse(
            status_code=404,
            content={"detail": f"Item with ID {exc.item_id} not found"}
        )
    

    Testing FastAPI Applications

    FastAPI integrates smoothly with pytest and httpx. Below is a minimal test suite for the todo endpoints.

    from fastapi.testclient import TestClient
    from app.main import app
    
    client = TestClient(app)
    
    def test_create_todo():
        response = client.post("/todos", json={"id": 1, "title": "Buy milk"})
        assert response.status_code == 201
        assert response.json()["title"] == "Buy milk"
    
    def test_list_todos():
        response = client.get("/todos")
        assert response.status_code == 200
        assert isinstance(response.json(), list)
    

    Running pytest will execute these tests, giving you confidence that your API behaves as expected.

    Deploying FastAPI to Production

    When you’re ready to go live, consider these best practices:

    1. Use a production‑grade ASGI server: uvicorn works for small loads, but gunicorn with uvicorn.workers.UvicornWorker scales better.
    2. Enable HTTPS: Terminate TLS at a reverse proxy like Nginx or use managed services (e.g., AWS Elastic Load Balancer).
    3. Environment variables: Store secrets (DB passwords, API keys) using python-dotenv or your cloud provider’s secret manager.
    4. Containerize with Docker: A typical Dockerfile looks like this:
    FROM python:3.12-slim
    
    WORKDIR /app
    COPY requirements.txt .
    RUN pip install --no-cache-dir -r requirements.txt
    
    COPY . .
    CMD ["gunicorn", "app.main:app", "-w", "4", "-k", "uvicorn.workers.UvicornWorker", "--bind", "0.0.0.0:8000"]
    

    Deploy the container to

  • Python Web App Using Django

    Building a robust, scalable, and secure web application in Python has never been easier thanks to Django. Whether you’re a seasoned developer or just starting out, Django’s “batteries‑included” philosophy provides everything you need—from an ORM and authentication system to a powerful admin interface—so you can focus on writing business logic instead of reinventing the wheel. In this guide we’ll walk through the entire lifecycle of a Python web app using Django: setting up the environment, creating a project, developing a simple to‑do list app, and finally deploying it to production. By the end, you’ll have a solid foundation to build more complex applications and a clear roadmap for scaling your Django projects.

    Why Choose Django for Python Web Apps

    Django stands out among Python web frameworks for several reasons that make it ideal for both small prototypes and large‑scale enterprise solutions.

    Key Features of Django

    • Rapid Development: Built‑in admin, forms, and authentication let you ship features quickly.
    • Security First: Protection against SQL injection, XSS, CSRF, and clickjacking out of the box.
    • Scalable Architecture: Supports caching, middleware, and asynchronous views for high‑traffic sites.
    • Extensive Ecosystem: Thousands of reusable apps on Django Packages for payments, REST APIs, and more.
    • Excellent Documentation: Clear, example‑driven docs that reduce onboarding time.

    Setting Up the Development Environment

    A clean, isolated environment ensures that your project’s dependencies don’t clash with other Python tools on your machine.

    Install Python and Virtualenv

    # Verify Python version (Django 5.x requires Python 3.8+)
    python3 --version
    
    # Install virtualenv if you don’t have it
    pip install virtualenv
    
    # Create and activate a virtual environment
    python3 -m venv myenv
    source myenv/bin/activate  # On Windows use `myenv\Scripts\activate`
    

    Installing Django

    # Upgrade pip for best compatibility
    pip install --upgrade pip
    
    # Install the latest stable Django release
    pip install Django
    
    # Verify installation
    django-admin --version
    

    Creating Your First Django Project

    With Django installed, you can generate a new project skeleton in a single command.

    1. Start a project named myproject:
      django-admin startproject myproject
    2. Navigate into the project directory:
      cd myproject
    3. Run the development server to confirm everything works:
      python manage.py runserver

      Open http://127.0.0.1:8000/ in your browser; you should see the default Django welcome page.

    4. Create an app called todo:
      python manage.py startapp todo

      The todo app will hold our models, views, and templates for the to‑do list example.

    Building a Simple Web App – A To‑Do List Example

    Let’s turn the freshly generated project into a functional web app that lets users add, view, and delete tasks.

    Defining the Model

    In todo/models.py, define a single Task model with a title and completion flag.

    from django.db import models
    
    class Task(models.Model):
        title = models.CharField(max_length=255)
        completed = models.BooleanField(default=False)
    
        def __str__(self):
            return self.title
    

    After saving the file, run migrations to create the database table:

    python manage.py makemigrations todo
    python manage.py migrate
    

    Creating Views and URLs

    In todo/views.py, add three basic views: list tasks, add a task, and delete a task.

    from django.shortcuts import render, redirect, get_object_or_404
    from .models import Task
    
    def task_list(request):
        tasks = Task.objects.all()
        return render(request, 'todo/task_list.html', {'tasks': tasks})
    
    def add_task(request):
        if request.method == 'POST':
            title = request.POST.get('title')
            if title:
                Task.objects.create(title=title)
            return redirect('task_list')
        return render(request, 'todo/add_task.html')
    
    def delete_task(request, task_id):
        task = get_object_or_404(Task, id=task_id)
        task.delete()
        return redirect('task_list')
    

    Map these views in todo/urls.py and include the file in the project’s main urls.py:

    # todo/urls.py
    from django.urls import path
    from . import views
    
    urlpatterns = [
        path('', views.task_list, name='task_list'),
        path('add/', views.add_task, name='add_task'),
        path('delete/<int:task_id>/', views.delete_task, name='delete_task'),
    ]
    
    # myproject/urls.py (add the include)
    from django.contrib import admin
    from django.urls import path, include
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('tasks/', include('todo.urls')),
    ]
    

    Designing Templates

    Create a templates/todo folder inside the todo app and add two HTML files.

    task_list.html displays all tasks with delete links:

    <!DOCTYPE html>
    <html>
    <head>
        <title>My To‑Do List</title>
    </head>
    <body>
        <h2>My Tasks</h2>
        <ul>
            {% for task in tasks %}
                <li>
                    {{ task.title }}
                    {% if not task.completed %} (Pending) {% else %} (Done) {% endif %}
                    <a href="{% url 'delete_task' task.id %}">Delete</a>
                </li>
            {% empty %}
                <li>No tasks yet!</li>
            {% endfor %}
        </ul>
        <a href="{% url 'add_task' %}">Add New Task</a>
    </body>
    </html>
    

    add_task.html provides a simple form:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Add Task</title>
    </head>
    <body>
        <h2>Add a New Task</h2>
        <form method="post">
            {% csrf_token %}
            <input type="text" name="title" placeholder="Task title" required>
            <button type="submit">Add</button>
        </form>
        <a href="{% url 'task_list' %}">Back to List</a>
    </body>
    </html>
    

    Run the server again (python manage.py runserver) and navigate to /tasks/ to see your functional to‑do list.

    Deploying Your Django Web App

    After development, the next step is to move your app to a production environment. Here are three popular deployment strategies:

    • Heroku: Simple Git‑based deployment, automatic SSL, and a managed PostgreSQL add‑on.
    • Docker + Nginx + Gunicorn: Containerize your app for consistent environments and scale with orchestration tools like Kubernetes.
    • Traditional VPS (e.g., DigitalOcean, Linode): Install Python, set up a virtualenv, configure systemd for Gunicorn, and serve static files via Nginx.

    Regardless of the platform, remember to:

    • Set DEBUG = False in settings.py.
    • Configure ALLOWED_HOSTS with your domain name.
    • Use a secure secret key (store it in environment variables).
  • Python Web App Using Flask

    Building a Python web app using Flask is one of the most rewarding ways to turn a simple idea into a fully functional, production‑ready service. Whether you’re a seasoned developer looking for a lightweight framework or a beginner eager to see instant results, Flask provides the perfect balance of flexibility, simplicity, and power. In this guide we’ll walk through everything you need to know—from setting up the environment and creating routes, to handling forms, integrating databases, and deploying your app to the cloud—so you can launch a robust Flask web application in no time.

    Why Choose Flask for Your Python Web App?

    Flask is often described as a “micro‑framework” because it ships with a minimal core, leaving you free to add only the components you actually need. This design philosophy brings several advantages:

    • Lightweight and fast: With a tiny footprint, Flask starts quickly and scales well for both prototypes and large‑scale projects.
    • Extensible: Hundreds of extensions (e.g., Flask‑SQLAlchemy, Flask‑Login, Flask‑Migrate) let you add ORM, authentication, migrations, and more without reinventing the wheel.
    • Easy to learn: A clean API and excellent documentation make onboarding smooth for developers of any skill level.
    • Pythonic: Flask follows Python’s “batteries‑included” philosophy—write clear, readable code that feels natural to the language.

    Setting Up Your Development Environment

    1. Install Python and Virtualenv

    First, ensure you have Python 3.10+ installed. Then create an isolated virtual environment to keep dependencies tidy:

    python -m venv venv
    source venv/bin/activate  # On Windows use: venv\Scripts\activate
    

    2. Install Flask

    With the virtual environment active, install Flask via pip:

    pip install Flask
    

    3. Verify the Installation

    Run a quick sanity check to confirm Flask is ready:

    python -c "import flask; print(flask.__version__)"
    

    Creating Your First Flask Route

    A Flask app is essentially a collection of routes—functions that return HTML, JSON, or other responses. Let’s start with the classic “Hello, World!” example.

    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/')
    def home():
        return '<h1>Hello, World!</h1>'
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    Save this as app.py and run python app.py. Visiting http://127.0.0.1:5000/ in your browser will display the greeting.

    Organizing a Real‑World Flask Project

    As your app grows, a flat file structure becomes unwieldy. Below is a recommended layout for a medium‑sized project:

    my_flask_app/
    │
    ├── app/
    │   ├── __init__.py      # Application factory
    │   ├── routes.py        # All view functions
    │   ├── models.py        # Database models
    │   ├── forms.py         # WTForms definitions
    │   └── templates/       # Jinja2 HTML templates
    │       └── base.html
    │
    ├── migrations/          # Database migration scripts (Flask‑Migrate)
    ├── venv/                # Virtual environment
    ├── config.py            # Configuration classes
    └── run.py               # Entry point
    

    Application Factory Pattern

    Using an application factory makes testing and configuration easier. Here’s a minimal __init__.py implementation:

    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    
    db = SQLAlchemy()
    
    def create_app(config_object='config.DevelopmentConfig'):
        app = Flask(__name__)
        app.config.from_object(config_object)
    
        db.init_app(app)
    
        with app.app_context():
            # Import parts of our application
            from . import routes, models
    
            # Register blueprints if you use them
            # app.register_blueprint(routes.bp)
    
        return app
    

    Working with Templates and Jinja2

    Flask uses the powerful Jinja2 templating engine to render dynamic HTML. Create a templates/base.html file that defines a common layout:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>{{ title|default('My Flask App') }}</title>
        <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    </head>
    <body>
        <header>
            <h1>{{ heading|default('Welcome') }}</h1>
        </header>
        <main>
            {% block content %}{% endblock %}
        </main>
        <footer>
            <p>&copy; {{ current_year }} My Flask App</p>
        </footer>
    </body>
    </html>
    

    Then extend this base in a page-specific template, for example templates/home.html:

    {% extends "base.html" %}
    {% block content %}
        <h2>Hello, {{ user_name }}!</h2>
        <p>This is a Flask‑powered page.</p>
    {% endblock %}
    

    Render the template from a view function:

    from flask import render_template
    from . import app
    
    @app.route('/home')
    def home():
        return render_template('home.html',
                               title='Home Page',
                               heading='Dashboard',
                               user_name='Alice',
                               current_year=2026)
    

    Handling Forms and User Input

    Flask‑WTForms simplifies form creation, validation, and CSRF protection. First, install the extension:

    pip install Flask-WTF
    

    Define a simple contact form in forms.py:

    from flask_wtf import FlaskForm
    from wtforms import StringField, TextAreaField, SubmitField
    from wtforms.validators import DataRequired, Email, Length
    
    class ContactForm(FlaskForm):
        name = StringField('Name', validators=[DataRequired(), Length(max=50)])
        email = StringField('Email', validators=[DataRequired(), Email()])
        message = TextAreaField('Message', validators=[DataRequired(), Length(max=500)])
        submit = SubmitField('Send')
    

    Use the form in a route and template:

    # routes.py
    from flask import render_template, flash, redirect, url_for
    from .forms import ContactForm
    
    @app.route('/contact', methods=['GET', 'POST'])
    def contact():
        form = ContactForm()
        if form.validate_on_submit():
            # Here you would normally process the data (e.g., send email)
            flash('Your message has been sent!', 'success')
            return redirect(url_for('contact'))
        return render_template('contact.html', form=form, title='Contact Us')
    

    Template snippet (contact.html) using Jinja2:

    {% extends "base.html" %}
    {% block content %}
        <h2>Contact Us</h2>
        <form method="POST">
            {{ form.hidden_tag() }}
            <div>{{ form.name.label }} {{ form.name(size=32) }}</div>
            <div>{{ form.email.label }} {{ form.email(size=32) }}</div>
            <div>{{ form.message.label }} {{ form.message(rows=5) }}</div>
            <div>{{ form.submit() }}</div>
        </form>
    {% endblock %}
    

    Integrating a Database with Flask‑SQLAlchemy

    Most real‑world apps need persistent storage. Flask‑SQLAlchemy provides a high‑level ORM that maps Python classes to database tables.

    pip install Flask-SQLAlchemy
    

    Configure the database in config.py:

    class DevelopmentConfig:
        DEBUG = True
        SECRET_KEY = 'your-secret-key'
        SQLALCHEMY_DATABASE_URI = 'sqlite:///site.db'
        SQLALCHEMY_TRACK_MODIFICATIONS = False
    

    Define a simple User model in models.py:

    from . import db
    from datetime import datetime
    
    class User(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        username = db.Column(db.String(20), unique=True, nullable=False)
        email = db.Column(db.String(120), unique=True, nullable=False)
        created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
        def __repr__(self):
            return f"<User {self.username}>"
    

    Initialize the database using Flask‑Migrate (optional but recommended):

    pip install Flask-Migrate
    

    Then add migration commands:

    # run.py
    from app import create_app, db
    from flask_migrate import Migrate
    
    app = create_app()
    migrate = Migrate(app, db)
    
    if __name__ == '__main__':
        app.run()
    

    Run the migration

  • Hello world!

    Welcome to WordPress. This is your first post. Edit or delete it, then start writing!