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

How to specify the response format using response_class for a specific route?#6227

Unanswered
Thytu asked this question inQuestions
Discussion options

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but toPydantic.
  • I already checked if it is not related to FastAPI but toSwagger UI.
  • I already checked if it is not related to FastAPI but toReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

fromfastapiimportFastAPI,File,UploadFilefromfastapi.responsesimportFileResponse,Responseapp=FastAPI()classImageResponse(Response):media_type="image/*"# What do I need to add here to specify that 'format = "binary"'# here I would like to no longer have to specify 'responses' but only use 'response_class' as a single source of information@app.post("what_I_currently_do",response_class=ImageResponse,responses={200: {"content": {"image/*": {"schema":{"type":"string","format":"binary"            }        }    }}},)asyncdefsend_g(b:UploadFile=File(...)):return"/tmp/test/b.jpg"

Description

I created a POST route that return a a binary formatted image and I would like this to be specified in theopenapi.json endpoint.

For that I currently do it by adding theresponses param in the decoder (see "Example code") but I wonder if I can directly specify that the format is binary in theresponse_class.

Is it possible? If so, how?

Operating System

Linux

Operating System Details

No response

FastAPI Version

0.66.1

Python Version

3.9.7

Additional Context

No response

You must be logged in to vote

Replies: 5 comments

Comment options

You can try StreamingResponse:
https://fastapi.tiangolo.com/advanced/custom-response/#using-streamingresponse-with-file-like-objects

You must be logged in to vote
0 replies
Comment options

Theresponse_class parameter defines how your response is formatted and returned to the caller. Theresponses parameter allows you to define some documentation on specific return codes. All these return codes might (or might not, incase of validation errors for example) use yourresponse_class to format the end result.

They seem related but they aren't really. To demonstrate how the paramsresponse_class andresponses effect the documentation:

importtypingfromfastapiimportBackgroundTasks,FastAPI,File,UploadFilefromfastapi.responsesimportFileResponse,Response,JSONResponsefromstarlette.backgroundimportBackgroundTaskimportuvicornapp=FastAPI()@app.get("/with_direct_jsonresponse")asyncdefwith_direct_jsonresponse():returnJSONResponse(content="{'hello':'world']",status_code=408)# 408 will not be documented! Will only show a 200 as per default response class@app.get("with_direct_jsonresponse_and_responses",responses={406:{"description":"in-line 406 response wut?"}})asyncdefwith_direct_jsonresponse_and_responses():returnJSONResponse(content="{'hello':'world']")# This would document both 200 (as per default response class) and 406classCustomJSONResponseWith407(JSONResponse):media_type="application/json"def__init__(self,content:typing.Any,status_code:int=407,headers:typing.Optional[dict]=None,media_type:typing.Optional[str]=None,background:typing.Optional[BackgroundTask]=None,    )->None:super().__init__(content,status_code,headers,media_type,background)@app.get("/with_response_class",response_class=CustomJSONResponseWith407)asyncdefwith_response_class():return {"is this":"a 407?"}# documents only a 407, as the response class is set to that.@app.get("/with_response_class_and_responses",response_class=CustomJSONResponseWith407,responses={406:{"description":"in-line 406 response wut?"}})asyncdefwith_response_class():return {"is this":"a 407?"}# documents only a 407 as the response class is set to that,# But also a 406.if__name__=="__main__":uvicorn.run(app,host="0.0.0.0",port=8000, )

So, there is no object in theresponse_class that is used in the documentation as you want it to. Hope this clarifies :)

You must be logged in to vote
0 replies
Comment options

You can try StreamingResponse:
https://fastapi.tiangolo.com/advanced/custom-response/#using-streamingresponse-with-file-like-objects

This wouldn't work. See example below:

@app.get("/with_response_class_as_streamingresponse",response_class=StreamingResponse)asyncdefwith_response_class_as_streamingresponse():return {"is this":"a 40x?"}

Results in the following doc:
image

This is because StreamingResponse as a response_class just let's the documentation know that the default response HTTP code is 200 but basically nothing much else. It even defaults the response content-type toNone (didn't expect that actually, interesting behaviour).

You must be logged in to vote
0 replies
Comment options

Thank you all for your feedbacks. It sound strange to me to not be able to specify the schema's type within theresponse_class as it's where we can declare themedia_type.

As a workaround I will specify it in theresponse_class and use it to generate theresponses value :

classImageResponse(Response):media_type="image/*"schema= {"something":"another thing"}@app.post("my_route",response_class=ImageResponse,responses={200: {"content": {"image/*": {"schema":ImageResponse.schema        }    }}},)asyncdefsend_g(b:UploadFile=File(...)):return"/tmp/test/b.jpg"

it's not perfect but it works 🙂 Don't hesitate if you have any suggestion on how to write that in a better way.

In the mean time I think we can close this issue.

You must be logged in to vote
0 replies
Comment options

I had a similar need myself, so I found this thread. I dug through the Starlette code and FastAPI code, and as far as I can see, there's no way to specify the schema on the Response class itself - so Ithink you found the minimal code.

Here's what I ended up using, to match the schema recommended by the OpenAPI docs:https://swagger.io/docs/specification/describing-responses/#response-that-returns-a-file

class ImageResponse(fastapi.responses.Response):    media_type = "image/png"@router.get(    "/generate_map",    response_class=ImageResponse,    responses={200: {"content": {"image/png": {"schema": {"type": "string", "format": "binary"}}}}},)

Full code in:

https://github.com/pamelafox/staticmaps-function/blob/main/function/fastapi_routes.py

You must be logged in to vote
0 replies
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Labels
questionQuestion or problemquestion-migrate
4 participants
@Thytu@pamelafox@ferulisses@JarroVGIT
Converted from issue

This discussion was converted from issue #5034 on February 27, 2023 21:45.


[8]ページ先頭

©2009-2025 Movatter.jp