Good evening, I hope this is the right section for my question.
I am working on an API that serves as backend for a React webapp, and uses FastAPI and Pydantic.
It is basically an hotel booking engine.
I have this model, RoomOccupancy(), which represents an hotel room, the age of each guest, number of pets if any, and other parameters. This object is meant to be used for handling both availability requests and availability responses.
As a workaround, I thought to implement a method that somehow converts the RoomOccupancy object from and to a serialized string or a stringified JSON object (you can see a draft in the obe code, in the
Any suggestion? How do you usually handle this cases, what is the best practise? Did I get my design wrong perhaps?
Pydantic and FastAPI are quite new to me.
I am working on an API that serves as backend for a React webapp, and uses FastAPI and Pydantic.
It is basically an hotel booking engine.
I have this model, RoomOccupancy(), which represents an hotel room, the age of each guest, number of pets if any, and other parameters. This object is meant to be used for handling both availability requests and availability responses.
class RoomOccupancy(BaseModel): ages: List[int] = [] pets: Union[int, None] = None min_age: int = 4 def __str__(self): # string repr should be a RoomOccupancy serialized as JSON object, to be passed in a query string return(str({"ages":str(self.ages),"pets":str(self.pets),"min_age":str(self.min_age)})) @property def adults(self): return [guest for guest in self.ages if guest >= self.min_age] @property def children(self): return [abs(guest) for guest in self.ages if guest < self.min_age] # always positive int values # The rest of the class is omitted, we don't need it here...My idea is that the client, amongst other query parameters such as checkin_date and check_out date, uses the parameter "rooms" to pass a list of RoomOccupancy objects. This is the implementation I had in mind:
@app.get("/avail/byroom") async def get_available_rooms( check_in: datetime.date, check_out: datetime.date, rooms: List[RoomOccupancy.RoomOccupancy], min_age: Union[int, None] = 4 ): # Debug... return { check_in: f"{check_in}", check_out: f"{check_out}", rooms: [room.dict() for room in rooms], min_age: f"{min_age}" }However, I don't know how the client should structure the URL request - in other words, what should be the content of the rooms parameter.
As a workaround, I thought to implement a method that somehow converts the RoomOccupancy object from and to a serialized string or a stringified JSON object (you can see a draft in the obe code, in the
__str__()
. But this sounds unelegant, difficult to maintain and honestly an overkill. Any suggestion? How do you usually handle this cases, what is the best practise? Did I get my design wrong perhaps?
Pydantic and FastAPI are quite new to me.