Asynchronous JSON Data Fetching with Tornado#s httpclient Module

  • Share this:

Code introduction


This function uses Tornado's httpclient module to asynchronously fetch JSON data. By passing a URL, the function sends an HTTP GET request, and processes the result in a response callback.


Technology Stack : tornado, tornado.ioloop, tornado.web, tornado.httpclient

Code Type : Asynchronous HTTP request

Code Difficulty : Intermediate


                
                    
import tornado.ioloop
import tornado.web
import tornado.httpclient
import json

def fetch_json_data(url):
    loop = tornado.ioloop.IOLoop.current()
    def handle_response(response):
        if response.code == 200:
            print("JSON data:", response.body)
        else:
            print("Failed to fetch JSON data:", response.error)
    http_client = tornado.httpclient.AsyncHTTPClient()
    http_client.fetch(url, callback=handle_response)
    loop.start()

# JSON response