Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 42

Building a Readability API with Python

Recommended resources

Hello! Welcome back to the course.

In our last lesson, you successfully created a new API endpoint (/api/analyze) that performs basic text analysis by calculating word and character counts. This was a great step in building the core functionality of your writing assistant application.

Today, we'll make that analysis more sophisticated. The goal for this lesson is to integrate a Python library to calculate a readability score and expose it via an endpoint. A readability score measures how easy a piece of text is to understand. This is a very common and useful feature in writing tools, helping users ensure their text is appropriate for their intended audience.

To do this, we'll learn a crucial skill for any programmer: how to find, install, and use external Python libraries to add powerful features to your code without having to write everything from scratch.

1. Finding Our Tool: The textstat Library

When you need to perform a common task in Python, chances are someone has already built a library for it. For text analysis, one of the most popular and easy-to-use libraries is textstat. It provides functions to calculate various metrics, including readability scores.

Textstat Library Homepage and Code Example
The homepage for `textstat`, the Python library we will use to calculate readability scores.

The first step is to add this library to our project's environment. In Python, we use a command-line tool called pip to install packages. You'll run this command in the same terminal you use to run your Flask app.

To see how this works and get a quick introduction to textstat, let's watch a short video.

Analyze Text Readability & Complexity in Python

This video from NeuralNine will introduce you to the textstat library and show you exactly how to install it.

Please watch the first 2 minutes of the video (from 00:00 to 01:51). The presenter will explain what textstat is used for and demonstrate the installation command.

As the video showed, you can install the library by opening your terminal (make sure your project's virtual environment is activated) and running the following command:

pip install textstat

Once the installation is complete, the textstat library is ready to be used in your Python code.


2. Calculating a Readability Score

textstat offers many different readability formulas. We will focus on one of the most widely recognized: the Flesch Reading Ease score.

This score rates text on a 100-point scale. The higher the score, the easier it is to understand the document.

  • 90-100: Easily understood by an average 11-year-old student.
  • 60-70: Easily understood by 13- to 15-year-old students.
  • 0-30: Best understood by university graduates.

Let's return to the video to see how to use textstat to calculate this score and how to interpret it.

Analyze Text Readability & Complexity in Python

The next segment of the video demonstrates how to use the flesch_reading_ease function and explains what its output means.

Please watch from 02:04 to 04:13. Focus on how the textstat.flesch_reading_ease() function is called and the explanation of the score's range.

As you saw, using the library is straightforward. You simply import it and call the function with the text you want to analyze.

Let's try it yourself. Create a temporary Python file (e.g., test_readability.py) and add this code to see it in action:

import textstat

# A simple text
text1 = "The cat sat on the mat. It was a very good cat."

# A more complex text
text2 = "The Flesch Reading Ease formula is a widely used readability test. It calculates a score based on average sentence length and average number of syllables per word."

score1 = textstat.flesch_reading_ease(text1)
score2 = textstat.flesch_reading_ease(text2)

print(f"Score for simple text: {score1}")
print(f"Score for complex text: {score2}")

When you run this file (python test_readability.py), you should see that the simpler text gets a much higher score.


3. Integrating the Score into Your Flask Endpoint

Now that we know how to calculate the score, let's add it to the analyze_endpoint you built in the last lesson. This involves three small changes to your app.py file:

  1. Import the textstat library at the top of the file.
  2. Calculate the readability score inside the analyze_endpoint function.
  3. Add the score to the JSON response that is sent back to the user.

Here is the updated code for your analyze_endpoint function in app.py. The new lines are marked with comments.

# In app.py

# Make sure you have these imports at the top of your file
from flask import Flask, request, jsonify
import textstat # 1. Import the library

# ... your Flask app initialization and other endpoints ...

@app.route('/api/analyze', methods=['POST'])
def analyze_endpoint():
    # Get the text from the request
    user_text = request.json.get('text')

    # Validate the input
    if not user_text:
        return jsonify({'error': 'No text provided'}), 400

    # Perform the existing analysis
    char_count = len(user_text)
    word_count = len(user_text.split())

    # 2. Calculate the new readability score
    readability_score = textstat.flesch_reading_ease(user_text)

    # Create a dictionary with all the results
    analysis_results = {
        'character_count': char_count,
        'word_count': word_count,
        'readability_score': readability_score # 3. Add the score to the results
    }

    # Return the results as a JSON response
    return jsonify(analysis_results)

With these changes, your endpoint is now significantly more powerful.

Test your understanding!

If you send a POST request to /api/analyze with the JSON body {"text": "See Spot run. Run, Spot, run."}, what would the keys in the returned JSON response be?

Show answer

The returned JSON object would have three keys: character_count, word_count, and readability_score. The readability_score would likely be very high, indicating the text is very easy to read.

To confirm everything is working, run your Flask application again. Use a tool like Postman to send a POST request to http://127.0.0.1:5000/api/analyze with some text. You should now see the readability score included in the JSON response alongside the word and character counts.

Interestingly, the idea of building a small script and then extending it into a Flask web app is a common workflow. The article below uses textstat to build a command-line tool and specifically mentions Flask as a way to turn it into a web application, which is exactly what you've just done.

Building a Real-Time Readability Checker with Textstat

This article from Statology, 'Building a Real-Time Readability Checker with Textstat', walks through a similar process. It's a good confirmation that the skills you're learning are standard practice.

You don't need to read the whole article, but take a look at the final section, 'Wrapping Up'. Notice how it suggests building a small web app with Flask as a logical next step. This reinforces the path we are on.


Conclusion

In this lesson, you've added a significant feature to your application by integrating an external library. This is a fundamental part of modern software development.

Key Takeaways:

  • Python's ecosystem is full of powerful libraries that can be installed using pip.
  • The pip install -> import -> use pattern is the standard workflow for using external packages.
  • The textstat library provides an easy way to calculate text readability scores, like the Flesch Reading Ease score.
  • You can easily extend existing Flask endpoints to provide more detailed and useful analysis in your JSON responses.

You've now built two core statistical features for your writing assistant. In the next lesson, we will return to the world of AI and create a Flask endpoint that uses the Gemini API for grammar and spelling correction, adding another powerful capability to your application.