Building Machine Learning APIs with FastAPI: A Beginner’s Guide to Serving Python Models

A student has already trained a Random Forest and built the interactive Streamlit application from Topic 92. A classmate can open that app, type property measurements and view a historical price estimate. But now a mobile app, a school dashboard and another Python program all need to ask the same model for a prediction—without opening the Streamlit interface. How can these different programs send inputs, receive reliable results and detect mistakes?

The answer is to build a machine learning API with FastAPI. This beginner guide teaches the HTTP and JSON fundamentals, Pydantic input validation, serving a saved Scikit-learn Pipeline, secure model loading, health and readiness checks, OpenAPI documentation, automated testing and Docker packaging. Our practical project is a historical six-feature Ames Housing prediction service. The application architecture is reusable for other models, but its house-price estimates are not present-day professional appraisals.

Actual verification and disclosure — 25 November 2026: The downloadable FastAPI project was created and syntax-checked, and its locally runnable validation tests report 6 passed, 2 skipped using installed FastAPI 0.128.2, Pydantic 2.13.5, Scikit-learn 1.8.0, HTTPX 0.28.1 and pytest 9.0.2. The two skipped endpoint tests require an authentic fitted Ames model. OpenML dataset 42165 could not be fetched in this execution environment, so no Ames training scores, model artifact, authentic prediction, live Uvicorn prediction test, Docker build or public API URL is claimed. The source intentionally fails startup rather than returning invented predictions. The architecture graphics are conceptual, not live API screenshots.

What is an API? An everyday explanation

API stands for Application Programming Interface. It is a defined way for one software component to interact with another. Imagine a restaurant: a customer chooses a meal, a server receives the order, a kitchen prepares it and the customer receives the result. In software, a client sends a structured request, a server receives it, an application performs an operation and a response is returned.

The analogy helps explain separation of responsibilities, but it is not an exact technical specification. An API is not necessarily a visible website; many are designed for programs rather than people. A machine-learning API accepts data, applies an existing model and returns a prediction or a meaningful error. The API’s input contract lets different kinds of software call the same predictive service consistently.

What is a REST API, and is every JSON service RESTful?

REST, or Representational State Transfer, is an architectural style for networked systems. It emphasizes concepts such as resources, consistent interfaces, stateless requests and representations. HTTP provides methods and standard response codes that many REST-oriented services use. A browser might request a page with GET, while a program sends a new collection of house measurements to a prediction endpoint with POST.

Simply responding to JSON with POST does not prove that every REST architectural constraint is satisfied. Our example is best described as a practical HTTP/JSON inference service that teaches REST-related conventions. The essential beginner skill is learning the request and response contract while understanding that broader architecture has additional design questions.

Understand client–server communication

A client is software that requests a service. It could be a phone app, a WordPress frontend, a command-line script or Streamlit. A server runs the FastAPI application and receives those requests. The client supplies six named property characteristics; FastAPI validates the JSON; a saved model Pipeline transforms the inputs and estimates a historical sale price; FastAPI returns structured JSON.

The server does not need to share its Python source code with the client for ordinary inference. In contrast, a client needs to know the endpoint URL, allowed HTTP method, fields, units, authentication requirements and possible errors. A well-defined API contract makes it possible to replace or update the underlying model without rewriting every client, provided the contract and prediction meaning remain compatible.

Client to FastAPI validation, saved preprocessing Pipeline and JSON response workflow
Conceptual diagram of the educational inference workflow; not a screenshot of a running server.

HTTP methods: GET, POST and the others

HTTP is the request–response protocol used by web services. A GET request typically retrieves information, for instance GET /health or GET /model-info. A POST request sends a body for processing; our POST /predict endpoint receives six numerical inputs. Methods such as PUT, PATCH and DELETE support replacement, partial modification and deletion in suitable APIs, but are unnecessary for this read-only inference demonstration.

A prediction API could use other interface designs, but POST is natural when a request contains structured feature values and should not become part of a simple URL query. A health check should not retrain a model or modify data. Keeping each endpoint’s behaviour narrow and documented reduces confusion for both students and later software clients.

What is JSON? Learn to read a prediction request

JSON stands for JavaScript Object Notation. It represents data using values such as numbers, strings, booleans, arrays, objects and null. Curly braces enclose an object; quoted keys identify fields; colons separate keys and values; commas separate entries. A machine-learning client sends the input as JSON with the HTTP header Content-Type: application/json.

The following request describes a hypothetical property, not a verified house in Ames. The keys must match the API schema and the model’s saved feature names. The numerical values must also carry the intended units: above-ground area and basement area use square feet, not square metres.

{
  "GrLivArea": 1500.0,
  "OverallQual": 6,
  "YearBuilt": 1995,
  "TotalBsmtSF": 800.0,
  "GarageCars": 2,
  "FullBath": 2
}

HTTP status codes: what a response tells the client

Status codes explain the outcome of an HTTP request separately from the JSON body. 200 indicates a successfully processed request. 404 means a route is not found. 422 commonly indicates a FastAPI/Pydantic request-validation failure. 500 indicates an unexpected internal failure, while 503 is appropriate when a required resource is unavailable. Authentication-related codes 401 and 403 apply only when appropriate authentication and authorization are implemented.

A rate-limited service may return 429, but our basic code does not implement rate limiting, so claiming that it already returns 429 would be incorrect. Errors must not expose passwords, private server paths or internal tracebacks. The exact validation-error JSON depends on the installed FastAPI and Pydantic versions; use the working API’s documentation rather than copying outdated error formats.

StatusMeaningExample
200Successful operation/health or valid /predict
401Authentication needed or rejectedOnly with auth configured
403Forbidden for this callerAuthorization policy
404Unknown route/does-not-exist
422Invalid request bodyOverallQual = 15
429Rate limit exceededOnly with rate limiting
500Internal errorModel prediction failure
503Not readyModel unavailable

FastAPI versus Streamlit: related but different tools

Streamlit creates a user-facing interactive Python interface with forms, charts and displays. FastAPI focuses on HTTP endpoints, input/output contracts and programmatic communication between systems. Both can run Python machine-learning inference. A Streamlit frontend may send a JSON request to FastAPI, which returns a prediction; that design allows the same backend to serve multiple authorized clients.

FastAPI is not universally faster or more appropriate for every application. Flask provides a lightweight general web framework, and Django offers more extensive web application facilities. A beginner should choose according to who uses the service, how requests are made, what validation and authentication are needed, and how the application will be deployed and maintained.

Why Pydantic matters: JSON is not automatically valid model input

A JSON body can be well-formed yet unsuitable for inference. A caller might omit FullBath, send quality 15 when the range is 1–10, provide an unexpected field or pass negative area. Pydantic lets developers declare named data fields, Python types and constraints in a BaseModel. FastAPI uses that schema to validate requests and to generate interactive OpenAPI documentation.

In the accompanying project, ConfigDict(extra='forbid', allow_inf_nan=False, strict=True) rejects unknown keys and nonfinite values and uses strict numeric type validation. A decimal field is expected to be a number rather than a numeric string. The user-facing bounds are instructional guardrails; accepting each field does not guarantee that the combined input resembles real historical training observations.

Build the six-field request model

The same six fields used in Topics 91–92 are retained: GrLivArea (living area), OverallQual (ordinal quality), YearBuilt, TotalBsmtSF (basement area), GarageCars and FullBath. Pydantic’s Field lets us constrain the values and attach explanatory descriptions. Extra JSON keys are rejected so that an irrelevant or misspelled field is not silently ignored.

One limitation is that a simple numeric range check is not a full scientific input-validity assessment. A house constructed in an accepted year may still have an unusual combination of size, garage capacity and bathrooms. More advanced services may examine joint distributions and detect out-of-domain requests, but should not present such checks as guarantees of prediction accuracy.

from pydantic import BaseModel, ConfigDict, Field
class HouseFeatures(BaseModel):
    model_config = ConfigDict(
        extra="forbid", allow_inf_nan=False, strict=True
    )
    GrLivArea: float = Field(ge=300, le=6000)
    OverallQual: int = Field(ge=1, le=10)
    YearBuilt: int = Field(ge=1800, le=2010)
    TotalBsmtSF: float = Field(ge=0, le=6000)
    GarageCars: int = Field(ge=0, le=5)
    FullBath: int = Field(ge=0, le=4)
# Request example uses 1500.0 and 800.0 for float fields.

Response models: make output structure predictable

A PredictionResponse Pydantic model declares prediction_usd, model_version, units and disclaimer. The endpoint’s response_model helps FastAPI validate and document successful outputs. It avoids returning arbitrary NumPy objects or unrelated internal metadata to clients.

For classroom discussion, a fictional response might contain prediction_usd: 245000.0, version 1.0.0, units Historical USD and a warning that the estimate is educational. That number is not an output generated by a verified Ames model. The actual service must return only whatever its trusted model predicts after successful model training and a real request.

Train the Scikit-learn model offline first

The source dataset is OpenML 42165, Ames Housing, commonly documented as 1,460 historical sales with SalePrice as the target. Our six inputs are a deliberately limited numerical subset to make the API beginner-friendly. The project training script checks required columns and target validity, reserves an 80/20 test split with seed 93, and performs five-fold KFold cross-validation using only development data.

It fits a median-imputation Pipeline followed by RandomForestRegressor(n_estimators=100, min_samples_leaf=2, random_state=93, n_jobs=1), and compares held-out performance against a median-only DummyRegressor. It calculates mean CV MAE, baseline test MAE, model test MAE and R². With the expected complete source, the split gives 1,168 training/development rows and 292 test rows. Real results cannot be reported until OpenML retrieval and training actually succeed.

Model evaluation before serving requests

MAE, or Mean Absolute Error, is the average of the absolute differences between actual and predicted prices. Suppose a fictional model has absolute errors of $10,000, $15,000, $10,000, $15,000 and $5,000 for five properties; then total absolute error is $55,000 and MAE equals $11,000. This is arithmetic practice, not an Ames result. R² compares squared prediction error with a constant mean-based reference on the evaluated set, and a negative test R² is possible.

An API that runs without crashing is not automatically statistically useful. Model validation and independent final evaluation must come before broad distribution. Users should not see “95% confidence” or a guaranteed valuation interval that was never estimated or calibrated. Historical real-estate data also do not establish present-day prices in other countries or markets.

Save the complete fitted preprocessing Pipeline

The training script creates both model/ames_model.joblib and model/model_metadata.json after genuine model fitting. Saving the entire Pipeline is important because the forest expects the same imputed feature representation used during training. Saving only the Random Forest and independently reconstructing preprocessing in the API could produce subtle mismatches.

Joblib uses pickle-based mechanisms. Loading untrusted Joblib objects can execute arbitrary Python code: never accept random user-uploaded model files for deserialization. The script reloads only its own newly saved trusted artifact and compares predictions before and after reloading. It records a SHA-256 digest, model versions and feature names so the serving process can detect unexpected changes relative to the metadata.

Checksums, provenance and version compatibility

A SHA-256 digest summarizes the model file’s bytes. On startup, the API computes the file’s digest and compares it with the digest recorded at training time. If they differ, startup fails. This helps detect altered files, but a matching hash does not independently authenticate an artifact if an attacker can replace both the binary and metadata. Control file provenance and permissions first.

Scikit-learn does not support arbitrary cross-version loading of its serialized estimators. Our API verifies that the saved Scikit-learn version matches the current runtime; the metadata also records Python and numerical package versions for compatibility review. A project may still require further environment checks and integration tests even when the Scikit-learn version matches. Do not bypass incompatible artifacts merely to make the server start.

FastAPI lifespan: load shared resources once

The FastAPI lifespan facility uses an async context manager to perform startup and shutdown work. The application loads and verifies the trusted model once during startup, stores it on app.state, serves requests from that state and cleans up when shutting down. This is preferred to recreating a fitted model for every prediction. It also makes a missing or invalid artifact an explicit deployment failure instead of a silent source of nonsense output.

The project intentionally fails startup if the expected Ames files are absent. That is why its model-dependent tests remain skipped here: the real source data could not be loaded to create an artifact. A process that fails its required startup checks is not described as a running model API with a merely unsuccessful prediction endpoint.

Four essential endpoints for a beginner API

The API contains four narrowly defined routes. GET /health responds with a simple process-level liveness message. GET /ready checks whether the fitted model is available and may produce HTTP 503 otherwise. GET /model-info exposes safe, deliberately selected metadata: model name, feature list, intended use, version and historical evaluation MAE. POST /predict receives validated JSON, builds a correctly ordered DataFrame, and returns a structured historical estimate.

The distinction between health and readiness matters: a server process may respond to networking checks while the prediction resource is unavailable. In this simple implementation an untrusted model prevents startup entirely, so cloud orchestration may not receive either endpoint. Production systems may support more sophisticated startup/readiness behaviour; avoid claiming the classroom example covers every failure mode.

Four FastAPI routes: health, ready, model information and predict
Original conceptual endpoint overview; not a captured Swagger UI session.

How the prediction route preserves the training schema

The Pydantic request becomes a dictionary using model_dump(). The service verifies the expected feature schema and constructs pd.DataFrame([values], columns=FEATURES). It passes this DataFrame to the saved Pipeline, which applies its fitted imputer and Random Forest. The output is converted to a regular Python float, checked for finiteness and positive value, and rounded for JSON display.

Preserving names and ordering avoids a critical bug: if a bare positional array mistakenly places a construction year into the living-area column, a model can produce an apparently plausible but meaningless output. The API doesn’t let the caller choose a file path or model class. Unexpected exceptions are logged for maintainers and turned into a generic HTTP 500 response without publishing internal details.

Run the API with Uvicorn during local development

Uvicorn is an ASGI server that can run FastAPI. After genuine Ames training, install project dependencies and start the local development server with uvicorn app.main:app --host 127.0.0.1 --port 8000 --reload. The module path identifies app/main.py and the object named app. The --reload flag is useful during development, not a recommended production setting.

On a typical local environment the browser documentation appears at http://127.0.0.1:8000/docs, alternative ReDoc at /redoc, and the OpenAPI schema at /openapi.json. These are local URLs, not public internet deployments. This manuscript does not claim a verified running Ames API or show a fabricated Swagger screenshot.

python -m venv .venv
python -m pip install -r requirements-dev.txt
# Only with verified Ames download/network access:
python train_model.py
python -m pytest -q
uvicorn app.main:app --host 127.0.0.1 --port 8000 --reload
# Then open http://127.0.0.1:8000/docs

Swagger UI and OpenAPI: automatically documented contracts

FastAPI can generate an OpenAPI document from route decorators, Pydantic request bodies, response models and descriptions. Swagger UI offers an interactive view where students can expand POST /predict, inspect field constraints, enter the six-feature JSON, execute a request and inspect the returned HTTP status and body. This helps learners understand the contract without first writing a separate client.

The docs are only as accurate as the declarations and implementation. They do not guarantee a model is secure, fair or correct. Students should also test missing fields, out-of-range values and unknown keys. For an authentic screenshot, capture the real working UI after completing local training rather than generating an imagined browser screenshot.

Call the endpoint from a terminal using cURL

On a POSIX-style shell, cURL can send a JSON request containing the six property measurements. The HTTP method is POST, the address targets the prediction route, and the Content-Type header says the body is JSON. The server responds only if the trusted model has been trained and loaded successfully. This request’s input describes a fictional example house.

PowerShell has different quoting conventions, and some Windows environments alias curl to another command. The companion API reference includes a native Invoke-RestMethod example so Windows learners can use the equivalent JSON request without relying on POSIX shell syntax.

curl -X POST "http://127.0.0.1:8000/predict" \
  -H "Content-Type: application/json" \
  -d '{"GrLivArea":1500.0,"OverallQual":6,
       "YearBuilt":1995,"TotalBsmtSF":800.0,
       "GarageCars":2,"FullBath":2}'

Use a Python HTTP client to request predictions

The HTTPX library lets another Python program call the API. The client constructs a payload, sends it with httpx.post(..., json=payload, timeout=10.0), calls raise_for_status() and then interprets response.json(). Errors should be handled intentionally: a 422 input error is usually corrected in the client, while server errors or timeouts may need retry decisions, logging or a user-facing message.

Do not keep retrying a malformed request or assume every failed response contains a prediction. Never hardcode access credentials into a public notebook. A network call can fail even when the model is valid because the server is offline or the network is interrupted.

import httpx
payload = {
    "GrLivArea":1500.0, "OverallQual":6,
    "YearBuilt":1995, "TotalBsmtSF":800.0,
    "GarageCars":2, "FullBath":2
}
response = httpx.post(
    "http://127.0.0.1:8000/predict", json=payload, timeout=10.0
)
response.raise_for_status()
print(response.json())  # Only when a real server is running

Optional Postman API testing

Postman is another tool for sending HTTP requests. Students can create a request, select POST, enter the running local URL, choose a raw JSON body, paste the six fields and inspect the HTTP status and response. Replacing OverallQual with 15 or removing a required field should reveal request validation behaviour. It is fine to rely on FastAPI’s Swagger UI and HTTPX instead of installing an additional program.

