In python, using Fast API, I have a str that when print show (this is an example, the real str is more complex) :
[1592494390, 'test', -0.2761097089544078, -0.0852381808812182, -0.101153, nan]
I want to return this using Fast API as a JSON array.
Using JSONResponse
def get_json(dataset: str, timeseries: str):
test = "[1592494390, 'test', -0.2761097089544078, -0.0852381808812182, -0.101153, nan]"
print(test)
return JSONResponse(content=test)
The print is as expecting showing:
[1592494390, 'test', -0.2761097089544078, -0.0852381808812182, -0.101153, nan]
But the answer of the API when hitting the call is:
"[1592494390, 'test', -0.2761097089544078, -0.0852381808812182, -0.101153, nan]"
So my str
is being serialised again and I don't know how to by-pass that.
Using Response :
The documentation of Fast API includes a page that describes how to return a Response directly (https://fastapi.tiangolo.com/advanced/response-directly/) where it is written:
When you return a Response directly its data is not validated, converted (serialized), nor documented automatically.
But using this method leads to an error :
def get_json(dataset: str, timeseries: str):
test = "[1592494390, 'test', -0.2761097089544078, -0.0852381808812182, -0.101153, nan]"
print(test)
return Response(content=test, media_type="application/json")
> line 53, in get_json
return Response(content=test, media_type="application/json")
File "pydantic/main.py", line 331, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 2 validation errors for Response
description
field required (type=value_error.missing)
content
value is not a valid dict (type=type_error.dict)
By the way the exact xml example of the documentation gives the same error:
> line 61, in get_json
return Response(content=data, media_type="application/xml")
File "pydantic/main.py", line 331, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 2 validation errors for Response
description
field required (type=value_error.missing)
content
value is not a valid dict (type=type_error.dict)
I know I can convert my data to a an array or dict to be serialized I how want but as I already have the right str and don't want the job to be done several times.