2

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!

sin0x1
  • 105
  • 1
  • 3
  • 13
  • @Chris technically, this is what I wanted to do, yet the error did not specify what's causing it, which I found it weird, that's why I was fed up with it. – sin0x1 Oct 20 '22 at 08:16

1 Answers1

3

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")

Matteo Zanoni
  • 3,429
  • 9
  • 27