Skip to content

"RecursionError" happens when jsonable_encoder is used inside path operation functionΒ #14

@amirsoroush

Description

@amirsoroush

Sometimes it's preferable to return JSONResponse directly. To ensure the returning object is jsonable, jsonable_encoder() should be used. When doing so, RecursionError: maximum recursion depth exceeded happens.

Here is a simple code to reproduce:

from dataclasses import dataclass
from typing import Literal
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from richapi.exc_parser.handler import add_exc_handler
from richapi.exc_parser.openapi import enrich_openapi
from richapi.exc_parser.protocol import RichHTTPException


@dataclass
class NShouldNotBeTen(RichHTTPException):
    message: Literal["N should not be 10"] = "N should not be 10"
    status_code = 403

class NWrapper(BaseModel):
    value: int

app = FastAPI()
app.openapi = enrich_openapi(app)
add_exc_handler(app)

@app.get("/{n}", response_model=NWrapper)
async def index(n: int) -> JSONResponse:
    if n == 10:
        raise NShouldNotBeTen
    return JSONResponse(content=jsonable_encoder(NWrapper(value=n)))

curl -X "GET" "http://127.0.0.1:8000/20" works fine but the swagger UI (http://127.0.0.1:8000/docs) won't be rendered as it cannot generate openapi.json, and it raises the aforementioned exception.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions