Reissel Reis
Reissel Reis

Reputation: 93

FastApi - receive list of objects in body request

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?

Upvotes: 9

Views: 27251

Answers (2)

verwirrt
verwirrt

Reputation: 165

Generally, FastAPI allows for simply receiving a list of objects, there's no need to wrap that list in an extra object.

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class ObjectListItem(BaseModel):
  ...

@app.post("/api_route")
def receive_list_of_objects(objects_list: list[ObjectListItem]):
  ...

More information in the FastAPI documentation.

Upvotes: 0

Kota Mori
Kota Mori

Reputation: 6750

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

Upvotes: 12

Related Questions