Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

FastAPI Basic Routing

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:

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:

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: