Search code examples
litestar

litestar How to combine query parameters with API documentation


from dataclasses import dataclass

from litestar import Litestar, get


@dataclass
class User:
    id: int
    name: str


@get(path="/")
async def index(
        query: User,
) -> dict[str, str]:
    print(query)
    return {}

app = Litestar(route_handlers=[index])

explain: The User class may be used in multiple GET views, and I want a reusable way. This is the current example, but it has its drawbacks. The API documentation does not support querying parameter requests and errors may occur

This is a demo on how to make the API documentation support ID and name query parameters.

from dataclasses import dataclass

from litestar import Litestar, get

from typing import Optional


@dataclass
class User:
    id: int
    name: str


@get(path="/")
async def index(
        # query: User,
        id: Optional[str] = None,
        name: Optional[str] = None
        # more params
) -> dict[str, str]:
    # print(query)
    return {}


app = Litestar(route_handlers=[index])

I know this approach supports displaying in the API documentation, but it is too cumbersome and requires declaring each parameter in the view, and these parameters may be used in multiple views, resulting in low reusability. Is there any way to support it, or is there another better way


Solution

  • I think I've found the best way.

    from dataclasses import dataclass
    from typing import Any
    
    from litestar import Litestar, get
    from litestar.params import Parameter
    from litestar.di import Provide
    
    
    @dataclass
    class User:
        id: int
        name: str
    
    
    async def get_params(
            id: int | None = Parameter(default=None),
            name: str | None = Parameter(default=None),
    ) -> dict[str, Any]:
        res = {}
        if id:
            res["id"] = id
        if name:
            res["name"] = name
        return res
    
    
    @get(path="/", dependencies={"params": Provide(get_params)})
    async def index(params: dict[str, Any]) -> dict[str, Any]:
        print(params)
        return params
    
    
    app = Litestar(route_handlers=[index])
    
    
    
    
    

    Now, good scalability and API documentation support can be maintained.