Building the backend - Part II (Live tweet sentiment analysis)

Part I | Part II | Part III

In the previous article, I explained how to build a sentiment classifier. Read it here. I this, we'll create the backend to serve predictions via an API.

Building the API

make sure you're in the backend folder



import nltk
import uvicorn
import utils as utils
from fastapi import FastAPI
from pydantic import BaseModel
from classify import remove_noise
from nltk.tokenize import word_tokenize

app = FastAPI()
classifier = utils.load_model()

class Tweet(BaseModel):
    tweet: str

def read_root():
    return {"message": "Welcome to sentiment classifier API"}"/api")
def analyse_tweet(tweet: Tweet):
    custom_tokens = remove_noise(word_tokenize(tweet.tweet))
    result = classifier.classify(dict([token, True] for token in custom_tokens))
    return {"sentiment": result}

if __name__ == "__main__":"server:app", host="", log_level="info")

This is similar to the other articles where I showed how to build APIs using FastAPI. Only change is that, In the previous ones, we launched the server using uvicorn main: app, here we're doing it programmatically. This way we can run the server using python

Dockerize the API

FROM python:3.8-slim


COPY requirements.txt .

RUN pip install -r requirements.txt

COPY . .

RUN python3 -m nltk.downloader punkt
RUN python3 -m nltk.downloader wordnet
RUN python3 -m nltk.downloader stopwords
RUN python3 -m nltk.downloader averaged_perceptron_tagger


CMD ["python3", ""]

Build and run the image

docker built -t sentwitter-backend .
docker run -d -p 8000:8000 setwitter-backend

Test the API

❯ docker run -d -p 8000:8000 sentwitter_backend

❯ curl http://localhost:8000
{"message":"Welcome to sentiment classifier API"}

❯ curl -X POST "http://localhost:8000/api" -H  "accept: application/json" -H  "Content-Type: application/json" -d "{\"tweet\":\"I hate you\"}"
{"sentiment": "Negative"}

We have successfully built the backend. In the next article, we'll build a frontend that retrieves tweets and sent to the backend for prediction.


No Comments Yet