question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Path Parameters in Advanced Dependency

See original GitHub issue

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

@router.get("/{project_id}/team}", response_model=List[schemas.team])
def get_team(
    project_id: UUID,
    is_authorized: bool = Depends(deps.AuthorizationCheck(project_id=project_id))
) -> Any:
# Get the Team through crud operations
 pass

class AuthorizationCheck:
    def __init__(self, project_id) -> None:
        self.project_id = project_id

    def __call__(self, air_data_session: Session = Depends(session),
    auth_id: str = Depends(get_firebase_auth_id)) -> bool:
        if not crud.user.is_user_part_of_module_and_project(
        session,
        project_id=str(self.project_id),
        firebase_auth_id=auth_id,
        ):
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="User not part of project",
            )
        return True

Description

I’m implementing a dependency that checks if the user is allowed to access a certain project or not. If they are not allowed, the dependency will raise a 401 exception otherwise, it will return true.

The project_id is provided through the path parameter and several APIs will be using this dependency. Here’s an example of one of the API that is supposed to fetch the team working on a specific project api/v2/{project_id}/team

As an attempt, I created a dependency class called AuthorizationCheck that takes as input project_id. However, project_id is not being recognized from the path parameter.

I’ve read the Advanced Dependency tutorial provided in the documentation but it doesn’t mention a way to use the path parameters in it. Is this doable?

Operating System

Windows

Operating System Details

No response

FastAPI Version

0.54.2

Python Version

3.9.6

Additional Context

No response

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
gitnarqtcommented, Sep 15, 2021

@frankie567 Merci beaucoup!! It’s exactly what I wanted 🎉

1reaction
frankie567commented, Sep 15, 2021

The problem here is that you are using a value that will be available at runtime, project_id, at “compile time”:

Capture d’écran 2021-09-15 à 07 49 52

Actually, all you have to do is to change your __call__ method so that it injects project_id. That’s the beauty of FastAPI: dependencies are 100% recursive:

@router.get("/{project_id}/team}", response_model=List[schemas.team])
def get_team(
    project_id: UUID,
    is_authorized: bool = Depends(deps.AuthorizationCheck())
) -> Any:
# Get the Team through crud operations
 pass


class AuthorizationCheck:
    def __call__(self, project_id: UUID, air_data_session: Session = Depends(session), auth_id: str = Depends(get_firebase_auth_id)) -> bool:
        if not crud.user.is_user_part_of_module_and_project(
            session,
            project_id=str(project_id),
            firebase_auth_id=auth_id,
        ):
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="User not part of project",
            )
        return True

If you don’t need to manage other parameters, a class may be unnecessary, you can do it with a simple function:

@router.get("/{project_id}/team}", response_model=List[schemas.team])
def get_team(
    project_id: UUID,
    is_authorized: bool = Depends(deps.is_authorized)
) -> Any:
# Get the Team through crud operations
 pass


def is_authorized(self, project_id: UUID, air_data_session: Session = Depends(session), auth_id: str = Depends(get_firebase_auth_id)) -> bool:
    if not crud.user.is_user_part_of_module_and_project(
        session,
        project_id=str(project_id),
        firebase_auth_id=auth_id,
    ):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="User not part of project",
        )
    return True

Even better, if you don’t need the return value, you can just inject this dependency in the route decorator:

@router.get(
    "/{project_id}/team}",
    response_model=List[schemas.team],
    dependencies=[Depends(deps.is_authorized)],
)
def get_team(project_id: UUID) -> Any:
# Get the Team through crud operations
    pass

You can reuse this dependency at will. The only thing you have to take care of is to put the project_id parameter in your path pattern. Otherwise, FastAPI will automatically look for it in query parameters.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Advanced Dependencies - FastAPI
Parameterized dependencies​​ All the dependencies we have seen are a fixed function or class. But there could be cases where you want to...
Read more >
Is it possible to pass Path arguments into FastAPI dependency ...
The parameters will simply be passed on through to the dependency function if they are present there. You can also use things like...
Read more >
Advanced Features - Izumi Project
Advanced Features · Dependency Pruning · Circular Dependencies Support · Automatic Resolution with generated proxies · Manual Resolution with by-name parameters.
Read more >
dependency-check-cli – Command Line Arguments
Short, Argument Name, Parameter, Description, Requirement. --project, <name>, The name of the project being scanned. Optional. -s, --scan, <path>, The path ...
Read more >
Task definition parameters - Amazon Elastic Container Service
You can use these parameters in a JSON file to configure your task definition. ... Standard container definition parameters; Advanced container definition ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found