astral-sh / ruff

An extremely fast Python linter and code formatter, written in Rust.
https://docs.astral.sh/ruff
MIT License
32.59k stars 1.09k forks source link

New rule: fast-api-unused-path-parameter #12632

Open Matthieu-LAURENT39 opened 3 months ago

Matthieu-LAURENT39 commented 3 months ago

Keywords: fastapi, path parameters

Hello, i've been using ruff for a while and i'm really loving it. I saw that recently some FastAPI rules have been added, and i would like to suggest a new one, fast-api-unused-path-parameter. It's pretty simple, it verifies that when defining a route that takes in path parameters, the function has matching arguments.

For example, the following code would trigger the rule, as we define a path parameter named "thing_id", but the function doesn't have an argument named "thing_id":

from fastapi import FastAPI

app = FastAPI()

@app.get("/things/{thing_id}")
async def read_thing(id: int, query: str = None):
    return {"thing_id": id, "query": query}

Also of note is that it should ignore any characters after a : in the path parameter name, so this wouldn't trigger the rule:

...

@app.get("/place/{my_path:path}")
def read_path(my_path):
    ...

If this rule is a good fit for ruff, i'd love to make a PR to implement it!

mattmess1221 commented 2 months ago

How should routes with path parameters consumed in dependencies behave? Example:

def foo(bar: Annotated[str, Path()]):
  print(bar)

@app.get("/foo/{bar}", dependencies=[Depends(foo)])
async def do_foo():
    pass
MichaReiser commented 2 months ago

Thanks for proposing a new rule.

Can you help me understand what's still missing from https://github.com/astral-sh/ruff/pull/12638 that shipped as preview rule in 0.6.1?