jonra1993 / fastapi-alembic-sqlmodel-async

This is a project template which uses FastAPI, Pydantic 2.0, Alembic and async SQLModel as ORM. It shows a complete async CRUD using authentication and role base access control.
MIT License
878 stars 142 forks source link

Unable to `GET` `hero` by its `name`. #47

Closed jymchng closed 1 year ago

jymchng commented 1 year ago

Hi, thanks for creating such a powerful and useful template!

I am attempting to retrieve a hero by its name, e.g. 'spiderman'.

I have created a record under the Hero table with name='spiderman'.

The code for the API to retrieve hero via name is:

@router.get("/{hero_name}")
async def get_hero_by_name(
    hero_name: str
) -> IGetResponseBase[IHeroReadWithTeam]:
    """
    Gets a hero by its `name`: str.
    """
    hero = await crud.hero.get_heroe_by_name(name=hero_name)
    if not hero:
        raise NameNotFoundException(Hero, name=hero_name)
    return create_response(data=hero)

Using the Swagger UI and upon execution, I get the following: image

The codes for the function get_heroe_by_name is as follows:

class CRUDHero(CRUDBase[Hero, IHeroCreate, IHeroUpdate]):
    async def get_heroe_by_name(
        self, *, name: str, db_session: Optional[AsyncSession] = None
    ) -> Hero:
        db_session = db_session or db.session
        heroe = await db_session.execute(select(Hero).where(Hero.name == name))
        return heroe.scalar_one_or_none()

Basically, I have took your template and attempted to write an API to get a hero by its name but failed to do so.

Thank you.

jonra1993 commented 1 year ago

Hello, @jymchng thanks for reporting this issue I created an API that is able to get a hero by its name. Check it here https://github.com/jonra1993/fastapi-alembic-sqlmodel-async/commit/64514006db09c992df9d09279f2ebb7319c5a8b5

The issue was caused because the get route for id and the name were the same @router.get("/{hero_id}") and @router.get("/{hero_name}") so it thought that name was an id. This is something tricky of fastapi and the solution was to make routes different like this

image

Please check it and let me know our feedback.