Member-only story

How To Make Parallel Async HTTP Requests in Python

Requests with Threads vs. aiohttp with Semaphore

Ng Wai Foong
Better Programming
5 min readOct 6, 2021

Photo by Matt Duncan on Unsplash

By reading this piece, you will learn to make multiple asynchronous requests concurrently in Python. This tutorial covers two different methods:

  • via requests package with Threads (a native thread for each request)
  • via aiohttp client with Semaphore (to limit and pool the number of tasks)

Both implementations are inspired by the explanation in the following blog post. The code samples provided by the author is meant to be run on Jupyter Notebook which comes with its own event loop, eliminating the need to call asyncio.run. In this tutorial, the code will be cleaned and modified for it to work in Python file.

Besides that, we will implement our own server instead of calling an external API. As a result, you can easily scale up or down the number of concurrent requests at your own will.

Let’s proceed to the next section and start installing the necessary modules.

Setup

It is highly recommended to create a new virtual environment before you continue with the installation.

aiohttp

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Ng Wai Foong
Ng Wai Foong

Written by Ng Wai Foong

Senior AI Engineer@Yoozoo | Content Writer #NLP #datascience #programming #machinelearning | Linkedin: https://www.linkedin.com/in/wai-foong-ng-694619185/

Responses (3)

Good article> I tested this and threads took about 1.21 seconds while aiohttp took around 0.3 sec , super fast. However for threads I used multiprocessing.pool.ThreadPool

Thanks for sharing Ng Wai!

I got those errors at the same time
TypeError: cannot unpack non-iterable coroutine object
self.run()func, args, kargs = self.tasks.get()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
C:\Users\nastia\PycharmProjects\techopedia…