'Parsing JSON from POST request using Python and FastAPI

I'm trying to parse a JSON that came from a POST request from user to my API made with FastAPI. I have a nested JSON that can receive multiple values and my problem is: How can I parse it and get the values from this nested JSON?

The JSON is like this:

{
    "recipe": [
    {
        "ingredient": "rice",
        "quantity": 1.5
        },
    {
        "ingredient": "carrot",
        "quantity": 1.8
        },
    {
        "ingredient": "beans",
        "quantity": 1.8
        }
    ]
}

I must grab the all values from the list recipe separated, as I have a database with this ingredient and will query all of this and do some calculates with the quantity given from user. But I don't even know how I can parse this JSON from the POST request.

I already have a 2 classes with Pydantic validating this values like:

class Ingredientes(BaseModel):
    ingredient: str
    quantity: float


class Receita(BaseModel):
    receita: List[Ingredientes] = []

Edit 1: I tried to include it in my function that recieve this POST request and didn't work like:

@app.post('/calcul', status_code=200)
def calculate_table(receita: Receita):
    receipe = receita["receita"]
    for ingredient in receipe:
        return f'{ingredient["ingredient"]}: {ingredient["quantity"]}'

Edit 2: Fixed the issue with the code bellow(Thanks MatsLindh):

@app.post('/calcul', status_code=200)
def calculate_table(receita: Receita):
    receipe = receita.receita
    for ingredient in receipe:
        return f'{ingredient.ingrediente}: {ingredient.quantidade}'


Solution 1:[1]

To parse a JSON-formatted string (from the POST request, for example) into a dictionary, use the loads function from the json module, like this:

import json

s = """{
    "recipe": [
    {
        "ingredient": "rice",
        "quantity": 1.5
        },
    {
        "ingredient": "carrot",
        "quantity": 1.8
        },
    {
        "ingredient": "beans",
        "quantity": 1.8
        }
    ]
}
"""
recipe = json.loads(s)["recipe"]
for ingredient in recipe:
    print(f"{ingredient['ingredient']}: {ingredient['quantity']}")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Programmer