fastapi: use middleware to generate a result in which the original result is included as an element

131 Views Asked by At

there is this code:

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

app = FastAPI()

@app.middleware("http")
async def response_middleware(request: Request, call_next):
    # execute the request
    results = await call_next(request)

    return JSONResponse(content={
        'response': results 
    })

  
@app.post("/test/")
async def test_func():
    results = {
        'test': 10
    }

    return results

but errors are generated

raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type 
_StreamingResponse is not JSON serializable

how to correctly pass results as an output dictionary element

Is JSONResponse necessary at all?

I thought it could be done simply:

async def response_middleware(request: Request, call_next):
    # execute request
    results = await call_next(request)

    return {
        'response': results 
    }

but no

0

There are 0 best solutions below