Retrieve food objects
Level: Intermediate (score: 3)
Now that our API can add food
objects, let's retrieve them from the foods
dictionary.
In this Bite you will write two endpoints to do so:
- read_foods()
to retrieve all foods
- read_food()
to retrieve a single food by id (i.e. the key in the foods
dictionary). For this you will need what FastAPI calls a path parameter.
After completing this Bite, you will be halfway there with the CRUD (create-read-update-delete) of foods. In the next Bite we'll have you implement the update and delete endpoints.
Good luck!
x
from typing import Dict
from fastapi import FastAPI
from pydantic import BaseModel
class Food(BaseModel):
"""Model from Bite 02"""
id: int
name: str
serving_size: str
kcal_per_serving: int
protein_grams: float
fibre_grams: float = 0
app = FastAPI()
foods: Dict[int, Food] = {}
post("/", status_code=201) .
async def create_food(food: Food):
"""Endpoint from Bite 03"""
foods[food.id] = food
return food
# write the two Read endpoints