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
-
Explain why the program does not print anything (or prints inconsistently).
-
Show how you would fix it so the API calls actually execute and
print
reliably runs.
-
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)?