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

Additional Responses#97

Merged
tiangolo merged 10 commits intofastapi:masterfrom
barsi:master
Apr 5, 2019
Merged

Additional Responses#97
tiangolo merged 10 commits intofastapi:masterfrom
barsi:master

Conversation

@barsi
Copy link
Contributor

Additional Responses Support

Summary

allows additional responses to be defined beside the default one

Example

# -*- coding: utf-8 -*-importuuid,datetimeasdtimportfastapifromstarletteimportresponsesimportpydanticasdanticfromfastapi.openapiimportmodels,constantsapp=fastapi.FastAPI(debug=True)classResponse400(dantic.BaseModel):'''HTTP 4xx responses schema'''summary:strdescription:strref_code:str# functional error refclassPoint(dantic.BaseModel):id:dantic.UUID1latitude:floatlongitude:floatpinned:boolpinned_at:dt.datetimeresponse_403=models.AdditionalResponse(status_code=403,description='Forbidden',models=[Response400,    ],)response_500=models.AdditionalResponse(status_code=500,description='Server Error',content_type='text/plain',)@app.post('/pin-my-location',summary='Pin My Location',description='Pin my location ...',response_model=Point,additional_responses=[response_403,response_500,    ])asyncdefpin_my_location():ifdt.datetime.utcnow().strftime('%Y-%m')!='2019-03':returnresponses.UJSONResponse({'summary':'Access Denied!','detail':'No Access allowed after Mar 2019.','ref_code':'TNQ00723',        },status_code=403,)returnPoint(id=uuid.uuid1(7,3),latitude=0.0,longitude=0.0,pinned=True,pinned_at=dt.datetime.utcnow(),    )

Result

Screen Shot 2019-03-22 at 10 44 42 PM

you can also define additional responses onapp.include_router so it can save you from repeating the definition of common response types (e.g.HTTP 500)

Limitations

This pull request only implements the injection of
additional responses definitions into OpenAPI schema
to be appeared in swagger or other OpenAPI 3 compatible
clients (e.g. postman), here are some of the limitations:

  • No validation on additional responses if they were returned.
  • No support for multiple media types in response content definition.
  • Extra fields on response not implemented yet (e.g.headers &examples).

mostaphaRoudsari reacted with thumbs up emoji
@codecov
Copy link

codecovbot commentedMar 22, 2019

Codecov Report

Merging#97 intomaster willdecrease coverage by0.79%.
The diff coverage is83.57%.

Impacted file tree graph

@@           Coverage Diff            @@##           master     #97     +/-   ##========================================- Coverage     100%   99.2%   -0.8%========================================  Files         109     110      +1       Lines        2740    2877    +137     ========================================+ Hits         2740    2854    +114- Misses          0      23     +23
Impacted FilesCoverage Δ
fastapi/openapi/utils.py100% <100%> (ø)⬆️
tests/test_additional_responses.py100% <100%> (ø)
fastapi/openapi/models.py100% <100%> (ø)⬆️
fastapi/applications.py100% <100%> (ø)⬆️
fastapi/utils.py100% <100%> (ø)⬆️
fastapi/routing.py86.85% <50%> (-13.15%)⬇️

Continue to review full report at Codecov.

Legend -Click here to learn more
Δ = absolute <relative> (impact),ø = not affected,? = missing data
Powered byCodecov. Last update9778542...95679ca. Read thecomment docs.

@codecov
Copy link

codecovbot commentedMar 22, 2019
edited
Loading

Codecov Report

Merging#97 intomaster willnot change coverage.
The diff coverage is100%.

Impacted file tree graph

@@          Coverage Diff           @@##           master    #97    +/-   ##======================================  Coverage     100%   100%            ======================================  Files         109    146    +37       Lines        2740   3590   +850     ======================================+ Hits         2740   3590   +850
Impacted FilesCoverage Δ
fastapi/openapi/utils.py100% <100%> (ø)⬆️
fastapi/routing.py100% <100%> (ø)⬆️
...rial/test_additional_responses/test_tutorial004.py100% <100%> (ø)
docs/src/bigger_applications/app/routers/items.py100% <100%> (ø)⬆️
docs/src/additional_responses/tutorial002.py100% <100%> (ø)
...est_tutorial/test_bigger_applications/test_main.py100% <100%> (ø)⬆️
docs/src/additional_responses/tutorial003.py100% <100%> (ø)
...rial/test_additional_responses/test_tutorial003.py100% <100%> (ø)
...rial/test_additional_responses/test_tutorial001.py100% <100%> (ø)
...rial/test_additional_responses/test_tutorial002.py100% <100%> (ø)
... and52 more

Continue to review full report at Codecov.

Legend -Click here to learn more
Δ = absolute <relative> (impact),ø = not affected,? = missing data
Powered byCodecov. Last update9778542...2bd7759. Read thecomment docs.

@tiangolo
Copy link
Member

Thanks! I'll review it soon.

@tiangolotiangolo merged commitad47130 intofastapi:masterApr 5, 2019
@tiangolo
Copy link
Member

Thanks@barsi, I see you put quite some effort into this, thanks for that! 👏 🍰


I took it further and updated/refactored it all to make it simpler for developers to use while extending the capabilities.

For example, it's possible to add more info to an existingresponse_model, likeexample. And they get the data from the additional response and the model combined.

I also included docs, tests for the code in the docs, etc.

With this you can now add aresponses parameter with adict, e.g.:

fromfastapiimportFastAPIfrompydanticimportBaseModelfromstarlette.responsesimportJSONResponseclassItem(BaseModel):id:strvalue:strclassMessage(BaseModel):message:strapp=FastAPI()@app.get("/items/{item_id}",response_model=Item,responses={404: {"model":Message}})asyncdefread_item(item_id:str):ifitem_id=="foo":return {"id":"foo","value":"there goes my hero"}else:returnJSONResponse(status_code=404,content={"message":"Item not found"})

The new docs are here:https://fastapi.tiangolo.com/tutorial/additional-responses/

@barsi
Copy link
ContributorAuthor

@tiangolo Thanks for the brilliant & carefully crafted framework 🥇 , glad to be a contributor 👍

@tiangolo
Copy link
Member

Thanks! 😊 🌮 🍰

lmignon pushed a commit to acsone/fastapi that referenced this pull requestSep 19, 2024
Signed-off-by lmignon
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment

Reviewers

No reviews

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

2 participants

@barsi@tiangolo

[8]ページ先頭

©2009-2026 Movatter.jp