2 Hours

2. Python Refresher for Backend Development

Python Fundamentals

Before diving deep into FastAPI, let us review the Python concepts that are essential for building backend APIs. You do not need to be an expert, but you should be comfortable with these fundamentals. The interactive sandbox validates your Python syntax, but to run these examples locally, save them to a .py file and run with python filename.py.

Type Hints (Annotations)

Type hints are the foundation of FastAPI's magic. They tell your IDE what type of data to expect and enable FastAPI to automatically validate incoming requests.

Python 3
# Without type hints (vanilla Python)
def get_user(name, age):
    return f"{name} is {age} years old"

# With type hints (FastAPI style)
def get_user(name: str, age: int) -> str:
    return f"{name} is {age} years old"
Local Testing: Save this code to a file called types.py and run python types.py. The code runs the same, but your IDE will give you better autocomplete and error checking.

Why Type Hints Matter in FastAPI

FastAPI reads your type hints to validate request data, generate JSON schemas, and produce API documentation. If you do not use type hints, FastAPI cannot perform these automatic features.

Optional and Union Types

In APIs, not every parameter is required. Python's Optional and Union types let you mark fields that can be None or have multiple possible types.

Python 3
from typing import Optional, Union

# Optional means the value can be None or the specified type
def get_user(user_id: int, include_details: Optional[bool] = None) -> dict:
    if include_details:
        return {"id": user_id, "details": "Full profile"}
    return {"id": user_id}

# Union means the value can be multiple types
def process_id(id_value: Union[int, str]) -> str:
    return f"Processing ID: {id_value}"
Local Testing: Run print(get_user(123)) and print(get_user(123, True)) to see both behaviors.

List and Dictionary Type Hints

Backend APIs frequently work with lists and dictionaries. Use type hints to specify what types they contain for better IDE support and validation.

Python 3
from typing import List, Dict

# List of strings
def get_names(names: List[str]) -> List[str]:
    return [name.upper() for name in names]

# Dictionary with string keys and integer values
def count_items(items: Dict[str, int]) -> int:
    return sum(items.values())

# Test locally
print(get_names(["alice", "bob"]))
print(count_items({"apple": 5, "banana": 3}))

Async/Await (Asynchronous Programming)

FastAPI supports async/await syntax. When you mark a function as async, it can perform I/O operations without blocking other requests.

Python 3
import asyncio

# Synchronous (blocks the entire thread)
def sync_task():
    import time
    time.sleep(2)
    return "Sync done"

# Asynchronous (non-blocking)
async def async_task():
    await asyncio.sleep(2)
    return "Async done"

# Running async code
async def main():
    result = await async_task()
    print(result)

# asyncio.run(main())
Async does not speed up CPU work! If you have heavy calculations like loops or image processing, use normal functions. Async is for I/O operations like database calls and network requests.

List Comprehensions

List comprehensions are a Pythonic way to transform and filter lists. They are used constantly in backend data processing.

Python 3
# Traditional loop
squares = []
for x in range(10):
    squares.append(x * x)

# List comprehension (cleaner and faster)
squares = [x * x for x in range(10)]

# With condition (filtering)
even_squares = [x * x for x in range(10) if x % 2 == 0]

# With transformation
users = [{"name": "Alice", "active": True}, {"name": "Bob", "active": False}]
active_names = [user["name"] for user in users if user["active"]]
print(active_names)

Exception Handling (Try/Except)

APIs must handle errors gracefully. You should never let an exception crash your server.

Python 3
# Basic exception handling
def divide(a: int, b: int) -> float:
    try:
        return a / b
    except ZeroDivisionError:
        return 0.0

# Multiple exception types
def process_data(data: dict) -> dict:
    try:
        value = data["key"] * 2
        return {"result": value}
    except KeyError:
        return {"error": "Missing key in data"}
    except TypeError:
        return {"error": "Invalid data type"}
    except Exception as e:
        return {"error": f"Unexpected error: {str(e)}"}
Local Testing: Call process_data({}) and see how it returns the KeyError message instead of crashing.

Context Managers (With Statement)

Context managers automatically handle setup and cleanup. They are essential for database connections, file handling, and locks.

Python 3
# Without context manager (manual cleanup)
file = open("data.txt", "r")
try:
    content = file.read()
finally:
    file.close()

# With context manager (automatic cleanup)
with open("data.txt", "w") as file:
    file.write("Hello, World!")
# File is automatically closed when exiting the block

# Verify the file was written
with open("data.txt", "r") as file:
    print(file.read())

Decorators

Decorators are functions that modify other functions. FastAPI uses them extensively for routing endpoints.

Python 3
# Simple decorator
def log_function_call(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned {result}")
        return result
    return wrapper

@log_function_call
def add(a, b):
    return a + b

print(add(3, 5))
# Output: Calling add
# add returned 8
# 8

Dataclasses (Python 3.7+)

Dataclasses are a concise way to create classes that primarily store data. They are a simpler alternative to Pydantic models when you do not need validation.

Python 3
from dataclasses import dataclass

# Regular class (verbose)
class User:
    def __init__(self, name, age, email):
        self.name = name
        self.age = age
        self.email = email

# Dataclass (concise)
@dataclass
class User:
    name: str
    age: int
    email: str

# Create a user
alice = User(name="Alice", age=30, email="alice@example.com")
print(alice)
# Output: User(name='Alice', age=30, email='alice@example.com')
Note: FastAPI uses Pydantic, which is like dataclasses on steroids. Pydantic adds validation, serialization, and JSON schema generation.

Knowledge Check

Ready to test your understanding of 2. Python Refresher for Backend Development?

Back