Get startedGet started for free

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

View Course

Exercise instructions

  • Implement a POST endpoint at route /analyze.
  • Validate the request in the analyze_comment() function as per the CommentRequest.
  • Make predictions using sentiment_model by passing the request's text.
  • Return the prediction attributes (text from request, "label" and "score" from result[0]) to format the outgoing response in CommentResponse.

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"
        )
Edit and Run Code