In modern web development, APIs (Application Programming Interfaces) play a crucial role in enabling the interaction between different software systems. Flask, a lightweight WSGI web application framework in Python, provides a simple and flexible way to create APIs. In this article, we’ll explore how to get data from an API using Python Flask. We’ll cover setting up a Flask project, making API requests, and handling responses.
Setting Up a Flask ProjectTo get started with Flask, you’ll need to install it. You can do this using pip:
Install Flask and requests:pip install Flask requests Directory Structure:
Next, create a new directory for your project and a Python file.
flask_api_project/
├── app.py
└── templates/
└── data.html Displaying Data in Flask TemplatesFlask supports rendering HTML templates using the Jinja2 template engine. Let’s create a simple HTML template to display the data we get from the API.
First, create a templates directory in your project folder and add a file named data.html :
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>API Data</title>
</head>
<body>
<h1>API Data</h1>
<pre>{{ data | tojson }}</pre>
</body>
</html>
Next, create a new directory for your project and a Python file, e.g., app.py . In this file, we’ll set up the basic structure of our Flask application.
Python
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/')
def home():
return "Welcome to the Flask API tutorial!"
if __name__ == '__main__':
app.run(debug=True)
app.py
The requests library provides a straightforward way to handle API responses. In the example, we use the json() method to parse the JSON response from the API. We then use Flask’s jsonify function to return the data as a JSON response from our endpoint.
Python
from flask import Flask, jsonify, render_template
import requests
app = Flask(__name__)
@app.route('/')
def home():
return "Welcome to the Flask API tutorial!"
@app.route('/api/data')
def get_data():
try:
response = requests.get('https://jsonplaceholder.typicode.com/todos/1')
# Raises an HTTPError if the HTTP request returned an unsuccessful status code
response.raise_for_status()
data = response.json()
except requests.exceptions.HTTPError as http_err:
return jsonify({'error': f'HTTP error occurred: {http_err}'}), 500
except Exception as err:
return jsonify({'error': f'Other error occurred: {err}'}), 500
return render_template('data.html', data=data)
if __name__ == '__main__':
app.run(debug=True)
Output
Home page
 Get Data Page
|