FastAPI Basic Routing

In FastAPI, basic routing is 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 FastAPI instance and root path routing:

Example

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

Code explanation:

  • FastAPI(): Create a FastAPI application instance.
  • @app.get("/"): Use@app.getThe decorator creates a route that handles the root path.
  • def read_root(): The route handler function returns a dictionary containing {"Hello": "World"}.

Path Parameter

Set route 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, where{item_id}is the path parameter, corresponding to the function parameteritem_id。
  • def read_item(item_id: int, q: str = None): The route handler function accepts an integer path parameteritem_idand an optional string query parameterq。

In route operations, query parameters can be declared using function parameters. For example,q: str = NoneRepresentsqis an optional string query parameter with a default value ofNone。

Start the application and test routes

Start the application using Uvicorn:

uvicorn main:app --reload

Visithttp://127.0.0.1:8000View the response of the root path:

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

The interactive API documentation automatically generated by FastAPI will include defined route information, path parameters, query parameters, etc. Visit the documentation URL.http://127.0.0.1:8000/docsView the detailed documentation and test interface:

other extensions