A client testing tool does not prove the model generalizes. Keep a separate record of evaluated model performance and API input/output correctness. An authentic screenshot should show a successful request made against the actual fitted model, not a JSON response manually fabricated to decorate a report.

How automated tests protect the API contract

The project includes pytest-based input-schema tests for valid values, missing fields, unexpected keys, invalid areas, invalid quality and nonfinite numbers. It also includes TestClient endpoint tests that exercise the FastAPI lifespan as a context manager. The endpoint checks verify liveness, readiness, model information, a valid prediction, multiple 422 failures, a 404 route and OpenAPI availability—once the real fitted artifact exists.

In this environment six schema tests passed and two endpoint tests were skipped because there was no genuine Ames model. Skipped is not passed. After training on a connected computer, rerun python -m pytest -q, confirm those tests execute rather than skip, and include an independent check that the API prediction agrees with the same saved Pipeline for the same labelled input DataFrame.

Read a 422 error rather than hiding it

Suppose the client sends OverallQual: 15 while the request schema allows only 1–10. FastAPI normally returns a 422 validation error with details identifying the rejected field and constraint. An extra key is also rejected because extra='forbid' is set. These errors tell a client what must be corrected before inference; they are not unexpected server failures.

A validation failure should not produce a randomly substituted value or a guessed prediction. Nor should a developer force every failure to status 400, which obscures the difference between invalid inputs and internal problems. The actual error representation should be inspected in the installed FastAPI/Pydantic version.

Logging and observability without exposing private data

Application logs can help maintainers diagnose startup failures, invalid request rates, endpoint availability, model-version changes and unexpected prediction exceptions. The example uses Python logging to record prediction exceptions without returning their stack traces to the client. For a public deployment, logs should avoid raw requests, identifying information, passwords, API keys and tokens whenever unnecessary.

Operational logs are not the same as model accuracy monitoring. A server can be fast and available while its predictions are wrong. To measure real-world accuracy after deployment, the organization would need appropriately collected actual outcomes and a justified evaluation plan. Simple learning demos often have no ongoing ground-truth feedback and should state that limitation.

Synchronous predictions and asynchronous APIs

A synchronous Python def prediction route is appropriate for a simple Scikit-learn call because it performs ordinary computational work. FastAPI runs synchronous route functions using its threadpool mechanisms in common setups. Declaring the same CPU-bound prediction function async def does not automatically make the numerical work nonblocking or faster.

More advanced systems consider concurrency limits, process workers, queueing, memory usage and thread safety. A hundred large simultaneous model calls may require a different serving architecture than a classroom API. Keep the fitted model read-only during prediction, measure performance, and scale only when actual requirements justify it.

API authentication, authorization and secure secrets

An educational local API on a private laptop can run without authentication. A publicly reachable API needs a documented security decision: who is allowed to call it, how often, what costs or risks arise, and whether the endpoint should be publicly accessible. Authentication verifies caller identity or credentials; authorization decides what an authenticated caller may do. API keys, bearer tokens and OAuth-related methods support different use cases.

The simple project does not pretend to implement enterprise-grade security. Do not commit secrets to GitHub or embed secret API keys in public WordPress JavaScript. Use environment-based secret storage on a compatible host, HTTPS for protected traffic, least privilege, operational monitoring, and rate limits or network restrictions if relevant. A secret placed in a browser-visible script is no longer secret.

CORS is a browser control, not a substitute for authentication

Cross-Origin Resource Sharing (CORS) lets a server declare which web origins may make certain browser-mediated cross-origin requests. If a Notes for SHS page calls a FastAPI endpoint hosted elsewhere, browsers may require an appropriate CORS configuration. The supplied project explicitly allows the Notes for SHS live and staging origins for browser requests; it does not allow credentials and only lists necessary methods and the Content-Type header.

An explicit CORS list does not prevent a server-to-server caller from sending requests directly; it is not authentication or a general firewall. Do not assume restricting allowed origins makes a public model API safe from misuse. If real authentication is added, configure origins, headers and credential handling deliberately and test them from the actual front end.

Rate limiting and resource protection

