Chapter 4 · Your First Backend
What a Backend Does: Requests, Routes and Responses
- Page 16 of 22
- 21 min read
For the last few pages you have been the client: you sent requests to the BitByte Practice API with curl and requests, and it answered. Now you switch sides. A backend is the program that sits on a server, waits for those requests, decides what each one means, does the work (read a database, run a model, call an LLM provider) and sends back a response. Every AI product you will build has one: the chat window, the mobile app and the Slack bot are just clients of it.
Before using a framework, you will write a tiny backend with nothing but Python's standard library. It is clumsy on purpose. Once you have parsed URLs, read request bodies, chosen status codes and caught crashes by hand, you will know exactly what FastAPI does for you on the next page, and you will be able to debug it when something goes wrong underneath.
What you will learn
- What a backend and an API server are, and how they differ from the frontend.
- The life of one request, from the client's socket to your handler and back.
- Routing, path and query parameters, request bodies and JSON serialisation, by hand.
- Which status code to send when, configuration from environment variables, logging and error handling.
- Sync vs async: what it really means, and when it matters for AI backends.
Frontend, backend and API server
The frontend is what the user touches: a web page in the browser, a mobile app, a command-line tool. It runs on the user's device, so you cannot trust it with secrets or rules. The backend runs on machines you control. It holds the API keys, talks to the database and the model, enforces who may do what, and keeps the business rules in one place, so every client gets the same behaviour.
An API server is a backend whose clients are other programs rather than people reading HTML. It speaks HTTP and (almost always) JSON. Most modern AI products are built exactly like this: a React or mobile frontend calls a JSON API, and the API calls the model.
| Part | Runs on | Typical job in an AI product | Can be trusted with secrets? |
|---|---|---|---|
| Frontend (web, mobile, CLI) | The user's device | Show the chat, collect the question, display the answer | No: anyone can read its code and traffic |
| Backend / API server | Your server or cloud | Check the user, validate input, call the model or LLM, save results, count usage | Yes: keys live here, in environment variables |
| Database | Your server or a managed service | Users, conversations, documents, feedback | Reached only through the backend |
| Model / LLM provider | Your GPU box, or OpenAI, Anthropic and others | Turn input into a prediction or a reply | Called only by the backend, with its key |
That last column is the most important reason the backend exists. If a mobile app called an LLM provider directly, the provider key would ship inside the app, and someone would extract it within days.
The life of one request
When a client sends GET /courses?level=beginner, this is what happens on the server side, in order:
client (curl, browser, app)
| 1. opens a TCP connection to the server's host and port
| 2. sends the request text: method, path, headers, optional body
v
server process (listening on a port, e.g. 8000)
| 3. parse: method=GET path=/courses query={"level": ["beginner"]} headers body
| 4. route: which handler owns "GET /courses"? none -> 404
| 5. handle: validate input -> do the work (database, model, LLM) -> build a result
| 6. serialise: Python dict -> JSON text -> bytes, plus status code and headers
| 7. log: "GET /courses?level=beginner" 200
v
client receives: status line, headers, JSON bodySteps 3, 4, 6 and 7 are the same in every backend ever written. Only step 5 is your actual product. That is the whole argument for frameworks: they do 3, 4, 6 and 7 for you, correctly, so you spend your time on 5.
A tiny backend with only the standard library
Each page starts in a fresh home folder, so make a project folder for this one:
mkdir -p ~/projects/tiny-backend
cd ~/projects/tiny-backend
python --versionPython 3.12.3Your Python may be newer (the course standardises on 3.14); everything here works on 3.12 and later. Now save this file as tiny_server.py. Read it slowly: every numbered step from the diagram is in there somewhere.
# file: tiny_server.py
"""A tiny JSON backend using only Python's standard library (no framework)."""
import json
import logging
import os
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlsplit
# Configuration comes from environment variables, with safe defaults.
APP_NAME = os.environ.get("APP_NAME", "tiny-backend")
PORT = int(os.environ.get("PORT", "8000"))
LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO")
logging.basicConfig(level=LOG_LEVEL, format="%(levelname)s %(name)s: %(message)s")
log = logging.getLogger(APP_NAME)
COURSES = [
{"id": 1, "title": "How AI Works", "level": "beginner", "hours": 3},
{"id": 2, "title": "Python for AI", "level": "beginner", "hours": 12},
{"id": 3, "title": "RAG Systems", "level": "advanced", "hours": 10},
]
POSITIVE = {"good", "great", "love", "excellent", "helpful", "clear"}
NEGATIVE = {"bad", "slow", "boring", "confusing", "hate", "broken"}
def classify(text):
"""A stand-in for a real ML model: count happy and unhappy words."""
words = text.lower().replace(".", " ").replace(",", " ").split()
score = sum(w in POSITIVE for w in words) - sum(w in NEGATIVE for w in words)
return "positive" if score > 0 else "negative" if score < 0 else "neutral"
class Handler(BaseHTTPRequestHandler):
# ---- step 6: serialise a Python object into an HTTP response
def send_json(self, status, data):
body = json.dumps(data).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
# ---- step 7: send the built-in access log through the logging module
def log_message(self, format, *args):
log.info(format, *args)
# ---- error handling: one place that turns any crash into a clean 500
def safely(self, route):
try:
route()
except Exception:
log.exception("unhandled error on %s %s", self.command, self.path)
self.send_json(500, {"detail": "Internal server error"})
def do_GET(self):
self.safely(self.route_get)
def do_POST(self):
self.safely(self.route_post)
# ---- steps 3 and 4: parse the URL and route it
def route_get(self):
url = urlsplit(self.path) # "/courses?level=beginner" -> path + query
query = parse_qs(url.query) # "level=beginner" -> {"level": ["beginner"]}
parts = url.path.strip("/").split("/")
if url.path == "/health":
self.send_json(200, {"status": "ok", "app": APP_NAME})
elif url.path == "/courses":
level = query.get("level", [None])[0]
items = [c for c in COURSES if level is None or c["level"] == level]
self.send_json(200, {"count": len(items), "items": items})
elif url.path == "/stats":
level = query.get("level", [None])[0]
hours = [c["hours"] for c in COURSES if c["level"] == level]
self.send_json(200, {"level": level, "average_hours": sum(hours) / len(hours)})
elif len(parts) == 2 and parts[0] == "courses":
if not parts[1].isdigit():
self.send_json(400, {"detail": "Course id must be a whole number"})
return
course = next((c for c in COURSES if c["id"] == int(parts[1])), None)
if course is None:
self.send_json(404, {"detail": f"Course {parts[1]} not found"})
else:
self.send_json(200, course)
else:
self.send_json(404, {"detail": f"No route for GET {url.path}"})
def route_post(self):
if self.path != "/sentiment":
self.send_json(404, {"detail": f"No route for POST {self.path}"})
return
length = int(self.headers.get("Content-Length", 0))
raw = self.rfile.read(length) # the body arrives as bytes
try:
data = json.loads(raw) # bytes of JSON -> Python objects
except json.JSONDecodeError:
self.send_json(400, {"detail": "Body must be valid JSON"})
return
text = data.get("text") if isinstance(data, dict) else None
if not isinstance(text, str) or not text.strip():
self.send_json(422, {"detail": "Field 'text' is required and must be a non-empty string"})
return
log.debug("classifying %d characters", len(text))
self.send_json(200, {"label": classify(text), "model": "keyword-v1"})
if __name__ == "__main__":
server = ThreadingHTTPServer(("127.0.0.1", PORT), Handler)
log.info("%s listening on http://127.0.0.1:%d", APP_NAME, PORT)
server.serve_forever()Start it. A server runs until you stop it, so on your own machine you would run it in a second terminal and watch its log there. On this page we start it in the background (&), send its output to server.log, remember its process id in SERVER_PID, and let curl --retry wait until it answers:
APP_NAME=bitbyte-tiny PORT=8000 python tiny_server.py > server.log 2>&1 &
export SERVER_PID=$!
curl -s --retry 20 --retry-connrefused --retry-delay 0 http://localhost:8000/health{"status": "ok", "app": "bitbyte-tiny"}The APP_NAME=… PORT=… python … form sets environment variables for that one command only. The /health endpoint is the first one every backend should have: load balancers, Docker and uptime monitors call it to ask "are you alive?".
Routing: which code handles which request
Routing maps a method plus a path to a handler. An endpoint is one such pair, such as GET /courses. In tiny_server.py the router is an if/elif chain, and anything it does not recognise falls through to a 404:
curl -s http://localhost:8000/courses
echo
curl -s http://localhost:8000/teachers
echo
curl -s -X DELETE http://localhost:8000/courses/1{"count": 3, "items": [{"id": 1, "title": "How AI Works", "level": "beginner", "hours": 3}, {"id": 2, "title": "Python for AI", "level": "beginner", "hours": 12}, {"id": 3, "title": "RAG Systems", "level": "advanced", "hours": 10}]}
{"detail": "No route for GET /teachers"}
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error response</title>
</head>
<body>
<h1>Error response</h1>
<p>Error code: 501</p>
<p>Message: Unsupported method ('DELETE').</p>
<p>Error code explanation: 501 - Server does not support this operation.</p>
</body>
</html>The last response came from the standard library itself: an HTML page saying 501 (not implemented), because the handler class has no do_DELETE method. A JSON API should answer 405 Method Not Allowed there, in JSON, since the path exists and only the method is wrong. That is a small example of the many details a hand-written server gets wrong unless you remember every one of them.
Path parameters, query parameters and the body
A request can carry input in three places. Here is each one, with the code that reads it:
| Where | Example | Use it for | Read in tiny_server.py with |
|---|---|---|---|
| Path parameter | /courses/2 | Which resource: an id or a name | url.path.split("/") |
| Query parameter | /courses?level=beginner | Optional filters, sorting, paging | parse_qs(url.query) |
| Body | {"text": "Great course"} | Data you send to create or process something | self.rfile.read(length) then json.loads |
curl -s http://localhost:8000/courses/2
echo
curl -s http://localhost:8000/courses/99
echo
curl -s http://localhost:8000/courses/two
echo
curl -s "http://localhost:8000/courses?level=advanced"{"id": 2, "title": "Python for AI", "level": "beginner", "hours": 12}
{"detail": "Course 99 not found"}
{"detail": "Course id must be a whole number"}
{"count": 1, "items": [{"id": 3, "title": "RAG Systems", "level": "advanced", "hours": 10}]}Notice that everything in a URL arrives as text. The 2 in /courses/2 is the string "2" until your code checks it (isdigit()) and converts it (int()). Forget the check and /courses/two crashes the handler. Also, parse_qs returns a list for every key, because ?tag=a&tag=b is legal; that is why the code says query.get("level", [None])[0].
The body is for real input, like text to classify. Send JSON with the right Content-Type:
curl -s -X POST http://localhost:8000/sentiment \
-H "Content-Type: application/json" \
-d '{"text": "Great course, the examples are clear and helpful."}'
echo
curl -s -X POST http://localhost:8000/sentiment -d 'not json'
echo
curl -s -X POST http://localhost:8000/sentiment -H "Content-Type: application/json" -d '{"txt": "typo in the key"}'{"label": "positive", "model": "keyword-v1"}
{"detail": "Body must be valid JSON"}
{"detail": "Field 'text' is required and must be a non-empty string"}Three requests, three different answers, and each one tells the client exactly what to fix. The handler checked, by hand, that the body is JSON, that it is an object, that text exists, is a string and is not empty. Imagine writing those checks for a request with fifteen fields. On the page after next, Pydantic will do it from a class definition.
JSON serialisation
Serialisation turns a Python object into bytes you can send; deserialisation turns received bytes back into objects. JSON has only six kinds of value (object, array, string, number, true/false, null), so not every Python object fits:
import json
from datetime import datetime
reply = {"label": "positive", "score": 0.93, "cached": False, "tags": ("ai", "nlp"), "error": None}
print(json.dumps(reply))
try:
json.dumps({"created": datetime(2026, 10, 11, 9, 30)})
except TypeError as exc:
print("TypeError:", exc)
print(json.dumps({"created": datetime(2026, 10, 11, 9, 30).isoformat()}))
print(json.dumps({"note": "café"}), json.dumps({"note": "café"}, ensure_ascii=False)){"label": "positive", "score": 0.93, "cached": false, "tags": ["ai", "nlp"], "error": null}
TypeError: Object of type datetime is not JSON serializable
{"created": "2026-10-11T09:30:00"}
{"note": "caf\u00e9"} {"note": "café"}What to notice: False became false, None became null, and the tuple became a JSON array. A datetime is refused, so APIs send dates as ISO 8601 strings. Non-English text is escaped by default; both forms are valid JSON and decode to the same string. Frameworks handle all of this (dates, decimals, UUIDs, your own classes) for you.
Status codes your backend sends
On the client side you read status codes. On the server side you choose them, and the choice is part of your API's contract: client code branches on it, and retry logic (like the one you wrote on Reliable API Calls: Timeouts, Retries, Pagination and LLM APIs) trusts it.
| Situation in your handler | Send | Why |
|---|---|---|
| It worked, here is the data | 200 OK | The normal success |
| A new resource was created | 201 Created | Tells the client something now exists |
| It worked, nothing to return (e.g. delete) | 204 No Content | No body at all |
| The request is malformed (not JSON, wrong type in the URL) | 400 Bad Request | The client must change the request. Our hand-written server uses 400; FastAPI answers 422 for a body that is not valid JSON or has wrong values (next pages), and some other frameworks use 400 |
| No or bad credentials / valid credentials but not allowed | 401 / 403 | Authentication vs authorisation |
| The thing asked for does not exist | 404 Not Found | Unknown id or route |
| Well-formed but the fields are invalid | 422 Unprocessable Content | What FastAPI uses for validation errors |
| The client is sending too fast | 429 Too Many Requests | Add Retry-After |
| Your code crashed | 500 Internal Server Error | Never the client's fault; log it, hide the details |
| A service you depend on (DB, LLM provider) is down | 502 / 503 | Tells the client a retry later may work |
The golden rule: 4xx means "client, fix your request"; 5xx means "server, fix yourself". Returning 200 with {"error": "..."} inside breaks every client's retry and monitoring logic.
Logging and error handling
A backend has no screen. When something goes wrong at 3 a.m., its log is all you have. Look at what tiny_server.py has written so far:
cat server.logINFO bitbyte-tiny: bitbyte-tiny listening on http://127.0.0.1:8000
INFO bitbyte-tiny: "GET /health HTTP/1.1" 200 -
INFO bitbyte-tiny: "GET /courses HTTP/1.1" 200 -
INFO bitbyte-tiny: "GET /teachers HTTP/1.1" 404 -
INFO bitbyte-tiny: code 501, message Unsupported method ('DELETE')
INFO bitbyte-tiny: "DELETE /courses/1 HTTP/1.1" 501 -
INFO bitbyte-tiny: "GET /courses/2 HTTP/1.1" 200 -
INFO bitbyte-tiny: "GET /courses/99 HTTP/1.1" 404 -
INFO bitbyte-tiny: "GET /courses/two HTTP/1.1" 400 -
INFO bitbyte-tiny: "GET /courses?level=advanced HTTP/1.1" 200 -
INFO bitbyte-tiny: "POST /sentiment HTTP/1.1" 200 -
INFO bitbyte-tiny: "POST /sentiment HTTP/1.1" 400 -
INFO bitbyte-tiny: "POST /sentiment HTTP/1.1" 422 -One line per request: method, path, status. (Real servers also log the time; the format here leaves it out so your output matches the page. In production add %(asctime)s.) Now trigger a real bug. /stats computes an average, and nobody thought about a level with no courses:
curl -s "http://localhost:8000/stats?level=beginner"
echo
curl -s -w "\nstatus: %{http_code}\n" "http://localhost:8000/stats?level=expert"{"level": "beginner", "average_hours": 7.5}
{"detail": "Internal server error"}
status: 500The client got a short, safe message and a 500. The details went to the log, where you can see them and an attacker cannot:
tail -n 9 server.logERROR bitbyte-tiny: unhandled error on GET /stats?level=expert
Traceback (most recent call last):
File "/home/nadia/projects/tiny-backend/tiny_server.py", line 50, in safely
route()
File "/home/nadia/projects/tiny-backend/tiny_server.py", line 76, in route_get
self.send_json(200, {"level": level, "average_hours": sum(hours) / len(hours)})
~~~~~~~~~~~^~~~~~~~~~~~
ZeroDivisionError: division by zero
INFO bitbyte-tiny: "GET /stats?level=expert HTTP/1.1" 500 -Read a traceback from the bottom up: the error (ZeroDivisionError), the line that raised it, then the calls that led there. This split, friendly message out, full detail in the log, is the pattern every production API follows. Never send a traceback to the client: it reveals file paths, library versions and sometimes data. Never log secrets either: API keys, passwords and users' full prompts do not belong in log files.
Configuration from the environment
The same code runs on your laptop, in CI and in production, with different settings: port, log level, database URL, model name, the LLM provider's API key. Those go in environment variables, never in the code (you met them on Environment Variables, .env Files and Virtual Environments). Stop the server and start it again with more detailed logging:
kill $SERVER_PID
while kill -0 $SERVER_PID 2>/dev/null; do sleep 0.1; done
APP_NAME=bitbyte-debug LOG_LEVEL=DEBUG PORT=8000 python tiny_server.py > server.log 2>&1 &
export SERVER_PID=$!
curl -s --retry 20 --retry-connrefused --retry-delay 0 http://localhost:8000/health
echo
curl -s -X POST http://localhost:8000/sentiment -H "Content-Type: application/json" -d '{"text": "Too slow and confusing"}'
echo
cat server.log{"status": "ok", "app": "bitbyte-debug"}
{"label": "negative", "model": "keyword-v1"}
INFO bitbyte-debug: bitbyte-debug listening on http://127.0.0.1:8000
INFO bitbyte-debug: "GET /health HTTP/1.1" 200 -
DEBUG bitbyte-debug: classifying 22 characters
INFO bitbyte-debug: "POST /sentiment HTTP/1.1" 200 -The while kill -0 line waits until the old process has really exited, so the new one can take the port. Same code, different behaviour: a new name and a DEBUG line you did not see before. Changing a setting never needs a code change, and secrets never enter Git.
| Task | bash (macOS, Linux, Git Bash) | PowerShell |
|---|---|---|
| Set a variable for one command | PORT=8000 python tiny_server.py | not available; set it first |
| Set for this terminal | export LOG_LEVEL=DEBUG | $env:LOG_LEVEL = "DEBUG" |
| Read it | echo $LOG_LEVEL | $env:LOG_LEVEL |
Sync vs async, in one section
Most of a backend's time is spent waiting: for the database, for another API, and above all for an LLM, which can take seconds per reply. What the server does while it waits decides how many users it can serve.
- Synchronous (sync) code waits by blocking: the thread stops until the answer arrives. To serve several users at once, the server needs several threads or processes.
ThreadingHTTPServergives each request its own thread; the plainHTTPServerwould serve one request at a time. - Asynchronous (async) code waits by stepping aside:
awaithands control back to an event loop, which runs other work until the answer arrives. One thread can keep many slow requests in flight.
Here are three fake "model calls" that each wait one second, done both ways:
import asyncio
import time
def call_model_sync(name):
time.sleep(1) # blocks: nothing else runs in this thread
return f"{name}: done"
async def call_model_async(name):
await asyncio.sleep(1) # steps aside: the event loop runs other work
return f"{name}: done"
start = time.perf_counter()
print([call_model_sync(n) for n in ("q1", "q2", "q3")])
print(f"sync, one after another: about {round(time.perf_counter() - start)} s")
async def main():
return await asyncio.gather(*(call_model_async(n) for n in ("q1", "q2", "q3")))
start = time.perf_counter()
print(asyncio.run(main()))
print(f"async, waiting together: about {round(time.perf_counter() - start)} s")['q1: done', 'q2: done', 'q3: done']
sync, one after another: about 3 s
['q1: done', 'q2: done', 'q3: done']
async, waiting together: about 1 sThe rules you need for now:
- Async helps when you are waiting on I/O (network, disk, database) with async libraries. It does not make CPU work, such as running a scikit-learn model, any faster.
- One blocking call (
time.sleep,requests.get) insideasynccode freezes the whole event loop, and every other user waits. - FastAPI lets you write both: an
async defendpoint runs on the event loop, and a plaindefendpoint runs in a thread pool so blocking code is safe. When in doubt, writedef. The advanced tutorial goes deeper.
What a framework does for you
Look back at tiny_server.py: about a hundred lines, and most of them are plumbing. Here is that plumbing next to what FastAPI gives you on the next page:
| You did by hand | FastAPI does it with |
|---|---|
if/elif routing, manual 404s, no 405s | @app.get("/courses") decorators; 404 and 405 automatically |
Splitting the path, isdigit(), int() | course_id: int in the function signature |
parse_qs and [None])[0] | level: str | None = None |
Reading bytes, json.loads, checking each field | A Pydantic model; errors become a detailed 422 |
json.dumps, headers, Content-Length | Return a dict or a model |
The safely() wrapper | Built in: unhandled errors become a 500 and are logged |
| Threads only | def and async def endpoints, both served well |
| No documentation | Interactive docs at /docs generated from your code |
Where this shows up in real AI work
- LLM features: a chat frontend sends the user's message to your backend; the backend checks the user's quota, adds the system prompt, calls the provider with the key it keeps secret, logs token usage and returns the reply.
- Model serving: a
/predictendpoint wraps a trained model exactly like/sentimentwrapsclassify(): validate input, run the model, return JSON with the model version. - Health checks and logs: hosting platforms restart a container whose
/healthstops answering, and the logs are how you find out why. - Configuration: switching from a cheap model to a better one, or from staging to production, is an environment-variable change, not a code change.
Common mistakes
- Calling an LLM provider straight from the frontend. The API key ships to every user's browser or phone. Fix: the frontend calls your backend; only the backend holds the key.
- Trusting input because "our app never sends that". Anyone can call your API with
curl, as you just did. Fix: validate every path parameter, query parameter and body field on the server. - Returning 200 for errors, or 500 for the client's mistakes. Clients retry 5xx and give up on 4xx, so wrong codes cause pointless retries or hidden failures. Fix: use the table above.
- Sending tracebacks or secrets to clients, or writing secrets into logs. Fix: a generic message for the client, the full traceback in the log, and never log keys, passwords or tokens.
- Blocking calls inside async code. One
time.sleeporrequests.getin anasyncfunction stalls every request. Fix: use an async library withawait, or a plaindefendpoint.
Try it yourself
The tiny server is still running from the previous section. For the medium and hard tasks, edit tiny_server.py, then restart the server (stop it, wait, start it, exactly like in the configuration section) and test your change with curl.
- Easy: Use
curl -s -o /dev/null -w "%{http_code}\n"to print only the status code ofGET /courses/3,GET /courses/30andGET /nothing. - Medium: Fix the
/statsbug so that a level with no courses returns404with{"detail": "No courses for level 'expert'"}instead of crashing. Which status code would you choose iflevelwere missing altogether, and why? - Hard: Add a
max_lengthrule to/sentiment: texts longer than 200 characters get422with a clear message. Why does an AI endpoint need a limit like this even when the model could handle longer input?
Answers
for path in /courses/3 /courses/30 /nothing; do
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8000$path
done200
404
404For the medium task, check before dividing. Replace the /stats branch with:
elif url.path == "/stats":
level = query.get("level", [None])[0]
hours = [c["hours"] for c in COURSES if c["level"] == level]
if not hours:
self.send_json(404, {"detail": f"No courses for level {level!r}"})
return
self.send_json(200, {"level": level, "average_hours": sum(hours) / len(hours)})A missing level is a malformed request rather than a missing resource, so 400 (or 422, which FastAPI would send for a missing required query parameter) is the honest answer. For the hard task, add a check right after the existing text check:
if len(text) > 200:
self.send_json(422, {"detail": "Field 'text' must be at most 200 characters"})
returnLimits protect you: every character sent to an LLM costs tokens (money), takes time, and a huge body can tie up your server. Input limits are the first defence against abuse and surprise bills.
When you have finished, stop the server:
kill $SERVER_PIDSummary
- The backend runs on machines you control: it validates input, holds secrets, talks to databases and models, and serves many clients through one API.
- Every request goes through parse, route, handle, serialise and log; only "handle" is your product.
- Input arrives in the path, the query string or the body, always as text or bytes, and must be checked and converted.
- Choose status codes deliberately: 2xx success, 4xx client mistakes, 5xx server problems. Log the details, return a safe message.
- Configuration and secrets come from environment variables. Async helps with waiting on I/O; blocking calls in async code hurt everyone.
Next: Your First FastAPI App. You will rebuild this server in a fraction of the code, with typed parameters, automatic validation and interactive documentation, using a proper uv project.

