0

I have this code for a FastAPI app. Right now it's just supposed to take in an array of strings and return them.

from fastapi import FastAPI
from pydantic import BaseModel

class Item(BaseModel):
    name: list[str]

app = FastAPI()

@app.post("/")
async def root(item: Item):
    list_names = []
    for nm in item.name:
        list_names.append(nm)
    return {list_names}

I run the code with uvicorn main:app --reload and make a post request in insomnia to http://127.0.0.1:8000 with the following JSON:

{
    "name": [
        "each",
        "single",
        "word"
    ]
}

But it fails... I get this in insomnia:
enter image description here
I also get this in my terminal: TypeError: unhashable type: 'list'

So how do I pass an array of strings into a FastAPI post request function?

ChristianOConnor
  • 820
  • 7
  • 29

1 Answers1

1

The problem was actually the return value. The list was getting passed to the post request function just fine. The post request function was unable to return the list inside of {} brackets because the {} brackets will give you a python set. I fixed it by removing the {}. This is the fixed code:

from fastapi import FastAPI
from pydantic import BaseModel
import json

class Item(BaseModel):
    names: list = []

app = FastAPI()

@app.post("/")
async def root(item: Item):
    list_names = []
    for nm in item.names:
        list_names.append(nm)
    return list_names

And this is a successful post request in insomnia:
enter image description here

ChristianOConnor
  • 820
  • 7
  • 29
  • 3
    However, note that you’re returning a JSON array with one text string in it, the names are not an array. The issue with your first example is that the {} brackets will give you a python `set`. However, you don’t have to use `json.dumps`, try just `return list_names`. – M.O. Mar 02 '23 at 08:12
  • Oh awesome thanks! I updated my answer to add this change – ChristianOConnor Mar 02 '23 at 22:26