FastApi - receive list of objects in body request

Viewed 8214

I need to create an endpoint that can receive the following JSON and recognize the objects contained in it:

{​
  "data": [
    {​
      "start": "A", "end": "B", "distance": 6
    }​,
    {​
      "start": "A", "end": "E", "distance": 4
    }​
  ]
}

I created a model to handle a single object:

class GraphBase(BaseModel):
    start: str
    end: str
    distance: int

And with it, I could save it in a database. But now I need to receive a list of objects and save them all. I tried to do something like this:

class GraphList(BaseModel):
    data: Dict[str, List[GraphBase]]

@app.post("/dummypath")
async def get_body(data: schemas.GraphList):
    return data

But I keep getting this error on FastApi: Error getting request body: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) and this message on the response:

{
    "detail": "There was an error parsing the body"
}

I'm new to python and even newer to FastApi, how can I transform that JSON to a list of GraphBaseto save them in my db?

1 Answers

This is a working example.

from typing import List
from pydantic import BaseModel
from fastapi import FastAPI

app = FastAPI()

class GraphBase(BaseModel):
    start: str
    end: str
    distance: int

class GraphList(BaseModel):
    data: List[GraphBase]

@app.post("/dummypath")
async def get_body(data: GraphList):
    return data

I could try this API on the autogenerated docs.

enter image description here

Or, on the console (you may need to adjust the URL depending on your setting):

curl -X 'POST' \
  'http://localhost:8000/dummypath' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "data": [
    {
      "start": "string",
      "end": "string",
      "distance": 0
    }
  ]
}'

The error looks like the data problem. And I found that you have extra spaces at several places. Try the following:

{
  "data": [
    {
      "start": "A", "end": "B", "distance": 6
    },
    {
      "start": "A", "end": "E", "distance": 4
    }
  ]
}

The positions of extra spaces (which I removed) are below:

enter image description here

Related