-
-
Notifications
You must be signed in to change notification settings - Fork 6.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
✨ Add support for function return type annotations to declare the response_model
#1436
Conversation
Codecov ReportBase: 100.00% // Head: 100.00% // No change to project coverage 👍
Additional details and impacted files@@ Coverage Diff @@
## master #1436 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 540 541 +1
Lines 13969 13989 +20
=========================================
+ Hits 13969 13989 +20
Help us with your feedback. Take ten seconds to tell us how you rate us. Have a feature suggestion? Share it here. ☔ View full report at Codecov. |
Have you searched through the issue tracker before submitting this? I remembered there is a reason that this is not implemented. |
This was also discussed in #875, I ended up implementing the same in my codebase basically by creating a subclass of the APIRouter that I use to create all my routers. |
@juhovh-aiven Thanks for the comment. I will do the same as you did. I will close this PR. But I think that won't be the last PR regarding this feature😔 |
# Conflicts: # fastapi/routing.py
📝 Docs preview for commit 1d6161c at: https://63567e2f28003420c0eae5ff--fastapi.netlify.app |
@tiangolo Should I also update docs? |
📝 Docs preview for commit 8c4cf25 at: https://6356805d246dd92bb09291ac--fastapi.netlify.app |
📝 Docs preview for commit 685f402 at: https://6356824de6485c2a69a44560--fastapi.netlify.app |
I just ran into this myself, can't wait for this to get merged in! Great job @uriyyo 😄 |
📝 Docs preview for commit 01640c4 at: https://6366a6668c085d1c80d8798d--fastapi.netlify.app |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM 🚀
@tiangolo I would love to use this feature in my project. Is there any chance you can include it in the next release? |
@app.get("/valid3", response_model=ModelTwo) | ||
def valid3() -> ModelOne: | ||
return ModelTwo(surname="Test") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@iudeen They actually different. On lines 22-44 there is no return type annotation but 27-29 has it.
📝 Docs preview for commit 3b3d039 at: https://639cc85ab5df5c0d9667060d--fastapi.netlify.app |
response_model
Thanks for the contribution @uriyyo! 🚀 🍰 And thanks for the discussion, everyone. ☕ 🍪 I added a couple of dozen tests to cover all the corner cases, interactions between return types and And I updated the docs to include all the information about this, how to use it, how and when to use This will be available in FastAPI |
I have created simple route: class Resp(BaseModel):
a: Optional[str] = Field(..., nullable=True)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
print("init")
@app.get("/")
async def root() -> Resp:
res = Resp(a=None)
print("Res created", res)
return res And this log is not what I really expect to see:
Probably it's ok for Moreover, by that reason code is not working at all if I declare model this way class Resp(BaseModel):
a: Optional[str] = Field(..., nullable=True)
class Config:
fields = {'a': {'exclude': True}} |
This seems to break in many cases. A lot of issues being reported on this. |
…sponse_model` (fastapi#1436) Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
Pardon my ignorance but what's the benefit of this? Before: @app.get("/", response_class=PlainTextResponse)
async def root():
return "bla bla" Swagger can infer that the response is going to be After @app.get("/")
async def root() -> PlainTextResponse:
return PlainTextResponse("bla bla") Now Swagger defaults to thinking it's Yes, I'm a still a FastAPI newbie but I use it in a production project and was intrigued to see if this is something I should change to. |
@Tishka17 the model is cloned to ensure that data is filtered, otherwise, if you return an instance of a subclass of that model (e.g. a subclass that includes a But if you have more follow up questions/ideas, please create a new GitHub Discussion question. @iudeen could you point me to those issues reported related to this? Maybe in Discord? (because I'll lose it in the GitHub notifications). I wanna check if there's something specific flawed about this approach or just several corner cases. As FastAPI is used by thousands and thousands of developers, any change will probably break some corner cases. But if the change is an improvement for everyone then it should be okay (that's also why I release so granularly, so many releases, so that people can pin and very gradually upgrade if there are changes that become problematic for them). But if there's something wrong with the approach or the implementation, or if there's one of those "corner cases" that is very, very common (not so "corner"), then it could deserve its own fix/workaround. @peterbe This is related to |
@tiangolo the issues were resolved in 0.89.1 |
given that FastAPI `response_model` now support return type annotation see more details at: 1. fastapi/fastapi#101 2. fastapi/fastapi#1436
…sponse_model` (fastapi#1436) Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
…sponse_model` (fastapi#1436) Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
I love the idea of OpenAPI auto-generated schema and the FastAPI at all 😄
This is a feature request.
When I was working with FastAPI I thought that it will be a great idea to use function return type annotation as default
response_model
for an endpoint.For instance, we have a simple application:
So with this PR, it can be rewritten to:
In case when
response_model
argument set and return type annotation present, thenresponse_model
will be used.