Advanced level · Module 4: Deploying Machine Learning Models · Lesson 2 of 4
Serving Predictions with an API
Wrap a model in a web API with validated inputs, clear errors and a health check.
In this lesson you will
- Build a FastAPI prediction endpoint
- Validate inputs with Pydantic models
Key concepts
FastAPIPydantic schema422 validation errorshealth endpoint
The lesson
FastAPI builds Python web APIs quickly. Load the model once at start-up and expose an endpoint such as POST /forecast that accepts JSON and returns predictions.
Define the input with a Pydantic model: field types, allowed ranges and required values. Invalid requests are rejected automatically with a clear 422 response instead of crashing the model.
Add a GET /health endpoint that confirms the model is loaded, and include the model version in responses so every prediction can be traced.
Step by step
- Create a FastAPI app that loads the model at start-up.
- Define the input schema with Pydantic.
- Implement POST /forecast and GET /health.
- Test valid and invalid requests.
Practice activity
Serve the price model through a validated API.
Expected result: The API returns forecasts with the model version and rejects invalid input clearly.
Check your understanding
-
Why load the model at start-up rather than per request?
Show answer
Loading is slow; doing it once keeps requests fast.
-
What does Pydantic validation provide?
Show answer
Automatic checking of input types and values with clear error responses.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.