NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Senior1 view

How can you efficiently make a synchronous request with requests in an asynchronous application?

Practice

Asked at

AI answer

If there are many requests or the application makes extensive use of asyncio, an asynchronous HTTP client such as httpx.AsyncClient or aiohttp is preferable. If you need to keep using requests, move the call out of the event loop and into a thread—for example, with asyncio.to_thread:

import asyncio
import requests

async def fetch(url):
    response = await asyncio.to_thread(requests.get, url, timeout=10)
    response.raise_for_status()
    return response.json()

This prevents the event loop from being blocked while waiting for a response. For a series of requests, account for the thread limit and reuse the client/connections if the library supports it.