FastAPI Basic Routing
In FastAPI, basic routing is the key to defining API endpoints.
Each route maps to a function in the application that handles a specific HTTP request and returns the corresponding response.

Root path route
Create a FastAPI instance and a root path route:
Example
from
fastapi
import
FastAPI
app
=
FastAPI
(
)
@
app.
get
(
"/"
)
def
read_root
(
)
:
return
{
"Hello"
:
"World"
}
Code explanation:
FastAPI(): creates a FastAPI application instance.@app.get("/"): When using@app.getdecorator creates a route that handles the root path.def read_root(): the route handler function, which returns a dictionary containing {"Hello": "World"}.
Path parameters
Set the route's parameters:
Example
from
fastapi
import
FastAPI
app
=
FastAPI
(
)
@
app.
get
(
"/"
)
def
read_root
(
)
:
return
{
"Hello"
:
"World"
}
@
app.
get
(
"/items/{item_id}"
)
def
read_item
(
item_id:
int
,
q:
str
=
None
)
:
return
{
"item_id"
: item_id
,
"q"
: q
}
Code explanation:
@app.get("/items/{item_id}"): defines a route path, in which{item_id}is a path parameter, corresponding to the function parameteritem_id。def read_item(item_id: int, q: str = None): the route handler accepts a path parameter of type integeritem_idand an optional query parameter of type stringq。
In a route operation, you can declare query parameters using function parameters. For example, q: str = None means q is an optional string query parameter with a default value of None。
Start the application and test the routes
Use Uvicorn to start the application:
uvicorn main:app --reload
Access the http://127.0.0.1:8000 View the response of the root path:

Visit http://127.0.0.1:8000/items/42?q=runoob to see the response with path and query parameters:

FastAPI's automatically generated interactive API documentation will include defined route information, path parameters, query parameters, and more. Visit the documentation URL http://127.0.0.1:8000/docs to view detailed documentation and the testing interface:
