I created 'user' and 'shop' route respectively. So there's an api where the 'user' account is accessible, and there's an api where the 'shop' account is accessible.
# user_route.py...
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/user/login")
router = APIRouter(
prefix="/api/user",
)
# shop_route.py...
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/shop/login")
router = APIRouter(
prefix="/api/shop",
)
However, only one type of account can be logged in in swagger ui. So I thought about making swagger ui for 'user' and 'shop' router, respectively, but only 'app1' works
# main.py...
app1 = FastAPI(
title="user Auth",
docs_url="/docs-user"
)
app2 = FastAPI(
title="user Auth",
docs_url="/docs-shop"
)
...
app1.include_router(user_router.router)
app2.include_router(shop_router.router)
Is there a way to use both types of accounts in Swagger ui?
If I get you rigth, you try to achieve this behaviour:
You can use this code to achive this:
from typing import Annotated
from fastapi import APIRouter, Depends, FastAPI
from fastapi.security import OAuth2PasswordBearer
application = FastAPI(
title="TEST APP"
)
class ShopOAuth2PasswordBearer(OAuth2PasswordBearer):
pass
class UserOAuth2PasswordBearer(OAuth2PasswordBearer):
pass
# user_route.py...
oauth2_scheme_user = ShopOAuth2PasswordBearer(tokenUrl="/api/user/login")
router_user = APIRouter(
prefix="/api/user",
)
# shop_route.py...
oauth2_scheme_shop = UserOAuth2PasswordBearer(tokenUrl="/api/shop/login")
router_shop = APIRouter(
prefix="/api/shop",
)
@router_user.post("/login")
async def login_user(token: Annotated[str, Depends(oauth2_scheme_user)]):
return {"token": "user_token"}
@router_shop.post("/login")
async def login_shop(token: Annotated[str, Depends(oauth2_scheme_shop)]):
return {"token": "shop_token"}
application.include_router(router_user)
application.include_router(router_shop)