Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Comments

✨ Add support for function return type annotations to declare theresponse_model#1436

Merged
tiangolo merged 9 commits intofastapi:masterfrom
uriyyo:master
Jan 7, 2023
Merged

✨ Add support for function return type annotations to declare theresponse_model#1436
tiangolo merged 9 commits intofastapi:masterfrom
uriyyo:master

Conversation

@uriyyo
Copy link
Contributor

@uriyyouriyyo commentedMay 20, 2020
edited
Loading

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 defaultresponse_model for an endpoint.

For instance, we have a simple application:

frompydanticimportBaseModelfromfastapiimportFastAPIclassModel(BaseModel):name:strapp=FastAPI()@app.get("/",response_model=Model)defendpoint():returnModel(name="Yurii")

So with this PR, it can be rewritten to:

frompydanticimportBaseModelfromfastapiimportFastAPIclassModel(BaseModel):name:strapp=FastAPI()@app.get("/")defendpoint()->Model:returnModel(name="Yurii")

In case whenresponse_model argument set and return type annotation present, thenresponse_model will be used.

TezRomacH, mzalevski, AntonOvsyannikov, johnthagen, Butch78, timoniq, MarshalX, ioalloc, andrew222651, alencardotpy, and Flashvita reacted with thumbs up emojiTezRomacH, mzalevski, johnthagen, aminalaee, dolfinus, rn4n, mgu, bkis, razvanavram, tjpalanca, and 2 more reacted with heart emoji
@codecov
Copy link

codecovbot commentedMay 20, 2020
edited
Loading

Codecov Report

Base:100.00% // Head:100.00% // No change to project coverage 👍

Coverage data is based on head(685f402) compared to base(cf73051).
Patch coverage: 100.00% of modified lines in pull request are covered.

❗ Current head685f402 differs from pull request most recent headfe9c95c. Consider uploading reports for the commitfe9c95c to get more accurate results

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
Impacted FilesCoverage Δ
fastapi/applications.py100.00% <ø> (ø)
tests/test_reponse_set_reponse_code_empty.py100.00% <ø> (ø)
fastapi/dependencies/utils.py100.00% <100.00%> (ø)
fastapi/routing.py100.00% <100.00%> (ø)
tests/test_response_model_as_return_annotation.py100.00% <100.00%> (ø)
tests/test_datastructures.py100.00% <0.00%> (ø)

Help us with your feedback. Take ten seconds to tell ushow you rate us. Have a feature suggestion?Share it here.

☔ View full report at Codecov.
📢 Do you have feedback about the report comment?Let us know in this issue.

@phy25
Copy link

Have you searched through the issue tracker before submitting this? I remembered there is a reason that this is not implemented.

@uriyyo
Copy link
ContributorAuthor

It was discussed at#101

Use can use a return type annotation asresponse_model, but in a case when it leads to some type errors it will be replaced withresponse_model keyword argument at endpoint decorator.

@phy25 What do you think about such option?

@ghost
Copy link

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.

@uriyyo
Copy link
ContributorAuthor

@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😔

AntonOvsyannikov, Tradunsky, and emilv-barium reacted with confused emoji

@github-actions
Copy link
Contributor

📝 Docs preview for commit1d6161c at:https://63567e2f28003420c0eae5ff--fastapi.netlify.app

@uriyyo
Copy link
ContributorAuthor

@tiangolo Should I also update docs?

@github-actions
Copy link
Contributor

📝 Docs preview for commit8c4cf25 at:https://6356805d246dd92bb09291ac--fastapi.netlify.app

@github-actions
Copy link
Contributor

📝 Docs preview for commit685f402 at:https://6356824de6485c2a69a44560--fastapi.netlify.app

@cj
Copy link

cj commentedOct 27, 2022

I just ran into this myself, can't wait for this to get merged in! Great job@uriyyo 😄

@github-actions
Copy link
Contributor

📝 Docs preview for commit01640c4 at:https://6366a6668c085d1c80d8798d--fastapi.netlify.app

Copy link
Contributor

@yezz123yezz123 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

LGTM 🚀

uriyyo reacted with heart emojiuriyyo reacted with rocket emoji
@uriyyo
Copy link
ContributorAuthor

@tiangolo I would love to use this feature in my project. Is there any chance you can include it in the next release?

