Table of Contents
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.
Subscribe for free, choose your subscription plan, or contact us here if you have a customized plan on your mind.
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?
Use the POST method to discover the emotions in textual messages.
The following is the parameter for sending POST request:
Text to perform emotion analysis
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 --location --request POST 'https://api.promptapi.com/text_to_emotion' \
--header 'apikey: YOUR_API_KEY' \
--data-raw 'To be, or not to be, that is the question:
Whether '\''tis nobler in the mind to suffer
The slings and arrows of outrageous fortune,
Or to take Arms against a Sea of troubles,
And by opposing end them: to die, to sleep;'
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 --location --request POST 'https://api.promptapi.com/text_to_emotion' --header 'apikey: YOUR_API_KEY' --data-raw "It\'s not funny. This must be a joke! 😡🤬"
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:
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:
The following is the complete Python script for you to get started:
url = "https://api.apilayer.com/text_to_emotion"
payload = "Be%20honest!%20How%20much%20coffee%20do%20you%20need%20to%20get%20you%20through%20the%20day%3F%20According%20to%20a%20study%2C%20the%20average%20developer%20consumes%20from%20two%20to%20five%20cups%20of%20coffee%20per%20day.%20Are%20you%20Team%20coffee%20or%20team%20tea%3F%0A%23API%20%23webdevelopment%20%23coding%20%23tech%20%23developers%20%23webscraping%20%23webscrapingapi%20%23webapi".encode("utf-8")
response = requests.request("POST", url, headers=headers, data = payload)
status_code = response.status_code
result = response.text
Here is the output on Python IDE (PyScripter):
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:
Check out the full source code here! 
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:
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!