How to disable application/json in Swagger UI autodocs of a FastAPI application?

Question:

My API can return only a file:

    @router.get(
        "/partners/{partner_id}/rsr-requests/{rsr_request_id}/{document_path}",
        responses={200: {"content": {"application/octet-stream": {}}, "description": "Файл"}}
    )
    async def download_rsr_document(...):
        pass

But in Swagger UI, I can see that application/json still remains. How to disable it?

enter image description here

Answers:

From the docs you use the response_class parameter with the type of Response you want.

    from fastapi import FastAPI
    from fastapi.responses import FileResponse
    
    some_file_path = "large-video-file.mp4"
    app = FastAPI()
    
    
    @app.get("/", response_class=FileResponse)
    async def main():
        return some_file_path
Answered By: PGHE

Since your API can only return a file, you could then change the default repsonse class—which is application/json—in FastAPI, as described in this answer (see the relevant documentation as well).

Example

from fastapi import FastAPI
from fastapi.responses import FileResponse

some_file_path = "some-file.txt"
app = FastAPI(default_response_class=FileResponse)


@app.get("/")
async def main():
    return FileResponse(some_file_path)

If you only needed to do that for specific endpoint(s) in your API, you could then use the response_class parameter in your endpoint’s decorator, as follows:

@app.get("/", response_class=FileResponse)
async def main():
    #return some_file_path  # this should work as well
    return FileResponse(some_file_path)
Answered By: Chris
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.