Exercise: Food Truck Orders
Load the Rolling Noodle food truck's day of orders from JSON into Order objects, refuse bad JSON with a clear ValueError, then total the day, find one dish's orders and build the receipt's lines, all with type hints, and let pytest's tests check each piece.
Apprentice · Python · Updated
The Rolling Noodle food truck takes its orders on a tablet, and at closing time the tablet saves the day as JSON: a list of orders, each with its number, the customer's first name, the dish, how many and the price of one. The owner, Dara, wants three answers from that file every night: the day's total, the orders for each dish, and a receipt she can print. Last week the tablet lost power halfway through saving, and her old script stopped with a traceback nobody could read. You'll write the Python that reads a day back and refuses a broken one with a message that says what's wrong.
This is the work every API in this course does with each request: JSON comes in, it becomes Python objects, and anything broken is refused clearly. Later in the course, FastAPI and its Pydantic models take over much of it, reading the same kind of type hints you'll write here.
Get the exercise code
Open this lesson's GitHub repository, github.com/ask-codey/exercise-fastapi-food-truck-orders, also linked from the Exercise box beside the lesson. Clone it into your python-course folder. In VS Code's terminal:
cd ~/python-course
git clone https://github.com/ask-codey/exercise-fastapi-food-truck-orders.git
Git makes a folder, exercise-fastapi-food-truck-orders, with the exercise code inside. Get the Exercise Code with Git walks through cloning step by step, if you'd like a reminder. Open that folder in VS Code (File > Open Folder), open its terminal with Terminal > New Terminal, and make the exercise's virtual environment. On Windows (PowerShell):
python -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt
On a Mac (zsh):
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
The prompt starts with (.venv) once the virtual environment is on. The exercise's README says what each command does, and what to do if PowerShell won't run the second one.
The folder holds:
orders.py: theOrderclass and four functions, for you to finish.orders.json: the truck's saved day, six orders. Ready to use.show_day.py: prints the day's receipt, two dishes' orders and a refused order with your code. Ready to use.tests/test_orders.py: the tests, which make orders and check what your code gives back. You don't need to change it.requirements.txtandpytest.ini: the one package the tests need, pytest, and where pytest finds the tests and your code.
What to do
Every method and function in orders.py stops with a NotImplementedError that says Not built yet. The docstring under each one says what it should do, with examples, and names the type hints its def line should have:
def day_total(orders):
"""Return the total of every order's total(), rounded to cents with round(..., 2).
Type hints: orders is a list of Order objects, list[Order], and it returns a float.
day_total(the day in orders.json) -> 109.4
day_total([Order(201, "Rosa", "Kimchi Noodles", 1, 10.1),
Order(202, "Tom", "Kimchi Noodles", 2, 10.1)]) -> 30.3
(10.1 + 20.2 is 30.299999999999997 before it's rounded)
day_total([]) -> 0.0
"""
raise NotImplementedError("Not built yet.")
Replace each raise NotImplementedError("Not built yet.") line with your own code, and add the type hints:
Order:__init__(number, customer, dish, quantity, price)keeps each value in an attribute of the same name.total()returns quantity times price, rounded to cents.__str__returns the order's receipt line.load_orders(text): turns JSON text into a list ofOrderobjects, in the same order, and refuses bad text (below).day_total(orders): adds up every order'stotal(), rounded to cents.orders_for(orders, dish): returns the orders for one dish, matching its name exactly, capitals included.receipt_lines(orders): returns each order's receipt line, then a last line with the day's total.
These are every call the tests make, with the answer each one expects:
Order(101, "Maya", "Sesame Noodles", 2, 9.5) number 101, customer "Maya", dish "Sesame Noodles",
quantity 2 and price 9.5, in attributes of those names
Order(101, "Maya", "Sesame Noodles", 2, 9.5).total() 19.0
Order(103, "Priya", "Garlic Udon", 3, 9.95).total() 29.85, rounded from 29.849999999999998
str(Order(101, "Maya", "Sesame Noodles", 2, 9.5)) "#101 Maya: 2 x Sesame Noodles at $9.50 = $19.00"
load_orders(one order's JSON) a list with that one Order
load_orders(the text of orders.json) orders 101 to 106, in order
load_orders("[]") []
load_orders("orders for today") ValueError: The orders aren't valid JSON.
load_orders(an order with no price) ValueError: An order has no price.
load_orders(an order with no customer and no price) ValueError: An order has no customer.
day_total(the six orders in orders.json) 109.4
day_total(1 and 2 Kimchi Noodles at 10.1) 30.3, rounded from 30.299999999999997
day_total([]) 0.0
orders_for(the six orders, "Sesame Noodles") orders 101 and 104
orders_for(the six orders, "Pad Thai") []
receipt_lines(orders 101 and 102) their two lines, then "Total: $31.25"
receipt_lines(the six orders) their six lines, then "Total: $109.40"
receipt_lines([]) ["Total: $0.00"]
Five more tests read your type hints, one for Order and one for each function, so each def line needs exactly the hints its docstring names, such as list[Order] for a list of orders.
Refusing bad text. One piece of Python here may be new: raise. The exceptions you've caught so far, such as the ValueError from float("two"), were raised by Python itself. The line raise ValueError("The orders aren't valid JSON.") starts one on purpose, with your message, and the function stops there. The code that called load_orders catches it with try and except and reads your message, as show_day.py does. load_orders raises in two cases:
- Text that isn't JSON at all, such as
orders for today:ValueError("The orders aren't valid JSON."). - An order that's missing a field:
ValueError("An order has no price."), naming the field.FIELDS, at the top oforders.py, lists the five fields in order; check them in that order and name the first one that's missing.
Whenever the text is valid JSON, it's a list of orders, so you don't need to check for anything else. You'll raise exceptions again in every API you build: When It Isn't There: HTTPException and 404 raises an API's 404 the same way.
Check your work
Run the tests from the exercise folder, with the virtual environment on:
pytest
At first all 23 tests fail. That's expected: each piece you finish turns its tests green. A failing test's message says what it did, what it expected and what came back, for example Order(103, 'Priya', 'Garlic Udon', 3, 9.95).total() should give 29.85, but it gave 29.849999999999998. A type-hint test shows the def line as it should read and as it reads now.
To see your code at work, run python show_day.py.
Hints
- Start with
Order. Every other test makes orders, so nothing else can pass until__init__keeps its five values. Classes: Blueprints for Your Own Things writes one the same way. - Let
json.loadsdo the reading. It turns the text into a list of dictionaries, one per order, anditem["dish"]reads one value, as JSON Files: Saving Your Data and Looping Through Dictionaries and Nested Data show. - Catch, then raise. For text that isn't JSON,
json.loadsraises ajson.JSONDecodeError, which counts as aValueErrortoo. Put only that line in thetryblock, and raise your own message in theexcept ValueError:block. Handling Errors with try and except catches aValueErrorthe same way. - Ask the dictionary.
field in itemisTruewhen the order has that key, the same check Type Hints: Saying What a Value Should Be uses before it reads a dictionary. - Two decimal places.
f"{9.5:.2f}"gives9.50, so a receipt line always shows cents. - Use what you've built.
receipt_linesneeds each order's line, which isstr(order), and the day's total, whichday_totalalready works out (Parameters and Return Values).
When you're done
Every test is green: pytest's last line says 23 passed. And python show_day.py prints:
The Rolling Noodle: today's receipt
#101 Maya: 2 x Sesame Noodles at $9.50 = $19.00
#102 Jordan: 1 x Veggie Ramen at $12.25 = $12.25
#103 Priya: 3 x Garlic Udon at $9.95 = $29.85
#104 Luis: 1 x Sesame Noodles at $9.50 = $9.50
#105 Ana: 2 x Pork Dumplings at $7.15 = $14.30
#106 Kenji: 2 x Veggie Ramen at $12.25 = $24.50
Total: $109.40
Sesame Noodles: 2 orders, $28.50
Veggie Ramen: 2 orders, $36.75
Refused an order: An order has no price.
Now look back at load_orders. If the tablet started sending a sixth field, notes, which lines would you change, and what should happen to an order whose quantity is the text "two"? Module 2's Pydantic models answer both questions from type hints like yours.
Submit your exercise
The exercise is how you finish this lesson. When your work is done, put it on GitHub in a repo of your own, then submit that repo's address here. Hand In Your Work with Git walks through each step.
On GitHub, click +, then New repository. Name it (for example
exercise-fastapi-food-truck-orders), choose Public, and click Create repository. Leave out the README: your folder already has one.In VS Code's terminal, in your exercise folder, send your work to your new repo. Point your copy at your own repo, then commit and push:
git remote set-url origin https://github.com/your-name/exercise-fastapi-food-truck-orders.git git add . git commit -m "My solution" git push -u origin mainPaste your repo's address, such as
https://github.com/your-name/exercise-fastapi-food-truck-orders, into Submit your exercise on this page. The site checks that the repo is public and holds your commits, and then the lesson is complete.
Changed something after you submitted? Push it, and submit again: your latest submission is the one that counts.
So what
JSON in, Python objects out, and a clear refusal when something's missing: that's the first job of every API route you'll write in this course, and you've now done it by hand, with type hints that FastAPI will soon read to do it for you.