#!/usr/bin/env python3 #from https://python.plainenglish.io/taming-your-python-dictionaries-with-dataclasses-marshmallow-and-desert-388dbffedaec from dataclasses import dataclass import json from marshmallow import EXCLUDE, fields, post_load, Schema, validate import requests @dataclass class Activity: activity: str participants: int price: float class ActivitySchema(Schema): activity = fields.Str(required=True) participants = fields.Int( required=True, validate=validate.Range(min=1, max=50, error="Participants must be between 1 and 50 people") ) price = fields.Float( required=True, validate=validate.Range(min=0, max=1, error="Price must be between $1 and $100") ) @post_load def transform_price(self, data, **kwargs): # The `price` key always has the price between 0 and 1 for some reason so # let's convert that number into dollars data['price'] = data['price'] * 100 return data def get_activity() -> Activity: # Restore https when https://github.com/drewthoennes/Bored-API/issues/61 fixed resp = requests.get("http://www.boredapi.com/api/activity").json() validated_resp = ActivitySchema(unknown=EXCLUDE).load(resp) return Activity( activity=validated_resp["activity"], participants=validated_resp["participants"], price=validated_resp["price"] ) if __name__ == '__main__': print(get_activity())