An unprotected public prediction endpoint can be called repeatedly by automated scripts, potentially exhausting CPU, causing downtime or increasing hosting costs. A suitable gateway, reverse proxy or application-specific limiter may set request budgets and return 429 when a limit is exceeded. The educational implementation does not include a working rate limiter; therefore it does not promise HTTP 429 responses.

Before exposing an API to the internet, consider rate limits, maximum payload size, authentication or IP controls, workload limits, abuse monitoring and cost alerts. Different providers offer different mechanisms, so test the particular configuration rather than copying generic security claims.

API versioning and compatibility

An API contract specifies the endpoint, required fields, accepted types, response structure, errors and prediction meaning. Renaming prediction_usd or changing GrLivArea units could break existing clients. A future endpoint such as /v1/predict can make compatibility decisions explicit. An API version and a model version are related but not identical: the contract might remain stable while a new verified model replaces the old one.

The current lesson keeps the simple route /predict and labels the documented model version. When changing the model, update its metadata, recompute its trusted artifact checksum, rerun evaluation, verify feature compatibility and test clients before release. Avoid silently changing the meaning of historical dollar predictions.

Docker: package the API and its dependencies

Docker packages an application and dependencies into an image that can run as a container on compatible hosts. The supplied Dockerfile starts from a Python 3.12 slim image, installs declared runtime packages, copies the application and trusted model files, creates a non-root user, exposes port 8000 and starts Uvicorn. A Docker image can improve environmental consistency, but it does not automatically supply a secure network, correct model or reliable public uptime.

Only build the image after actual Ames training has produced and verified the artifacts. The model directory in this ZIP is intentionally empty; a built container without the real model cannot serve valid predictions. Docker was not available for a verified build in this task, so the Dockerfile is supplied for students to test, not reported as a successfully deployed container.

FROM python:3.12-slim
WORKDIR /code
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt \
    && useradd --create-home appuser
COPY app ./app
COPY model ./model
USER appuser
EXPOSE 8000
CMD ["uvicorn","app.main:app","--host","0.0.0.0","--port","8000"]

Docker build, run and port mapping

After successful local verification, docker build -t fastapi-ml-demo . creates an image from the Dockerfile. docker run --rm -p 8000:8000 fastapi-ml-demo maps container port 8000 to port 8000 on the developer’s computer. Only then should students open http://127.0.0.1:8000/docs and test requests. This is still local execution, not internet publication.

The project includes .dockerignore and .gitignore files to avoid copying caches, local virtual environments and common secret files. They are not a substitute for reviewing the actual files committed to a repository. Docker security also involves trusted base images, vulnerability updates, least-privilege permissions, TLS termination and host configuration.

Deploy to a compatible host using HTTPS

FastAPI can run on a VPS, managed Python web-service platform or compatible container host. The exact procedure depends on the provider’s current capabilities, account permissions, pricing, domain and networking. A reverse proxy or hosting platform often terminates HTTPS and forwards requests to a Uvicorn process. HTTPS protects data in transit when implemented correctly; it does not replace authentication or application-layer validation.

Streamlit Community Cloud is designed for Streamlit apps and should not automatically be treated as a general-purpose FastAPI server. This project has no authorized external API host attached and no public service was deployed. The completed deployment checklist describes how to test actual hosted /health, /ready, /model-info and /predict responses after deployment, without inventing a URL.

Monitoring, drift and responsible updates

Monitoring combines software signals—availability, errors, request latency, CPU/memory and model version—with appropriate modelling signals. Data drift means incoming feature distributions change from those used during training. Concept drift refers to changes in the relationship between inputs and the target. Changes do not necessarily prove immediate performance collapse, but they prompt investigation. Measuring predictive accuracy after release generally requires observed outcomes.

For a historical six-feature education service, privacy-preserving error counts may be enough; collecting precise visitor addresses or identifying characteristics is unnecessary. Avoid storing raw visitor payloads by default. When releasing a new model, repeat validation, document dataset changes, update metadata and checksum, run API contract tests, and retain an appropriate rollback option.

Connect the API to Streamlit or WordPress

A verified FastAPI endpoint can serve a Streamlit interface through an HTTP request, letting the human-facing form remain separate from prediction logic. The Streamlit app should validate inputs locally, send the exact six fields, manage timeouts and display server errors in understandable terms. It must not treat a 422 response as a valid price.

