How do computer programs communicate with one another? The answer is APIs. In this article, you will learn how to create and consume APIs using Python. We will guide you step by step with practical examples so you can immediately put what you learn into practice.
What Is an API?
An API (Application Programming Interface) is a set of rules and definitions that allows two applications to communicate with each other. Imagine it as a messenger that takes your requests to another program and brings back the responses.
Why Use Python to Create APIs?
Python is a programming language known for its simplicity and power. It is ideal for creating APIs because of its robust libraries and frameworks, such as Flask, which make fast and efficient development easier.
Creating a Python API with Flask
Installing Flask
First, you need to install Flask. Open your terminal and type:
pip install Flask
Writing the API Code
Create a file called app.py and add the following code:
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/api/greet', methods=['GET'])
def greet():
name = request.args.get('name', 'World')
return jsonify({'message': f'Hello, {name}!'})
@app.route('/api/add', methods=['GET'])
def add():
a = request.args.get('a', default=0, type=int)
b = request.args.get('b', default=0, type=int)
return jsonify({'result': a + b})
if __name__ == '__main__':
app.run(debug=True)
Explaining the Code
-
Import Flask: We import the required Flask functions.
-
Create the Application:
app = Flask(__name__)creates a Flask application instance. -
Define Routes:
-
/api/greet: Returns a personalized greeting. -
/api/add: Adds two numbers and returns the result.
- Run the Application:
app.run(debug=True)runs the application in debug mode.
Running the API
To run the API, open your terminal and type:
python app.py
Your API will be available at http://127.0.0.1:5000.
Consuming an API from a Web Client
Now that your API is running, let us see how to consume it from a web client using JavaScript.
Creating the Web Client
Create a file called index.html and add the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Consuming a Python API</title>
</head>
<body>
<h1>Consuming a Python API with Flask</h1>
<div>
<h2>Greeting</h2>
<input type="text" id="name" placeholder="Enter your name">
<button onclick="getGreeting()">Get greeting</button>
<p id="greeting"></p>
</div>
<div>
<h2>Add Numbers</h2>
<input type="number" id="number1" placeholder="Number 1">
<input type="number" id="number2" placeholder="Number 2">
<button onclick="addNumbers()">Add</button>
<p id="result"></p>
</div>
<script>
function getGreeting() {
const name = document.getElementById('name').value;
fetch(`http://127.0.0.1:5000/api/greet?name=${name}`)
.then(response => response.json())
.then(data => {
document.getElementById('greeting').innerText = data.message;
})
.catch(error => console.error('Error:', error));
}
function addNumbers() {
const number1 = document.getElementById('number1').value;
const number2 = document.getElementById('number2').value;
fetch(`http://127.0.0.1:5000/api/add?a=${number1}&b=${number2}`)
.then(response => response.json())
.then(data => {
document.getElementById('result').innerText = `Result: ${data.result}`;
})
.catch(error => console.error('Error:', error));
}
</script>
</body>
</html>
Testing the Application
-
Run your Flask server, if it is not already running, with
python app.py. -
Open the
index.htmlfile in your web browser. -
Test the greeting by entering your name and pressing the “Get greeting” button.
-
Test adding two numbers in the corresponding fields and pressing the “Add” button.
Conclusion
Creating and consuming APIs in Python is easier than it may seem, especially with tools such as Flask. Whether you are developing on Linux or another operating system, Python gives you the flexibility and power to create robust and efficient applications. Now that you know how, start building your own Python APIs.
This article has shown you the basic concepts and practical examples you need to get started. Keep exploring and learning to improve your software development skills.

