Python (FastAPI)
Python used with FastAPI to build typed, high-performance HTTP APIs and backend services.
Why it exists.
It provides a productive way to turn domain logic into documented, testable web endpoints.
Where it shines.
API services, automation backends, and teams that value fast iteration with strong typing and validation.
Where not to use it.
Do not use it without defining service boundaries, dependency management, and production observability.
What it is made of.
- Python
- FastAPI
- Pydantic
- ASGI server
- OpenAPI
How it works.
- A route declares an endpoint
- Pydantic validates input
- Application logic runs
- The API returns a typed response
How it works
Run a Python script
Python executes a module’s top-level statements. In CPython, source is compiled to bytecode and executed by the interpreter. Save as hello.py, then run python3 hello.py; on Windows, use py hello.py.
name = "World"
print(f"Hello, {name}!")Blocks and functions
Indentation defines blocks. Use four spaces consistently. def defines reusable behavior; the main guard runs code when the file is executed directly.
def greet(name):
return f"Hello, {name}!"
if __name__ == "__main__":
print(greet("Ada"))Variables & print
Values and formatting
Variables refer to objects. Common types include strings, integers, booleans, lists, and dictionaries. print writes text; f-strings interpolate expressions.
name = "Ada"
count = 3
enabled = True
print(f"{name}: {count} tasks, enabled={enabled}")Input and arguments
input returns a string. sys.argv contains the script name followed by command-line arguments. Convert numeric input explicitly.
import sys
name = sys.argv[1] if len(sys.argv) > 1 else "World"
print(f"Hello, {name}")
environment = input("Environment: ")
print("Selected:", environment)If / else
Choose a branch
Use if, elif, and else with colons and indented bodies. == compares values; = assigns them.
count = 3
if count > 5:
print("Large batch")
elif count > 0:
print("Small batch")
else:
print("Nothing to process")Combine conditions
Use and, or, and not. Empty collections, empty strings, None, and numeric zero are false in conditions.
environment = "production"
approved = True
if environment == "production" and approved:
print("Ready to deploy")
else:
print("Approval needed")For loops
Iterate over items
for traverses an iterable. range excludes its stop value. break exits a loop and continue skips the current iteration.
for environment in ["development", "staging", "production"]:
print(environment)
for attempt in range(1, 4):
print(f"Attempt {attempt}")Work with dictionaries
items provides key/value pairs. enumerate adds an index when iterating over a sequence.
services = {"api": "healthy", "worker": "degraded"}
for name, status in services.items():
print(f"{name}: {status}")API calls
GET with the standard library
No additional package is needed. Request adds headers, urlopen sets a timeout, and json parses the response. HTTPError handles HTTP failures; URLError handles connection failures.
import json
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError
request = Request(
"https://api.github.com/repos/octocat/Hello-World",
headers={"Accept": "application/vnd.github+json", "User-Agent": "python-reference"},
)
try:
with urlopen(request, timeout=20) as response:
data = json.load(response)
print(data["full_name"])
except HTTPError as error:
print(f"HTTP failure: {error.code}")
except URLError as error:
print(f"Connection failure: {error.reason}")POST JSON with authentication
Replace the example endpoint. Set API_TOKEN in your environment. Serialize the dictionary to JSON bytes and set the content type. The response here is assumed to be JSON.
import json
import os
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError
payload = json.dumps({"name": "demo"}).encode("utf-8")
request = Request(
"https://api.example.com/items",
data=payload,
method="POST",
headers={"Content-Type": "application/json", "Authorization": f"Bearer {os.environ['API_TOKEN']}"},
)
try:
with urlopen(request, timeout=20) as response:
print(json.load(response))
except HTTPError as error:
print(f"HTTP failure: {error.code}")
except URLError as error:
print(f"Connection failure: {error.reason}")