Unparalleled suite of productivity-boosting Web APIs & cloud-based micro-service applications for developers and companies of any size.


How To Automatically Discover The Emotions In Tweets With Python

blog Banners apilayer text to emotion api

What is the Text to Emotion API, and how does it help you automate your work?

Human beings can easily perceive emotions from any text and experience them naturally. But, what about the machines? Can they detect the emotions from a text as we do? Here is where Text to Emotion API will help you!

You might be thinking of building your own NLP solutions to detect emotions from any given text automatically. But, as we know, creating and training our NLP apps might be expensive and high-effort work (no need to mention handling the messy text you want to analyze).

Text to Emotion API lets you automatically find the appropriate emotions embedded in the text data using a few lines of code and a simple API. And the best of it, Text to Emotion API is equipped with a pre-trained model. It is straightforward and beginner-friendly; it doesn’t even need prior NLP knowledge.

Text to Emotion API was built and maintained by apilayer, an Austrian technology company. You can browse all our products to learn more about us and our variety of reliable programming interfaces, and the affordable APIs we make for developers and startups.

What is Emotion Detection, and how is it different from sentiment analysis?

Sentiment Analysis helps you understand the polarity of a given text by labeling them as positive, negative, or neutral. Emotion detection takes it to a more granular level by revealing the real emotions that the user feels while typing their content. For example, Sentiment Analysis will categorize anger and fear as negative sentiments, but they require different communication approaches.

Look at our Sentiment Analysis API if it is more suitable for your needs.

What are the common industrial implementations of Emotion Detection API?

The API is mostly useful for the following industrial use cases:

  • Customer Engagement: The signals that the text will provide to emotion API can help customer services teams to understand and interact with their clients more appropriately. It helps to speed up the process of understanding customer needs and complaints.
  • Customer support with chatbots: Chatbots help companies to provide 24-hour support to their users. By enabling emotion detection, chatbots will provide more human-like interaction, which will help increase customer satisfaction.
  • Social Media Monitoring: Keeping a close eye on the social media posts will help brands take action before minor problems happen to be a crisis.

How does the Text to Emotion API work?

Text to Emotion API uses complex NLP algorithms to mine underlying emotions from a given text. The following are the default flow of how Text to Emotion API works:

  • It removes the unwanted textual part from the message.
  • Perform the natural language processing techniques.
  • Bring out the well-pre-processed text from the text pre-processing.
  • API finds the appropriate words that express emotions or feelings.
  • Check the emotion category of each word.
  • Store the count of emotions relevant to the words found.

The endpoint output is a JSON dictionary with keys as emotion categories (happy, surprise, angry, sad, fear) and values as emotion scores. The score is a value between 0.00 to 1.00. The higher the value, the more likely our text expresses that emotion.

How to get started with Text to Emotion API?

How to get API Access Key & do Authentication?

First, create your apilayer account, and sign in.

Browse our API Marketplace with 69 powerful APIs, go straight to the AI & Machine Learning section, and choose Text to Emotion API.

apilayer machine learning APIsSubscribe for free, choose your subscription plan, or contact us here if you have a customized plan on your mind.

subscription successful

Next, go to your account dashboard to get your API key. Text to Emotion API authenticates requests with API keys. On the account page, you can view and manage your API keys.

All requests made to the API must hold a custom HTTP header named “apikey”. Implementation differs with each programming language, and in this post, we will talk about Python implementation.

You must make all API requests over HTTPS. Calls made over plain HTTP will fail. API requests without authentication will also fail.

What are the Emotion Detection endpoints available via the API?

POST method 

Use the POST method to discover the emotions in textual messages.

The following is the parameter for sending POST request:

Object Description
body (required)

Text to perform emotion analysis

Location: Body, 

Data Type: string

Basic cURL example

Run this simple cURL command to perform the text to emotion analysis on the famous speech from Hamlet (W.Shakespeare):

curl On Hamlet speech

Great! It is a complicated and emotional speech, but the API is capable of showing the mixed feelings of Prince Hamlet.

Basic cURL example for handling text with emojis

Run this simple cURL command to perform the text to emotion analysis on text with emojis:

curl Text With Emojis

The API can identify the emotion from the emojis which describe human behavior. How do we know it? Textually, there is a chance of the text being a joke, but looking at the emojis, the API correctly classifies the emotion of the text as anger.

How do I automatically discover the emotions in tweets using Python and Text to Emotion API?

First, let’s take an example from any tweets. Here I use the @apilayer tweet on 27th January 2022:

text Example From Tweets

Copy and paste the tweets into the live demo. You can browse implementations in 10 different programming languages. In this post, we will try Python:

output api Playground python

The following is the complete Python script for you to get started:

Here is the output on Python IDE (PyScripter):

output on PyScripter IDE

How can I develop an interactive web-based Emotion Detector dashboard with Jupyter Notebook?

You can easily build an interactive web-based automated Emotion Detector dashboard using Python scripts in the previous section, just by running them inside Jupyter Notebook. 

Here is the result:

output jupyter Notebook

Check out the full source code here! [1]

How accurate is Text to Emotion API?

Human emotions are too complex for computers to identify. Even humans are easily mistaken by the speech, especially when sarcasm is involved. It is sometimes impossible to predict emotions accurately without mimics and background information. But text to emotion API will perform above the mentioned expectations in most cases. Just subscribe to this API, give it a try for your use case (it is free) and see if it works.

What are the available error codes?

apilayer uses standard HTTP response codes to indicate the success or failure of an API request. In general:

  • Codes in the 2xx range indicate success.
  • Codes in the 4xx range indicate a client-side error, which failed with the information provided (e.g., a missing parameter, unauthorized access, etc.).
  • APILayer’s server errors are indicated by the codes in the 5xx range (typically, this shouldn’t happen).

If the response code you get is not 200, the operation failed somehow, and you may need to take action accordingly. You can check this response (in JSON format) for a field called ”message” that briefly explains the error reported.

The following are the explanations for the 4xx and 5xx error codes:

Status Code


400 – Bad Request

The request was unacceptable, often due to missing a required parameter.

401 – Unauthorized

No valid API key was provided.

404 – Not Found

The requested resource doesn’t exist.

429 – Too many requests

API request limit exceeded. See section Rate Limiting for more info.

5xx – Server Error

We have failed to process your request. (You can contact us anytime)

You can always contact support and ask for more assistance if you have further queries.

Are you ready to build your advanced Emotion Detection apps with Text to Emotion API?

As you can see, the Text to Emotion API provided a powerful emotion detector implementing a complex NLP algorithm. Text to Emotion REST API endpoint also can be connected to any platform and any programming language you work with. It has a broad possibility of industrial implementations.

This article shows you the basic demo of how you can automatically discover emotions from tweets using Text to Emotion API with Python scripting.

Take advantage of the free tier on Text to Emotion API. We strongly recommend upgrading your subscription plan if you need more daily or monthly requests or contacting us for a custom solution. We can’t wait to see what you build with our REST APIs!

Head over and sign up for free to start integrating a powerful emotion detector in text data into your apps today!

[1] https://github.com/MuhammadAzizulHakim/apilayerBlog-repo/tree/main/Article16%20-%20Text%20to%20Emotion%20API%20%2B%20Python

Related posts

YouTube API Key | How Do You Get It in 2024? Tutorial + Examples


Cron Job Monitoring | The Perfect Way to Do it in 2024


Background Removal API | Automate the Image Editing Process


Current Weather API | A Complete Beginner's Guide in 2024

Leave a Reply

Your email address will not be published. Required fields are marked *