litestar icon indicating copy to clipboard operation
litestar copied to clipboard

Enhancement: Allow body parameter to have an arbitrary name.

Open Liraim opened this issue 1 year ago • 6 comments

Summary

When you write a handler it is more convenient to have a body parameter named as entity you work with.

Basic Example

Before you required to write live:

@post
async def post_todo_item(data: TodoItem) -> None:
    ...

After, you CAN to annotate it with Body and have an arbitrary name.

@post()
async def post_todo_item(todo_item: Annotated[TodoItem, Body()]) -> None:
    ...

Drawbacks and Impact

  • More complicated handler logic to implement
  • New name can overlap with dependency name and break dependencies resolution.

Unresolved questions

No response


[!NOTE]
While we are open for sponsoring on GitHub Sponsors and OpenCollective, we also utilize Polar.sh to engage in pledge-based sponsorship.

Check out all issues funded or available for funding on our Polar.sh dashboard

  • If you would like to see an issue prioritized, make a pledge towards it!
  • We receive the pledge once the issue is completed & verified
  • This, along with engagement in the community, helps us know which features are a priority to our users.
Fund with Polar

Liraim avatar Jan 31 '24 20:01 Liraim

I've guessing this should also apply to other reserved parameters such as state and query?

cofin avatar Feb 23 '24 15:02 cofin

Yeah. I think we should do this for all injected things.

E.g.

async def handler(
  param: Query[str], 
  request_body: Body[list[str]], 
  header: Header[int],
):
 ...

IMO this belongs to the DI redesign and is something I'd definitely want to address as part of that.

provinzkraut avatar Feb 23 '24 16:02 provinzkraut

Agree - it would be great to be more flexible in this respect!

peterschutt avatar Feb 24 '24 01:02 peterschutt

Just want to highlight how nice it would be to split Parameter into more specific types, ie. Body, Query, Header, Cookie, Path(?). Current mechanism of having to thing: Annotated[int, Parameter(header="thing")] vs thing: Annotated[int, Header()]) feels a bit bloated.

Also discussed in https://github.com/litestar-org/litestar/pull/3223#issuecomment-2020196878 & https://github.com/litestar-org/litestar/pull/3223#issuecomment-2021747321. FYI.

tuukkamustonen avatar Apr 04 '24 06:04 tuukkamustonen

@tuukkamustonen That's already in the current proposal, see https://github.com/litestar-org/litestar/issues/3053#issuecomment-1961605988

provinzkraut avatar Apr 05 '24 15:04 provinzkraut

Yeah, just wanted to highlight how nice it would be to have those types. The topic of the ticket is "allow ... parameter to have an arbitrary name" (and not add Query, Body, etc convenience wrappers for shorter field name syntax...) after all.

But yeah, good that you have it scoped like that 👍🏻

tuukkamustonen avatar Apr 05 '24 16:04 tuukkamustonen