A WordPress frontend could also call a hosted API, subject to HTTPS, CORS and appropriate public-access safeguards. If secret authentication is required, do not put the credential in client-side JavaScript. Prefer a controlled server-side integration where feasible. Because no real FastAPI hosting endpoint exists yet, this article intentionally does not include a fake “Try the live API” button.

Why AI responsibility still matters when the API is technically correct

A correctly written service can nevertheless expose a historically limited or biased model. Our dataset comes from past housing sales in one United States city and omits many market and property characteristics. Predictions should not be presented as current property values or automatically used for lending, investment, housing discrimination or financial decisions. Document the intended educational purpose and known limitations.

For student performance or healthcare models, additional privacy, authorization, fairness and human oversight would be necessary. Neither Pydantic validation nor SHAP-style explanations establish scientific or ethical suitability. Software correctness, statistical generalization, fairness and lawful operation are separate questions.

Ten-task capstone: from model to API service

Task 1: inspect and verify OpenML 42165. Task 2: select six numerical features and define the target. Task 3: train and evaluate the median-imputation Random Forest using training-only five-fold CV and held-out testing. Task 4: save the trusted full Pipeline and metadata. Task 5: build a Pydantic request model rejecting missing, extra and invalid fields.

Task 6: create FastAPI lifespan and four endpoints. Task 7: verify Swagger UI, valid and invalid JSON requests, and consistent model inference. Task 8: run the entire pytest suite and record actual results. Task 9: verify a Docker image and assess security, HTTPS, authentication and rate limiting before any public release. Task 10: deploy only with an authorized host, check real endpoint responses, and write a report on model quality, API behaviour, limitations and monitoring.

Thirty original practice questions with worked answers

Question 1: What does API stand for?

Worked answer: Application Programming Interface.

Question 2: Does every API have a visible website interface?

Worked answer: No. Many APIs are intended for program-to-program communication.

Question 3: What is a client?

Worked answer: Software that sends a request to a service.

Question 4: What is JSON?

Worked answer: A lightweight structured data format with objects, arrays and basic value types.

Question 5: What is a REST API?

Worked answer: A service using a resource-oriented architectural style; JSON and POST alone do not guarantee full REST compliance.

Question 6: Which method is used for this model’s prediction request?

Worked answer: POST /predict.

Question 7: Which method reads the model information?

Worked answer: GET /model-info.

Question 8: What does HTTP 422 indicate here?

Worked answer: A request failed validation, such as out-of-range quality or missing required fields.

Question 9: Does the basic code already implement HTTP 429?

Worked answer: No. It requires a configured rate limiter.

Question 10: What does Pydantic BaseModel do?

Worked answer: It declares a structured schema and validates fields.

Question 11: Why forbid extra JSON keys?

Worked answer: To reject unsupported or misspelled fields rather than ignore them silently.

Question 12: What is the target of Ames regression?

Worked answer: SalePrice, the historical recorded sale price.

Question 13: Name the six inputs.

Worked answer: GrLivArea, OverallQual, YearBuilt, TotalBsmtSF, GarageCars and FullBath.

Question 14: Why save an entire Pipeline?

Worked answer: It preserves the fitted preprocessing and model together.

Question 15: What does a test split of 20% of 1,460 yield?

Worked answer: 292 test records, assuming all 1,460 are retained.

Question 16: What is the development size for the same split?

Worked answer: 1,168 records.

Question 17: Compute MAE for absolute errors 10k, 15k, 10k, 15k and 5k.

Worked answer: 55k/5 = $11,000, a fictional mathematics example.

Question 18: Does a matching SHA-256 prove a Joblib file safe?

Worked answer: No. It does not authenticate a file if the metadata can also be forged.

Question 19: What is a FastAPI lifespan context manager used for?

Worked answer: Loading and cleaning up shared resources at application startup and shutdown.

Question 20: Why does the API fail startup without a trusted model?

Worked answer: It must not return fabricated or unverified predictions.

Question 21: What does /health measure?

Worked answer: Basic process responsiveness or liveness.

Question 22: What does /ready measure?

Worked answer: Whether the API’s prediction model resource is ready.

Question 23: What does OpenAPI describe?

Worked answer: Routes, methods, schemas and related API contract information.

Question 24: Where is Swagger UI usually found on the local server?

Worked answer: At /docs under the running FastAPI service.

Question 25: What does TestClient do?

Worked answer: Exercises API routes in tests without an external network server.

Question 26: Why use TestClient as a context manager?