Comment on lines 27 to 29
@app.get("/valid3", response_model=ModelTwo)
def valid3() -> ModelOne:
return ModelTwo(surname="Test")
Copy link
ContributorAuthor

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.

iudeen reacted with thumbs up emoji
@github-actions
Copy link
Contributor

📝 Docs preview for commit3b3d039 at:https://639cc85ab5df5c0d9667060d--fastapi.netlify.app

@tiangolotiangolo changed the title🎉 Use function return type annotation as response_model✨ Add support for function return type annotations to declare theresponse_modelJan 7, 2023
@tiangolo
Copy link
Member

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 andresponse_model, different types of declarations, data filtering, etc.

And I updated the docs to include all the information about this, how to use it, how and when to useresponse_model instead of the return type annotation, etc. 🤓

This will be available in FastAPI0.89.0 released (most probably) in the next few hours. 🚀

sector119 reacted with thumbs up emojiuriyyo, benjavicente, benyaming, and MarshalX reacted with hooray emoji

@Tishka17
Copy link

Tishka17 commentedJan 9, 2023
edited
Loading

I have created simple route:

classResp(BaseModel):a:Optional[str]=Field(...,nullable=True)def__init__(self,*args,**kwargs):super().__init__(*args,**kwargs)print("init")@app.get("/")asyncdefroot()->Resp:res=Resp(a=None)print("Res created",res)returnres

And this log is not what I really expect to see:

INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)initRes created a=Noneinit

Probably it's ok forresponse_model case, but if I return model directly I do not expect it to be recreated by some reason internally.

Moreover, by that reason code is not working at all if I declare model this way

classResp(BaseModel):a:Optional[str]=Field(...,nullable=True)classConfig:fields= {'a': {'exclude':True}}
kiriharu, ReznikovRoman, strpc, hainamantik, MrBanja, nkhitrov, SamWarden, and Alkalit reacted with thumbs up emojiadaamz reacted with thumbs down emoji

@iudeen
Copy link
Contributor

iudeen commentedJan 10, 2023
edited
Loading

This seems to break in many cases. A lot of issues being reported on this.

MindTooth, TheLovinator1, hainamantik, and mveleci reacted with confused emoji

JonasKs pushed a commit to JonasKs/fastapi that referenced this pull requestJan 12, 2023
…sponse_model` (fastapi#1436)Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
@peterbe
Copy link

Pardon my ignorance but what's thebenefit of this?

Before:

@app.get("/",response_class=PlainTextResponse)asyncdefroot():return"bla bla"

Swagger can infer that the response is going to betext/plain. I only have to specify what type of response it isonce.

After

@app.get("/")asyncdefroot()->PlainTextResponse:returnPlainTextResponse("bla bla")

Now Swagger defaults to thinking it'sapplication/json and I have to typePlainTextResponsetwice.

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.

@tiangolo
Copy link
Member

@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 apassword field), if the class is not cloned and the data is created again, it would pass Pydantic validation by default, just for being a subclass. That's why it has to be recreated. It will probably change and improve in Pydantic v2. You can read more about why is that here:https://fastapi.tiangolo.com/tutorial/response-model/#return-type-and-data-filtering

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 toresponse_model, not toresponse_class. And in your use case, keeping the code you had would probably be better (that's what I would do). If you have more questions, please create a new GitHub Discussion.

iudeen reacted with thumbs up emoji

@iudeen
Copy link
Contributor

@tiangolo the issues were resolved in 0.89.1

baoliay2008 added a commit to baoliay2008/lccn_predictor that referenced this pull requestFeb 16, 2023
given that FastAPI `response_model` now support return type annotationsee more details at:1.fastapi/fastapi#1012.fastapi/fastapi#1436
axel584 pushed a commit to axel584/fastapi that referenced this pull requestMar 5, 2023
…sponse_model` (fastapi#1436)Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
mahenzon pushed a commit to mahenzon/fastapi that referenced this pull requestMar 11, 2023
…sponse_model` (fastapi#1436)Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment

Reviewers

1 more reviewer

@yezz123yezz123yezz123 approved these changes

Reviewers whose approvals may not affect merge requirements

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

8 participants

@uriyyo@phy25@cj@tiangolo@Tishka17@iudeen@peterbe@yezz123

[8]ページ先頭

©2009-2026 Movatter.jp