Let’s create a really simple FastAPI with, create yourself our app file (app.py) and requirements file (requirements.txt).
We’re going to use TextBlob to process our text.
In the requirements.txt add the following
fastapi uvicorn textblob
In the app.py add the following imports
from fastapi import FastAPI from textblob import TextBlob
Now let’s create the FastAPI and a POST endpoint named sentiment, the code should look like this
@app.post("/sentiment")
def analyze_sentiment(payload: dict):
text = payload["text"]
blob = TextBlob(text)
polarity = blob.sentiment.polarity
subjectivity = blob.sentiment.subjectivity
return {
"polarity": polarity,
"subjectivity": subjectivity
}
Don’t forget to run pip install
pip install -r requirements.txt
or if you’re using PyCharm, let this install the dependencies.
Run the app using
uvicorn app:app --reload
Note: as we’re using FastAPI we can access the OpenAPI interface using http://localhost:8000/docs
Now from curl run
curl -X POST http://localhost:8000/sentiment -H "Content-Type: application/json" -d '{"text": "I absolutely love this!"}'
and you’ve see a result along the following lines
{"polarity":0.625,"subjectivity":0.6}
Polarity is within the range [-1.0, 1.0], where -1.0 is a very negative sentiment, 0, neutral sentiment and 1.0 very positive sentiment. Subjectivity is in the range [0.0. 1.0] where 0.0 is very objective (i.e. facts or neutral statements) and 1.0 is very subjective (i.e. opinions, feelings or personal judgement).