Random JSON Data Fetcher with Tornado Web Server

  • Share this:

Code introduction


This code creates a simple Tornado web server that randomly fetches a JSON data. The server listens on port 8888 and when accessed at the root path, it randomly selects one from three predefined URLs, fetches JSON data, and returns it.


Technology Stack : Tornado, HTTPClient

Code Type : Web server

Code Difficulty : Intermediate


                
                    
import tornado.ioloop
import tornado.web
import tornado.httpclient
import random

def fetch_random_data():
    urls = [
        "http://jsonplaceholder.typicode.com/todos/1",
        "http://jsonplaceholder.typicode.com/posts/1",
        "http://jsonplaceholder.typicode.com/users/1"
    ]
    
    client = tornado.httpclient.HTTPClient()
    url = random.choice(urls)
    response = client.fetch(url)
    
    return response.body

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        data = fetch_random_data()
        self.write(data)

def make_app():
    return tornado.web.Application([
        (r"/", MainHandler)
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()