The Python You Need for APIs

Refresh the Python every API leans on: functions with parameters and return values, nested data made of lists and dictionaries, JSON, handling errors with try and except, classes, and type hints. Each lesson comes from Python in Depth, so you can skip the ones you know, then use them all on a food truck's day of orders.

Updated

Functions and Data for APIs

  1. Parameters and Return Values (Novice): Parameters let a function work on whatever values each call hands it, and return hands a result back to the code that called it, which is different from printing it and gives None when a function returns nothing.
  2. Looping Through Dictionaries and Nested Data (Apprentice): A for loop goes through a dictionary's keys, items(), keys() and values() give its pairs, its keys or its values, and lists of dictionaries and dictionaries of lists hold whole tables of data, the shape CSV files and web APIs give you.
  3. JSON Files: Saving Your Data (Apprentice): JSON is a text format for data that json.dump and json.load turn Python's dictionaries and lists into and back from, through a file, while json.dumps and json.loads do the same with a string, which is how web APIs send their answers.

Errors and Classes for APIs

  1. Handling Errors with try and except (Apprentice): An exception is Python's report of an error while a program runs, and try and except let a program catch the one it expects, such as the ValueError from turning "two" into a number, with else for what runs when nothing went wrong and finally for what runs every time.
  2. Classes: Blueprints for Your Own Things (Apprentice): A class describes one kind of thing your program keeps track of, what it holds and what it can do, so every object made from it gets the same attributes, the same methods and a friendly printout.
  3. Type Hints: Saying What a Value Should Be (Apprentice): A type hint is a label on a variable, a parameter or a return value that says what kind of value belongs there, such as float, list[float] or a string that may be None, so people and tools can see what a function expects without reading its body.

Exercise: Food Truck Orders

  1. Exercise: Food Truck Orders (Apprentice): 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.