Worked answer: So application lifespan startup and shutdown execute during tests.

Question 27: Is CORS the same as authentication?

Worked answer: No. It governs browser cross-origin behaviour, not caller authorization.

Question 28: What is the purpose of HTTPS?

Worked answer: Protecting HTTP traffic in transit when configured correctly.

Question 29: Does building a Docker image publish an API?

Worked answer: No. A container must be hosted and its URL verified separately.

Question 30: What proves that Topic 93’s API is publicly deployed?

Worked answer: A real accessible URL and successful authenticated or permitted endpoint smoke tests. None is available yet.

Four-week roadmap to a model-serving portfolio project

Week 1—Foundations: practise JSON, clients, servers, HTTP methods and status codes, then create the six-field Pydantic schema. Week 2—Model and application: obtain the authentic dataset, train and evaluate the Pipeline, serialize it safely, add metadata and implement lifespan and endpoints.

Week 3—Testing and security: run pytest, Swagger requests, cURL and HTTPX; investigate failed inputs and review CORS, authentication choices, secrets and logs. Week 4—Deployment: verify Docker, choose an authorized host, configure HTTPS and access controls, test the actual URL and write the capstone report with limitations and monitoring expectations.

Frequently asked questions

What is FastAPI used for?

Building Python HTTP APIs and related services with type-aware validation and generated API documentation.

Can I serve a Scikit-learn model with FastAPI?

Yes. Load a trusted fitted Pipeline at startup and call predict on validated inputs.

What is the difference between FastAPI and Streamlit?

FastAPI primarily exposes programmatic endpoints; Streamlit provides a Python-driven human-facing web interface.

Do I need Pydantic?

It is a practical way to declare and validate FastAPI request bodies; this project uses Pydantic v2.

Does FastAPI automatically train machine learning models?

No. This project trains offline and loads a fitted artifact for inference.

What is the role of Uvicorn?

It is an ASGI server that runs the FastAPI application.

Why is the saved model missing from the project ZIP?

The authentic Ames dataset could not be retrieved, so no verified model was generated.

Can I trust a downloaded Joblib file?

Not by default. Loading an untrusted pickle-based artifact can execute code.

Why can the API return 422?

The JSON body violates the declared Pydantic schema.

Why does /ready differ from /health?

A process may respond while the required model is unavailable.

Can a WordPress page call FastAPI?

Yes, when hosted with appropriate HTTPS, CORS and authentication or server-side integration.

Is Docker mandatory?

No, but it is a useful packaging and portability option for compatible hosts.

Is the prediction response shown in this tutorial real?

No. Any illustrated dollar amount is explicitly fictional; actual results require a trained model.

Does API availability prove model quality?

No. Evaluation and deployment reliability are distinct.

Is a public FastAPI URL available for this project?

No. No authorized public deployment has been completed or verified.

Trusted learning references and related Notes for SHS topics

For technical details see FastAPI documentation, lifespan events, TestClient testing, CORS, container deployment, Pydantic, Scikit-learn persistence and OpenML 42165. Review official documentation for the package version in use.

Follow the progression from Topic 92: Streamlit Model Deployment to Topic 91: Explainable AI, Topic 90: Feature Engineering and Topic 63: Model Evaluation. Each addresses a different problem in the machine-learning lifecycle.

Conclusion: reliable machine learning APIs require more than a route

FastAPI gives beginners a clear way to expose a model to other programs. Pydantic checks input contracts, application lifespan loads a trusted fitted Pipeline, endpoint routes distinguish status and prediction operations, and automated tests help identify errors. A container can make installation more reproducible, while HTTPS, authentication decisions, logging safeguards and operational monitoring become essential when a service is publicly accessible.

The most important distinction is between code that has been written, code that has actually been tested, and a prediction service that has genuinely been deployed. This article provides verified validation tests and full offline training and serving source, but no fabricated Ames model or live URL. Finish the authentic training and endpoint checks before making broader claims. A credible beginner engineer reports limits with the same care used to write code.

Student resources: Download the companion project ZIP from the article completion report. It includes complete offline training and FastAPI code, six-field schema, Pydantic tests, TestClient endpoint checks, Dockerfile, dependency lists, API reference, security and deployment checklists, model card, original conceptual diagrams and a reproducible README. It intentionally does not contain an invented model artifact, fabricated training scores or a public server URL.