FastAPI helps you quickly share your machine learning model so others can use it easily through the internet.
FastAPI for model serving in ML Python
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class InputData(BaseModel): feature1: float feature2: float @app.post('/predict') async def predict(data: InputData): # Use your model here prediction = data.feature1 + data.feature2 return {'prediction': prediction}
Use @app.post to create a POST endpoint where you send data.
Define input data with BaseModel to check data types automatically.
from fastapi import FastAPI app = FastAPI() @app.get('/') async def root(): return {'message': 'Hello World'}
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class InputData(BaseModel): age: int income: float @app.post('/predict') async def predict(data: InputData): score = data.age * 0.1 + data.income * 0.01 return {'score': score}
This program creates a FastAPI app with one POST endpoint '/predict'. It takes two numbers, adds them, and returns the result as prediction.
Run this code, then send a POST request with JSON like {"feature1": 3.5, "feature2": 2.5} to get prediction 6.0.
from fastapi import FastAPI from pydantic import BaseModel import uvicorn app = FastAPI() class InputData(BaseModel): feature1: float feature2: float @app.post('/predict') async def predict(data: InputData): # Simple model: sum of features prediction = data.feature1 + data.feature2 return {'prediction': prediction} if __name__ == '__main__': uvicorn.run(app, host='127.0.0.1', port=8000)
Use tools like curl or Postman to send POST requests to your FastAPI server.
FastAPI automatically creates interactive docs at /docs to test your API.
Keep your model loading outside the endpoint function to avoid reloading on every request.
FastAPI makes it easy to share your ML model as a web service.
Define input data clearly with Pydantic models for safety and clarity.
Use POST endpoints to send data and get predictions back in JSON format.
Practice
Solution
Step 1: Understand FastAPI's role
FastAPI is a web framework used to build APIs that can serve machine learning models.Step 2: Identify the main use in ML serving
It allows sending input data and receiving predictions via HTTP requests, making models accessible.Final Answer:
To create a web service that allows users to send data and get model predictions -> Option AQuick Check:
FastAPI serves ML models as web APIs = D [OK]
- Confusing FastAPI with training libraries
- Thinking FastAPI is for data storage
- Assuming FastAPI is for data visualization
Solution
Step 1: Recall HTTP methods for sending data
POST is used to send data to the server, suitable for prediction requests.Step 2: Match method to FastAPI syntax
FastAPI uses @app.post decorator to define POST endpoints.Final Answer:
app.post('/predict') -> Option AQuick Check:
POST endpoint for sending data = app.post [OK]
- Using GET instead of POST for sending input data
- Confusing HTTP methods like PUT or DELETE
- Missing the @ decorator syntax
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class InputData(BaseModel):
text: str
@app.post('/predict')
def predict(data: InputData):
return {"length": len(data.text)}Solution
Step 1: Understand input and output
The input JSON has "text": "hello". The function returns the length of this string.Step 2: Calculate length of 'hello'
"hello" has 5 characters, so the output JSON is {"length": 5}.Final Answer:
{"length": 5} -> Option CQuick Check:
len('hello') = 5 [OK]
- Returning the string instead of its length
- Confusing keys in the output JSON
- Expecting a syntax or runtime error
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class InputData(BaseModel):
value: int
@app.post('/predict')
def predict(data: InputData):
return {"result": data.value * 2}
# Client sends JSON: {"value": "10"}Solution
Step 1: Check data type in Pydantic model
InputData expects 'value' as int, client sends string "10".Step 2: Understand Pydantic validation and coercion
Pydantic automatically converts compatible strings like "10" to int 10, so no validation error occurs.Final Answer:
No error, code works fine -> Option DQuick Check:
Pydantic coerces "10" to 10 [OK]
- Thinking Pydantic doesn't auto-convert string to int
- Expecting a type validation error
- Overlooking Pydantic's coercion feature
Solution
Step 1: Define input for multiple texts
Since the model expects multiple texts, input should be a list of strings, best defined with Pydantic List[str].Step 2: Define output for multiple scores
The model returns multiple sentiment scores, so output should be a list of floats matching input size.Final Answer:
Use a Pydantic model with a field 'texts' as List[str] and return List[float] -> Option BQuick Check:
Input/output types match model expectations [OK]
- Using single string input for multiple texts
- Returning single score instead of list
- Using query params for large input lists
Ready to prove it?
Pass the test and this pattern moves unknown
