FastAPI is returning AttributeError: 'dict' object has no attribute 'encode'
Question:
I am having a very simple FastAPI service, when I try to hit the /spell_checking
endpoint, I get this error `AttributeError: ‘dict’ object has no attribute ‘encode’.
I am hitting the endpoint using postman, with Post request, and this is the url: http://127.0.0.1:8080/spell_checking
, the payload is JSON with value:
{"word": "testign"}
Here is my code:
from fastapi import FastAPI, Response, Request
import uvicorn
from typing import Dict
app = FastAPI()
@app.post('/spell_checking')
def spell_check(word: Dict ) :
data = {
'corrected': 'some value'
}
return Response(data)
@app.get('/')
def welcome():
return Response('Hello World')
if __name__ == '__main__':
uvicorn.run(app, port=8080, host='0.0.0.0')
I still dont know why a simple service like this would show this error!
Answers:
The problem happens when you try to create the Response
object. This object expects a string as input (infact it tries to call .encode()
on it).
There is no need to explicitly create one, you can just return the data and fastapi will do the rest.
from typing import Dict
import uvicorn
from fastapi import FastAPI
app = FastAPI()
@app.post("/spell_checking")
def spell_check(word: Dict):
data = {"corrected": "some value"}
return data
@app.get("/")
def welcome():
return "Hello World"
if __name__ == "__main__":
uvicorn.run(app, port=8080, host="0.0.0.0")
I am having a very simple FastAPI service, when I try to hit the /spell_checking
endpoint, I get this error `AttributeError: ‘dict’ object has no attribute ‘encode’.
I am hitting the endpoint using postman, with Post request, and this is the url: http://127.0.0.1:8080/spell_checking
, the payload is JSON with value:
{"word": "testign"}
Here is my code:
from fastapi import FastAPI, Response, Request
import uvicorn
from typing import Dict
app = FastAPI()
@app.post('/spell_checking')
def spell_check(word: Dict ) :
data = {
'corrected': 'some value'
}
return Response(data)
@app.get('/')
def welcome():
return Response('Hello World')
if __name__ == '__main__':
uvicorn.run(app, port=8080, host='0.0.0.0')
I still dont know why a simple service like this would show this error!
The problem happens when you try to create the Response
object. This object expects a string as input (infact it tries to call .encode()
on it).
There is no need to explicitly create one, you can just return the data and fastapi will do the rest.
from typing import Dict
import uvicorn
from fastapi import FastAPI
app = FastAPI()
@app.post("/spell_checking")
def spell_check(word: Dict):
data = {"corrected": "some value"}
return data
@app.get("/")
def welcome():
return "Hello World"
if __name__ == "__main__":
uvicorn.run(app, port=8080, host="0.0.0.0")