Bird
Raised Fist0
MLOpsdevops~20 mins

REST API serving with FastAPI in MLOps - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
FastAPI Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
1:30remaining
What is the output of this FastAPI endpoint response?
Given this FastAPI endpoint code, what will be the JSON response when a GET request is made to /items/42?
MLOps
from fastapi import FastAPI
app = FastAPI()

@app.get('/items/{item_id}')
async def read_item(item_id: int):
    return {"item_id": item_id, "name": f"Item {item_id}"}
A{"item_id": 42, "name": "item 42"}
B{"item_id": "42", "name": "Item 42"}
C{"item_id": 42, "name": "Item 42"}
D{"item_id": 42}
Attempts:
2 left
💡 Hint
Remember that FastAPI converts path parameters to the declared type.
Configuration
intermediate
1:30remaining
Which uvicorn command correctly runs the FastAPI app from main.py with auto-reload?
You have a FastAPI app in main.py with the app instance named app. Which command will start the server with auto-reload enabled?
Auvicorn main.py:app --reload
Buvicorn app:main --reload
Cuvicorn main.app --reload
Duvicorn main:app --reload
Attempts:
2 left
💡 Hint
The syntax is uvicorn module_name:app_instance.
🔀 Workflow
advanced
2:00remaining
What is the correct sequence to deploy a FastAPI app with Docker?
Arrange these steps in the correct order to build and run a FastAPI app using Docker.
A1,2,3,4
B2,1,3,4
C1,3,2,4
D3,2,1,4
Attempts:
2 left
💡 Hint
Think about writing the Dockerfile before building the image.
Troubleshoot
advanced
1:30remaining
Why does this FastAPI app raise a 422 error on POST?
This FastAPI endpoint expects JSON with name (string) and age (int). The client sends {"name": "Alice", "age": "25"}. Why does the server respond with status 422?
MLOps
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    name: str
    age: int

@app.post('/users')
async def create_user(user: User):
    return user
ABecause age is sent as a string, not an integer
BBecause name is missing in the JSON
CBecause the endpoint only accepts GET requests
DBecause the JSON is missing required fields
Attempts:
2 left
💡 Hint
Check the data types expected by Pydantic models.
Best Practice
expert
2:00remaining
Which approach best improves FastAPI app performance under high load?
You want to improve the performance of a FastAPI app serving ML model predictions under heavy traffic. Which option is the best practice?
AUse a single uvicorn worker to avoid race conditions
BUse Gunicorn with multiple workers and uvicorn workers to handle concurrency
CDisable async features to simplify code
DRun uvicorn with --reload for faster code changes in production
Attempts:
2 left
💡 Hint
Consider how to handle many requests efficiently in production.

Practice

(1/5)
1. What is the main purpose of using FastAPI in serving machine learning models?
easy
A. To train machine learning models faster
B. To create fast and simple REST APIs for model serving
C. To store large datasets efficiently
D. To visualize model performance graphs

Solution

  1. Step 1: Understand FastAPI's role

    FastAPI is a web framework used to build APIs quickly and simply.
  2. Step 2: Connect to model serving

    It is commonly used to serve machine learning models via REST APIs for easy access.
  3. Final Answer:

    To create fast and simple REST APIs for model serving -> Option B
  4. Quick Check:

    FastAPI = REST API serving [OK]
Hint: FastAPI is for building APIs, not training or storage [OK]
Common Mistakes:
  • Confusing API serving with model training
  • Thinking FastAPI handles data storage
  • Assuming FastAPI is for visualization
2. Which of the following is the correct way to define a GET endpoint in FastAPI?
easy
A. @app.route('/items', method='GET') def read_items(): return {'items': []}
B. @app.post('/items') def read_items(): return {'items': []}
C. @app.get('/items') def read_items(): print('items')
D. @app.get('/items') def read_items(): return {'items': []}

Solution

  1. Step 1: Identify correct decorator for GET

    FastAPI uses @app.get() to define GET endpoints.
  2. Step 2: Check function returns JSON response

    The function should return a dictionary to send JSON; print statement does not return data.
  3. Final Answer:

    @app.get('/items')\ndef read_items():\n return {'items': []} -> Option D
  4. Quick Check:

    @app.get() + return dict = correct GET endpoint [OK]
Hint: Use @app.get() and return dict for GET endpoints [OK]
Common Mistakes:
  • Using @app.post() for GET endpoints
  • Using print instead of return
  • Using Flask-style @app.route() syntax
3. What will be the output when you call the following FastAPI endpoint?
@app.get('/hello')
def say_hello():
    return {'message': 'Hello, FastAPI!'}
medium
A. {\"message\": \"Hello, FastAPI!\"}
B. Hello, FastAPI!
C. Error: Missing return type
D. 404 Not Found

Solution

  1. Step 1: Analyze endpoint return value

    The function returns a dictionary with key 'message' and value 'Hello, FastAPI!'.
  2. Step 2: Understand FastAPI response format

    FastAPI automatically converts dict to JSON response with the same structure.
  3. Final Answer:

    {"message": "Hello, FastAPI!"} -> Option A
  4. Quick Check:

    Return dict = JSON response with same keys [OK]
Hint: Return dict from endpoint gives JSON response [OK]
Common Mistakes:
  • Expecting plain string instead of JSON
  • Thinking missing return type causes error
  • Assuming endpoint path is incorrect
4. Identify the error in this FastAPI POST endpoint code:
@app.post('/predict')
def predict(data: dict):
    return {'result': data['value'] * 2}
medium
A. Missing request body declaration with Pydantic model
B. Incorrect HTTP method, should be GET
C. Function missing return statement
D. Syntax error in decorator

Solution

  1. Step 1: Check parameter type for POST data

    FastAPI requires request body to be declared with Pydantic models or Body for parsing JSON.
  2. Step 2: Understand why dict alone is insufficient

    Using plain dict as parameter does not parse JSON body automatically, causing validation error.
  3. Final Answer:

    Missing request body declaration with Pydantic model -> Option A
  4. Quick Check:

    POST body needs Pydantic model or Body [OK]
Hint: Use Pydantic models for POST request bodies [OK]
Common Mistakes:
  • Using plain dict instead of Pydantic model
  • Confusing POST with GET method
  • Forgetting to return a response
5. You want to serve a machine learning model prediction via FastAPI. Which approach correctly handles input validation and prediction?
from pydantic import BaseModel

class InputData(BaseModel):
    feature1: float
    feature2: float

@app.post('/predict')
def predict(data: InputData):
    result = model.predict([[data.feature1, data.feature2]])
    return {'prediction': result[0]}

What is the main advantage of this design?
hard
A. It skips input validation for faster response
B. It trains the model on each request
C. It validates input data types automatically before prediction
D. It returns raw model object instead of prediction

Solution

  1. Step 1: Understand Pydantic model role

    InputData class validates that feature1 and feature2 are floats before function runs.
  2. Step 2: Connect validation to prediction safety

    This prevents invalid data from reaching model.predict, avoiding runtime errors.
  3. Final Answer:

    It validates input data types automatically before prediction -> Option C
  4. Quick Check:

    Pydantic = automatic input validation [OK]
Hint: Use Pydantic models to validate inputs before prediction [OK]
Common Mistakes:
  • Thinking model retrains on each request
  • Skipping validation causes errors
  • Returning model object instead of prediction