How to Get Data from API in Python Flask
Last Updated :
05 Jul, 2024
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 Project
To 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 Templates
Flask 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
Similar Reads
How to get data from 'ImmutableMultiDict' in flask In this article, we will see how to get data from ImmutableMultiDict in the flask. It is a type of Dictionary in which a single key can have different values. It is used because some elements have multiple values for the same key and it saves the multiple values of a key in form of a list. It is usu
2 min read
How to get JSON data from request in Django? Handling incoming JSON data in Django is a common task when building web applications. Whether you're developing an API or a web service, it's crucial to understand how to parse and use JSON data sent in requests. In this article, we will create a simple Django project to demonstrate how to retrieve
2 min read
Flask login without database - Python In this article, we will talk about Python-based Flask login without a database in this article. In order to use Flask login without a database in this method basically we are using a python dictionary through which users will be able to log in using their login credentials that we add to the databa
4 min read
How to return a JSON response from a Flask API ? Flask is one of the most widely used python micro-frameworks to design a REST API. In this article, we are going to learn how to create a simple REST API that returns a simple JSON object, with the help of a flask. Prerequisites: Introduction to REST API What is a REST API? REST stands for Represent
3 min read
Python Falcon - get POST data In this discussion, we will delve into retrieving Python Falcon - get POST data. Falcon is a lightweight and speedy web framework explicitly crafted for constructing RESTful APIs. Effective handling of POST data is essential in API development, enabling the creation, updating, or manipulation of res
4 min read
How To Use Web Forms in a Flask Application A web framework called Flask provides modules for making straightforward web applications in Python. It was created using the WSGI tools and the Jinja2 template engine. An example of a micro-framework is Flask. Python web application development follows the WSGI standard, also referred to as web ser
5 min read