Skip to content

Let's write some code

Now we take the starlette example from usages and specify it to use Path now.

Handle request specific fields

First of all, Starlette pass to a handler the only one argument - request To use them with FastDepends we need unwrap request to kwargs.

1
2
3
4
5
6
7
8
9
from fast_depends import inject


def wrap_starlette(func):
    async def wrapper(request):
        return await inject(func)(
            request=request
        )
    return wrapper

Also, we wraps an original handler to fast_depends.inject too at 3 line

Declare Custom Field

Next step, define Path custom field

1
2
3
4
5
6
7
8
9
from fast_depends.library import CustomField


class Path(CustomField):
    def use(self, /, *, request, **kwargs):
        return {
            **super().use(request=request, **kwargs),
            self.param_name: request.path_params.get(self.param_name)
        }

Usage with the Starlette

And use it at our Starlette application:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.routing import Route


async def hello(user: str = Path()):
    return PlainTextResponse(f"Hello, {user}!")

app = Starlette(debug=True, routes=[
    Route("/{user}", hello)
])

Depends is working as expected too

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
def get_user(user_id: int = Path()):
    return f"user {user_id}"

@wrap_starlette
async def hello(user: str = Depends(get_user)):
    return PlainTextResponse(f"Hello, {user}!")

app = Starlette(debug=True, routes=[
    Route("/{user_id}", hello)
])

As an Annotated does

1
2
3
@wrap_starlette
async def get_user(user: Annotated[int, Path()]):
    return PlainTextResponse(f"Hello, {user}!")

Full example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from fast_depends import inject
from fast_depends.library import CustomField

from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.routing import Route

class Path(CustomField):
    def use(self, /, *, request, **kwargs):
        return {
            **super().use(request=request, **kwargs),
            self.param_name: request.path_params.get(self.param_name)
        }

def wrap_starlette(func):
    async def wrapper(request):
        return await inject(func)(
            request=request
        )
    return wrapper

@wrap_starlette
async def hello(user: str = Path()):
    return PlainTextResponse(f"Hello, {user}!")

app = Starlette(debug=True, routes=[
    Route("/{user}", hello)
])

The code above works "as it". You can copy it and declare other Header, Cookie, Query fields by yourself. Just try, it's fun!