Exam Study Guide
The exam will cover Units 1 through 6 and homeworks 1 through 5.
Python: programming and best practices
Writing code with: functions, loops, if-then, data structures, types
Code organization: functions, classes, modules, libraries (packages), imports
Maintaining package dependencies with
uvLogging
Programmatic testing
Data formats, primarily JSON
What are the functions to read JSON from strings and from files?
What kinds of data types can be serialized into JSON? What is an example of a data type that cannot be
serialized into JSON? * What are the functions for writing Python objects to JSON?
Pydantic data models
Building classes from
BaseModel, specifying types of fields.Building classes from other classes
Containers, specifically Docker
Describe the concepts of Docker container, image, volume and network.
What a Dockerfile is used for and some basic instructions including
FROM,RUN,COPY,ENV
APIs and FastAPI
The basic HTTP methods GET, POST, PUT, DELETE
HTTP headers and the meaning of
Content-typeandContent-lengthHTTP response codes and the meaning of a 200 level, 400 level and 500 level response
Basics of using
curlandrequeststo make HTTP requests to a server.RESTful HTTP API architecture, including URL paths as collections, single items, and subcollections, and HTTP verbs for actions.
Building HTTP APIs with FastAPI, including:
The
appobject and the@appdecoratorsSpecifying request and response types
Specifying and working with URL path parameters
Specifying and working with URL query parameters
Example Exam Questions
Warning
This set of example questions is not intended to be a comprehensive study guide. Rather, it is only intended to give you a sense of the format of questions you will be asked. Be sure to review all of the topics in the previous section.
Short Answer
(True/False) A docker container is built from a Docker volume?
(True/False) An HTTP header is formatted as a name-value pair.
(True/False) If an API server is overloaded with too many requests from clients, it should return a 400-level error response.
(True/False) A Python library available in the standard library, such as the
jsonlibrary, must be installed using a tool likeuvfrom PyPI, the Python Package Index.(True/False) In Python, logs can be set at different levels to distinguish the severity or importance of the message being logged.
(True/False) In Python, a decorator returns a function.
(True/False) The HTTP method for creating a resource is PUT.
(True/False) Containers deployed to some server do NOT share an operating system.
(True/False) In order to define a new pydantic model, you must create a class that extends pydantic’s
BaseModel(True/False) In python
json.loadsconverts a JSON-serialized string into a dictionary.(True/False) You can defined nested paydantic models. i.e., a ShoppingCart model have an attribute
itemswhich is a list of ShoppingCartItem models.(True/False) FastAPI ignore type hints in routes
(True/False) Pydantic models can NOT extend of pydantic models. Ex. Given model Animal(BaseModel), you can define a model like Dog(Animal).
(True/False) A standard endpoint for an HTTP server will have both a route (“/products”) and an HTTP verb
(True/False) In Python, you can use the
typefunction to inspect the type of any object(True/False) If you some code within an
ifstatement likeif __name__ == "__main__":, when the module that contains this code is imported, the code within thatifstatement will run.(True/False) When testing your code using
pytest, you should prefix your test function names withtest_
Multiple choice
When working with a Dockerfile (select all that apply):
Use the
COPYinstruction to make a copy of a container.The
FROMinstruction is used to define a pre-existing image as the starting point or base for the new image.Use the
docker buildcommand to build the image defined by the Dockerfile.Use the
RUNinstruction to run containers from the built image.
Which of thehe following Python objects are JSON-serializable (select all that apply):
A single string, such as
"abc"Boolean values, including
TrueandFalseThe contents of an image file, such as a
jpgfile, read from disk usingfile.open().The following list:
[ {"a": 1, "key": True}, 7, "Another string", {"key": "value"}]
Which of the following HTTP methods should be used when creating a new resource:
GET
PUT
PATCH
DELETE
POST
Which of the following status codes should be returned when a user makes a mistake.
100
200
300
400
500
Complete the following decorator for a route that should return a list of courses:
@app.______(“/courses”)
get
GET
post
POST
list
LIST
In your FastAPI application, a user requests a resource that does not exist so you raise the following
Exception.raise HTTPException(status_code=_________). Complete the exception:
500
200
400
404
201
To see the headers when making a request using the command line utility
curl, you must use which of the following flags:
-X
-d
-v
--help
--show-headers
Code Analysis
What will be the output of the following code?
data = [{"a": 1, "b": 2}, {"a": 3, "b": -1}, {"a": 4, "b": 1}]
def f(key):
tot = 0
for item in data:
val = item[key]
tot += val
return tot
print(f("b"))
Writing Code: Part 1
Given the following code:
def get_data():
return {
"products": [
{"id": 1, "name": "Apple", "price": .50},
{"id": 2, "name": "Banana", "price": 10.00},
{"id": 3, "name": "Coconut", "price": 4.50},
{"id": 4, "name": "Pear", "price": 2.50},
{"id": 5, "name": "Lettuce", "price": 1.50},
]
}
- Write a function that:
Takes a single argument that is a list of product dictionaries
Sums the value of all products
and returns that sum as a float
contains type hints for the argument and the return type
Call that function with the data returned from get_data and prints the result to stdout
Writing Code: Part 2
Given the following code:
from pydantic import BaseModel
from fastapi import FastAPI, HTTPException
app = FastAPI()
class Product(BaseModel):
id: int
name: str
price: float
def get_data():
return {
"products": [
{"id": 1, "name": "Apple", "price": .50},
{"id": 2, "name": "Banana", "price": 10.00},
{"id": 3, "name": "Coconut", "price": 4.50},
{"id": 4, "name": "Pear", "price": 2.50},
{"id": 5, "name": "Lettuce", "price": 1.50},
]
}
Write 2 FastAPI routes.
- Route 1
Converts the data returned by
get_datainto a list of pydantic modelsReturns a list of products
@app.____("/_______________")
def list_products():
# Fill in the code below
- Route 2
Converts the data returned by
get_datainto a list of pydantic modelsReturns a single product by the specified
idRaises an
HTTPExceptionwith the correct status code if no product is found with the providedid.
@app.____("/_______________/{___}")
def get_product_by_id(___: ___):
# Fill in the code below
Note
FastAPI allows you to return the pydantic models directly. The framework will serialize it for you