Hello! Let's dive into the next crucial step in building your web application.
In our last lesson, you learned how to receive data from an HTML form on your Flask server and use it to render a brand-new HTML page. This is a complete data round-trip, but modern web applications often feel faster and more interactive because they don't require a full page reload for every action.
Today, you'll learn the technique that makes this possible. We will create a special kind of URL called an API endpoint. Instead of returning a full, styled webpage, this endpoint will return only raw, structured data. This is the foundation that will allow your web page (the "frontend") to communicate with your Python code (the "backend") to get AI-generated results without a disruptive page refresh.
What is an API Endpoint and What is JSON?
An API (Application Programming Interface) is like a contract or a menu that allows two different pieces of software to talk to each other. In our case, it's how we'll define the "menu" of functions our Flask backend offers to the web browser. An API endpoint is a specific URL on our server that, when accessed, performs a task and returns data.
But in what format should that data be? The most popular format for web APIs is JSON (JavaScript Object Notation).
To get a clear understanding of what JSON is and why it's so important, please read the first part of the following article.
Returning JSON for Structured Responses
This article, 'Returning JSON for Structured Responses', explains what JSON is and why it's the standard for modern web APIs.
Please read the introduction and the sections 'Why to Structure Endpoint Responses' and 'What is JSON'. Focus on understanding that JSON uses a key-value pair structure, just like the Python dictionaries you've already worked with.
As you read, you'll see that a JSON object looks incredibly similar to a Python dictionary.
- Python Dictionary:
{"name": "John", "age": 30} - JSON:
{"name": "John", "age": 30}
This similarity makes it very easy to work with JSON in Python.
Creating Your First JSON Endpoint
Flask makes returning JSON incredibly simple. In modern versions of Flask, if you return a Python dictionary from a route function, Flask will automatically convert it into a proper JSON response.
Let's see this in action. Take a look at this short video.
How To Return JSON With Flask For an API - Flask Fridays #16
This video from Codemy.com demonstrates the simplest way to return JSON data from a Flask endpoint.
Watch from 02:10 to 04:42. Notice how returning a simple Python dictionary from the function results in JSON being displayed in the browser. The video also shows a slightly more complex dictionary example.
Let's write the code for our own simple API endpoint.
app.py
from flask import Flask
app = Flask(__name__)
# This is our API endpoint
@app.route('/api/status')
def api_status():
# Create a Python dictionary
status_data = {
'appName': 'AI Writing Assistant',
'version': '0.1',
'status': 'online'
}
# Return the dictionary. Flask will convert it to JSON.
return status_data
if __name__ == '__main__':
app.run(debug=True)
Run this app.py file and navigate your browser to http://127.0.0.1:5000/api/status. Instead of an HTML page, you'll see the raw JSON text. Your browser might even have a built-in viewer to format it nicely.
Using jsonify for Clearer Code
While returning a dictionary directly works, Flask provides a function called jsonify that makes your intention more explicit and gives you a bit more control. It's considered good practice to use it.
The jsonify function does two things:
- It converts your Python dictionary into a JSON formatted string.
- It creates a proper HTTP Response object with the
Content-Typeheader set toapplication/json. This header is a signal to browsers and other clients that they are receiving JSON data.
The video below gives a great overview of building a simple API with Flask and demonstrates how to use jsonify.
Create A Python API in 12 Minutes
This video from Tech With Tim, 'Create A Python API in 12 Minutes', provides a practical guide to building an API, including how to return a JSON response.
Please watch from 01:57 to 08:42. Pay attention to: Importing flask, request, and jsonify (02:40) How he creates a dictionary called user_data (06:30) The final return jsonify(user_data) line, which sends the JSON response (07:55) How he also returns a status code 200, which means 'OK' (08:05)
Let's update our previous example to use jsonify.
app.py (updated)
from flask import Flask, jsonify # Import jsonify
app = Flask(__name__)
@app.route('/api/status')
def api_status():
status_data = {
'appName': 'AI Writing Assistant',
'version': '0.1',
'status': 'online'
}
# Use jsonify to create the response
return jsonify(status_data)
if __name__ == '__main__':
app.run(debug=True)
If you run this and visit the URL again, the result will look identical. Under the hood, however, we are being more explicit about our goal.
Testing Your API Endpoints
While you can test simple GET endpoints in your browser, it's not practical for more complex requests (like the POST requests we'll need later). Professional developers use API testing tools. One of the most popular is Postman.
These tools let you craft any kind of HTTP request (GET, POST, etc.), add headers, send JSON data, and inspect the server's response in detail.
This image shows exactly what this looks like. A request with JSON data is sent to a Flask server, which then processes it and sends a JSON response back.

The final part of the Tech With Tim video you were watching introduces Postman and shows you how to use it to test a POST request. Getting familiar with this tool now will be very helpful.
Create A Python API in 12 Minutes
Now, let's learn how to test an API endpoint that expects to receive data, which can't be done easily in a browser. This section introduces the Postman tool.
Watch from 08:42 to 11:36. You don't need to code the POST route yourself right now, but focus on understanding how he uses Postman to: Set the URL and the request method (POST). Add JSON data to the 'Body' of the request. Send the request and view the JSON response from the server.
Test your understanding!
Let's build an API endpoint that performs a simple text analysis, a small step towards your final project!
- Create a new Flask app.
- Define a route
/api/analyze/<text_to_analyze>. This uses a dynamic URL part, similar to the/get-user/<user_id>example in the video. - In the function for this route, calculate two things: the number of characters and the number of words in
text_to_analyze. (Hint:len()for characters andlen(text_to_analyze.split())for words). - Return a JSON object containing the original text, the character count, and the word count.
For example, if you navigate to http://127.0.0.1:5000/api/analyze/Hello world this is fun, your API should return a JSON response like this:
{
"character_count": 25,
"original_text": "Hello world this is fun",
"word_count": 5
}
Show answer
Here is the complete app.py file:
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api/analyze/<text_to_analyze>')
def analyze_text(text_to_analyze):
# Calculate the word and character counts
char_count = len(text_to_analyze)
word_count = len(text_to_analyze.split())
# Create the dictionary for the JSON response
analysis_result = {
'original_text': text_to_analyze,
'character_count': char_count,
'word_count': word_count
}
# Return the result as a JSON response
return jsonify(analysis_result)
if __name__ == '__main__':
app.run(debug=True)
Conclusion
Fantastic work! You have now learned how to create a backend API endpoint that provides raw data to any client that asks for it. This is a fundamental building block of modern web development and is the exact mechanism we will use to connect your web page's interactive elements to the powerful AI models on the backend.
Key Takeaways:
- APIs allow your frontend (browser) and backend (Flask server) to communicate using data.
- JSON is the standard data format for web APIs, using a key-value structure that looks just like a Python dictionary.
- In Flask, you can simply
returna dictionary from a route, or more explicitly use thejsonify()function to create a JSON response. - API endpoints are often tested with dedicated tools like Postman.
In our next lesson, we'll take a step back and look at organization. As our application grows with HTML files, Python code, and soon CSS and JavaScript files, we need a clean folder structure to manage everything. We'll learn the standard way to structure a Flask project to keep it tidy and maintainable.