This lesson on FastAPI Basics — Routes, Path & Query Params is hands-on and example-driven. You can set up a production-ready FastAPI development environment, initialize the core application instance, and define synchronous HTTP endpoints that serialize Python dictionaries into JSON responses. You will also run and manage local development servers using the official FastAPI CLI tooling.
What You'll Be Able To Do
- Initialize a new Python project and install FastAPI with the standard bundle containing Uvicorn and CLI tools.
- Instantiate the central FastAPI application object in a root module.
- Define a root HTTP GET endpoint using route decorators and synchronous Python functions.
- Return native Python dictionaries from route handlers to leverage automatic JSON serialization.
- Start and manage a live local development server with the FastAPI CLI.
Detailed Concept Walkthrough
1. Environment Initialization and Standard Dependencies
FastAPI requires an ASGI web server like Uvicorn to run, packaged conveniently alongside the framework via standard extras.
- Mechanism: Installing
fastapi[standard]installs the core framework along with production-grade defaults, including Uvicorn for ASGI serving and the FastAPI CLI for developer workflows. Modern package managers likeuvstreamline this setup into isolated project environments. - Under the Hood: FastAPI itself is strictly a web framework layer, delegating raw socket management, HTTP parsing, and ASGI lifecycle handling directly to Uvicorn.
- Best Practice: Always specify the
[standard]extra or explicitly includeuvicornwhen setting up projects to ensure development CLI tooling and ASGI servers are present.
# Initialize a new project and add FastAPI with standard dependencies
uv init fastapi-demo
cd fastapi-demo
uv add "fastapi[standard]"
Key Takeaway: FastAPI relies on an external ASGI server like Uvicorn, provided automatically when installing the standard package extra.
2. Application Instantiation and Route Decorators
The central FastAPI instance serves as the primary registry for application routes, middleware, and lifecycle events.
- Mechanism: Creating
app = FastAPI()initializes the ASGI callable that handles incoming HTTP requests. Method decorators such as@app.get("/")register endpoint handler functions against specific HTTP verbs and URL paths. - Under the Hood: Route decorators bind endpoint functions to an internal routing table, mapping incoming request paths and HTTP methods directly to their corresponding handler logic.
- Syntax Rule: The path string inside the decorator must begin with a forward slash (
/), and the decorated function executes whenever a matching request arrives.
from fastapi import FastAPI
# Instantiate the core application
app = FastAPI()
# Register a root GET endpoint
@app.get("/")
def read_root():
return {"message": "Hello World"}
Key Takeaway: Endpoint handlers are registered by decorating Python functions with HTTP method methods on the
FastAPIapplication instance.
3. Synchronous Handler Execution and Serialization
FastAPI automatically serializes returned Python data structures into JSON and executes synchronous handlers inside an external thread pool.
- Mechanism: Returning a native Python dictionary from an endpoint handler automatically triggers JSON conversion with the correct
application/jsonContent-Type header. - Under the Hood: When an endpoint is defined with standard
definstead ofasync def, FastAPI offloads its execution to a separate external worker thread pool to prevent blocking the main asynchronous event loop. - Execution Flow: The incoming request hits the ASGI server, passes to FastAPI's event loop, is dispatched to a background thread for synchronous execution, and returns serialized JSON back through the loop.
from fastapi import FastAPI
app = FastAPI()
# Standard synchronous function runs in a separate thread pool
@app.get("/status")
def get_status():
# Dictionary is automatically converted to JSON
return {"status": "ok", "code": 200}
Key Takeaway: FastAPI safely executes synchronous
defendpoints in a thread pool without blocking the main event loop while converting dicts to JSON automatically.
4. Development Server Execution via CLI
The FastAPI CLI provides an optimized development runner that manages server lifecycles and hot-reloading.
- Mechanism: Running
fastapi dev main.pyboots Uvicorn in development mode, binding the server to localhost and watching the file system for changes. - Under the Hood: The CLI inspects the target file, locates the
FastAPI()instance, and configures an ASGI worker process with auto-reload capabilities enabled by default. - Best Practice: Use
fastapi devduring development for debugging and hot-reloading, while reserving standard ASGI runners orfastapi runfor production deployments.
# Run the development server with auto-reload via the CLI
fastapi dev main.py
# Alternative execution using uv project runner
uv run fastapi dev main.py
Key Takeaway: The
fastapi devcommand automates Uvicorn configuration and live-reload management for local development.
Topics Covered in FastAPI Basics — Routes, Path & Query Params
- Project Scope and Overview (0:00 - 4:47) — An overview of large-scale architectural features including authentication, databases, and asynchronous programming in FastAPI.
- Environment Setup (4:47 - 6:30) — The environment workspace is initialized and FastAPI standard dependencies are installed.
- Application Instantiation (6:30 - 7:41) — The root application module is created and the main FastAPI instance is instantiated.
- Root Route Definition (7:41 - 8:50) — A synchronous GET endpoint is defined using route decorators to return a dictionary response.
- FastAPI CLI Serving (8:50 - 9:33) — The local development server is started and monitored using the FastAPI CLI runner.
FastAPI Cheat Sheet
-
app = FastAPI()— Creates main FastAPI application instanceapp = FastAPI() -
@app.get("/")— Registers an HTTP GET route handler@app.get("/") def root(): return {"ok": True} -
def handler(): return {}— Returns synchronous response serialized to JSON@app.get("/info") def get_info(): return {"version": "1.0"} -
uv add "fastapi[standard]"— Installs FastAPI, Uvicorn, and CLI toolsuv add "fastapi[standard]" -
fastapi dev main.py— Starts local server with auto-reloadfastapi dev main.py
Comparison Table
| Feature / Aspect | Synchronous Endpoint (def) | Asynchronous Endpoint (async def) |
|---|---|---|
| Execution Context | Separate thread pool | Main async event loop |
| Best Used For | Blocking I/O or standard libraries | Non-blocking async libraries with await |
| Event Loop Impact | Offloaded from event loop | Executes directly inside event loop |
Common Pitfalls
- Mistake: Forgetting to install the standard extras when installing FastAPI. Avoid: Install using fastapi[standard] to include Uvicorn and CLI tools.
- Mistake: Omitting the leading forward slash in route decorator paths. Avoid: Always include the slash such as @app.get(/path).
- Mistake: Manually serializing dictionaries to JSON strings with json.dumps. Avoid: Return raw Python dictionaries directly for automatic serialization.
FAQs
- Do I need to define every endpoint with async def?
No, standard synchronous functions defined with
defare fully supported and executed in a dedicated background thread pool. - Why is installing fastapi[standard] recommended over bare fastapi? The standard extra includes essential ecosystem packages like the Uvicorn ASGI server and the FastAPI CLI required to run applications.
- How does FastAPI convert return values into JSON?
FastAPI automatically handles JSON serialization and sets the appropriate
application/jsonresponse headers whenever a dictionary or list is returned.