Skip to content

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

@Thytu

Description

@Thytu

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 to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from fastapi import FastAPI, File, UploadFile
from fastapi.responses import FileResponse, Response


app = FastAPI()


class ImageResponse(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"
            }
        }
    }}},
)
async def send_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 the openapi.json endpoint.

For that I currently do it by adding the responses param in the decoder (see "Example code") but I wonder if I can directly specify that the format is binary in the response_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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions