I want my FastAPI application to return JSON:API responses. It would be really cumbersome to craft each response manually so I’ve looked into creating a custom response class, one based on JSONResponse
, since the responses have to be in JSON format.
They have an example here:
https://fastapi.tiangolo.com/advanced/custom-response/#custom-response-class
So, subclass your response class (in my case JSONResponse
), subclass it, implement the render
method.
So far so good:
class JSONAPIResponse(JSONResponse):
def render(self, content: Any) -> Any:
# Null object.
if content is None:
[...]
However, the problem comes at the next step.[1]
If I add a content_object_type
to JSONAPIResponse, I put it in the __init__
method and everything, FastAPI still complains about it.
class JSONAPIResponse(JSONResponse):
content_object_type: str
def __init__(self, content: Any, content_object_type: str):
super().__init__(content=content)
self.content_object_type = content_object_type
def render(self, content: Any) -> Any:
self.content_object_type
[... Elsewhere in the code base, another method ...]
return JSONAPIResponse(content=jsonable_encoder(content_object), content_object_type="bla")
Boom ???? this is the FastAPI error message below
<code>def render(self, content: Any) -> Any:self.content_object_type</code><code>def render(self, content: Any) -> Any: self.content_object_type </code>def render(self, content: Any) -> Any: self.content_object_type
E AttributeError: ‘JSONAPIResponse’ object has no attribute ‘content_object_type’
So I’ve declared the attribute, I have it in the constructor that’s used… what’s wrong?