Search code examples
pythonpostfastapiuvicorninsomnia

How do I pass an array of strings to a FastAPI post request function?


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?


Solution

  • 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