Retrieve JSON data from URL in Flask | Python

In this article, we will see how we can use the request object in a flask to Get the Data that is passed to your routes and How to Process Get Request Data in Flask using Python.

Introduction

So, basically, Flask is a web development framework which is written in Python, and it is widely used as a web framework for creating APIs (Application Programming Interfaces) or it is a micro web framework that allows developers to build web applications quickly and easily.

Python-Flask Request

In Python-Flask the request module is an object that allows you to access the data sent from the user to the server (Client-Server), and that data is passed into your Flask Application.
There are two methods in order to get the data/ request the data:

  • GET Method
  • Post Method

Prerequisites

Before writing the code ensure that in your IDE or VS Code Editor the Flask framework and requests library is installed. If not, then you can download it using the following command.

pip install Flask
pip install requests

Basic Example:

from flask import Flask, jsonify
import requests

app = Flask(__name__)

@app.route('/')
def fetch_data():
    # The URL from which to fetch JSON data
    url = "https://jsonplaceholder.typicode.com/posts"

    try:
        # Make the GET request
        response = requests.get(url)
        response.raise_for_status()  # Raise an error for HTTP error codes (4xx, 5xx)

        # Parse the JSON data
        data = response.json()

        # Return the data as a JSON response
        return jsonify(data)

    except requests.exceptions.RequestException as e:
        # Handle errors (network issues, bad responses, etc.)
        return jsonify({"error": str(e)}), 500

if __name__ == "__main__":
    app.run(debug=True)

Explanation:

  • Flask(__name__): Used to create an instance of the Flask application. It sets up your Flask app and acts as the central object for the application, managing routing, configuration, and other functionalities.
  • @app.route: Decorator in Flask used to define the URL route (or endpoint).
  • Try: The try block ensures proper handling.
  • request.get(url): Fetches the data from the url provided.
  • response.raise_for_status(): Checks for HTTP errors and raises exceptions.
  • response.json(): Parses the obtained data.

Warning:

The url used in the above code is for educational purposes only. Do not use it for DoS or DDoS.

Output:

You can access the endpoint http://127.0.0.1:5000 and see the JSON file which will look as

 

 

Conclusion

The @app can be used to access different routes of a website or create different routes for a website.

Related Posts

If you are working with Flask framework, you might also find this post helpful:

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top