Katkat

Debug missing output in Python async HTTP flow

MillenniumSoftware Engineer · Onsite

Last updated

This question evaluates understanding of asynchronous programming in Python, including event loop management and async I/O semantics, and is categorized under Software Engineering Fundamentals with a focus on practical application of concurrency concepts.

You are given a Python program intended to call two HTTP APIs in order, process the returned JSON, and finally print the computed result. However, when you run the program, it exits without printing the expected output.

Assume an async HTTP client (e.g., aiohttp) is used.

Code (simplified)

import asyncio
import aiohttp

async def fetch_json(session, url):
 async with session.get(url) as resp:
 return await resp.json()

async def pipeline():
 async with aiohttp.ClientSession() as session:
 a = fetch_json(session, "https://api.example.com/a")
 b = fetch_json(session, "https://api.example.com/b")
 result = (await a)["value"] + (await b)["value"]
 print("result:", result)

def main():
 pipeline()

if __name__ == "__main__":
 main()

Tasks

  1. Explain why the program does not print anything (or prints inconsistently).
  2. Show how you would fix it so the API calls actually execute and print reliably runs.
  3. As a follow-up: if the intent is to run both HTTP calls concurrently, what is the idiomatic way to do that, and what pitfalls should you watch for (e.g., cancellation, exceptions, and program exit)?