Returning structured output from API
You're building a content moderation system where you need to define a POST endpoint to test a pre-trained sentiment analysis model on user comments.
You need to create an endpoint that leverages pydantic
models to return predictions in a structured format.
Note: Pydantic models - CommentRequest
and CommentResponse
are already created for you to use along with the pre-trained sentiment_model
from pre-defined SentimentAnalyzer
class.
This exercise is part of the course
Deploying AI into Production with FastAPI
Exercise instructions
- Implement a
POST
endpoint at route/analyze
. - Validate the
request
in theanalyze_comment()
function as per theCommentRequest
. - Make predictions using
sentiment_model
by passing therequest
'stext
. - Return the prediction attributes (
text
fromrequest
,"label"
and"score"
fromresult[0]
) to format the outgoing response inCommentResponse
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create a POST request endpoint
@app.____("/analyze")
# Capture the request text for validation as per CommentRequest model
def analyze_comment(____: CommentRequest):
try:
# Specify pass the request text to the model
result = sentiment_model(____.____)
# Specify the result attributes to complete the comment response
return CommentResponse(text=____,
sentiment=____,
confidence=____)
except Exception:
raise HTTPException(status_code=500,
detail="Prediction failed"
)