We all know that in large applications or Web apis, we rarely write multiple routes in a file
Writing all request methods under the same processing file would make our code look illogical
This is not conducive to the expansion of the program, is not conducive to the maintenance of the program in the future
In Flask, we usually use blueprints
So how do you handle that in FastApi?
You can, of course, use APIRouter in FastApi to handle this multiprogram classification
The blueprints in Flask
APIRouter
Assume that the submodules/APP /routers/users.py are dedicated to handling user files
You want to separate user-specific path operations from the rest of the code to make them look clean and straightforward.
You can use this to create the path operation APIRouter for the module.
from fastapi import APIRouter
router = APIRouter()
@router.get("/users/", tags=["users"])
async def read_users():
return [{"username": "Rick"}, {"username": "Morty"}]
@router.get("/users/me", tags=["users"])
async def read_user_me():
return {"username": "fakecurrentuser"}
@router.get("/users/{username}", tags=["users"])
async def read_user(username: str):
return {"username": username}
Copy the code
There is another application module in Web services, Item
You can also register the routes via APIRouter as follows: app/routers/items.py
from fastapi importAPIRouter, Depends, HTTPException from .. dependenciesimport get_token_header
router = APIRouter(
prefix="/items",
tags=["items"],
responses={404: {"description": "Not found"}},
)
@router.get("/")
async def read_items():
return fake_items_db
@router.get("/{item_id}")
async def read_item(item_id: str):
if item_id not in fake_items_db:
raise HTTPException(status_code=404, detail="Item not found")
return {"name": fake_items_db[item_id]["name"]."item_id": item_id}
Copy the code
This separates the two function modules item and User
In the future, we want to update or expand the functions of user module, which will not affect Item!
This is where APIRouter is most basic and powerful. What else?
B: of course!
Custom tags, responses
If you are careful, you will notice that there are several parameters passed when instantiating the router in item.py
Let’s see what they mean!
The prefix parameter indicates the route prefix
Tags will be applied to the content of a particular path operation
Responses refer to the response content specific to the path, such as the return information specified above for 404
@router.put(
"/{item_id}",
tags=["custom"],
responses={403: {"description": "Operation forbidden"}},
)
async def update_item(item_id: str):
ifitem_id ! ="plumbus":
raise HTTPException(
status_code=403, detail="You can only update the item: plumbus"
)
return {"item_id": item_id, "name": "The great Plumbus"}
Copy the code
It also supports extension or rewriting to add additional functionality
But we can still add more tags that will apply to a particular path operation,
Registered APIRouter
The final step is to register our APIRouter with the core object
Import FastApi as we created the main file earlier, along with the declared APIRouter instance
The main py files
from fastapi import Depends, FastAPI
from .dependencies import get_query_token, get_token_header
from .internal import admin
from .routers import items, users
app = FastAPI(dependencies=[Depends(get_query_token)])
app.include_router(users.router)
app.include_router(items.router)
app.include_router(
admin.router,
prefix="/admin",
tags=["admin"],
dependencies=[Depends(get_token_header)],
responses={418: {"description": "I'm a teapot"}},
)
@app.get("/")
async def root():
return {"message": "Hello Bigger Applications!"}
Copy the code
The include_router() function is the registration function.
That’s it. Use the app to start the service
The startup command is as follows:
uvicorn main:app --host=0.0. 0. 0 --port=8800
Copy the code
Finally, verify that you open the interface document and view the interface
Recommended reading
Fully embrace FastApi – gracefully return exception errors
Fully embrace FastApi – Three parameters and validation