2. Python Refresher for Backend Development
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.
# 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"
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.
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}"
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.
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.
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())
List Comprehensions
List comprehensions are a Pythonic way to transform and filter lists. They are used constantly in backend data processing.
# 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.
# 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)}"}
Context Managers (With Statement)
Context managers automatically handle setup and cleanup. They are essential for database connections, file handling, and locks.
# 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.
# 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.
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')
Knowledge Check
Ready to test your understanding of 2. Python Refresher for Backend Development?