TUTORIAL

How to Create an Async API Call with asyncio


Compared to other programming languages, Python can be much slower at making API calls. That's because, by design, Python is a blocking language. This means Python code will not be executed until the previous set of instructions has finished. This holds true for definition calls, too.

The good news is, there's a way to speed up this process. In this tutorial, you’ll learn how to use asyncio and aiohttp to create an asynchronous API call in Python. By the end, you’ll understand how async code works in practice and how it can make your applications more responsive when dealing with network requests.

Project Overview

EXPERIENCE LEVEL: Intermediate

TIME TO COMPLETE: 45–75 minutes

ESTIMATED COST: $0 (all tools and libraries used are free and open source) 


Before starting this tutorial, make sure you can:

  • Run Python scripts from the command line

  • Install packages using pip

  • Read and modify basic Python functions

You don’t need prior experience with asynchronous programming, but you should be comfortable writing and running standard (synchronous) Python code.

  • Intermediate Python Fundamentals (functions, imports, control flow)

  • Basic understanding of HTTP requests (GET requests and responses)

  • Comfort using a terminal or command prompt

  • Python 3.8 or newer (3.11 recommended)

  • pip (included with modern Python installs)

  • A code editor (VS Code, PyCharm, or similar)

  • Terminal, PowerShell, or Command Prompt

  • Internet access (we’ll call a public test API)

An Intro to asyncio

By design, Python is a blocking language—it finishes one task before moving on to the next. The asyncio library enables writing non-blocking, concurrent code using the familiar async and await syntax.

Before jumping in, keep a few things in mind:

  • This tutorial is intentionally focused: asyncio can do much more than what’s shown here. The goal is to demonstrate how async code works in Python—not to cover every asyncio feature. For a full reference, see the official documentation at Python.org.

  • You’ll see two code examples: One example uses asyncio and async/await, which we’ll reference throughout the tutorial. The second shows a traditional blocking GET request using the requests library and is included only for comparison.

  • Code references are labeled: Some parts of the async example are tagged with reference comments (for example, # Reference 1) so they’re easier to call out and explain later.

  • One function is just for visualization: The count() function exists only to show async behavior in action. It counts once per second and prints to the console while the API request runs in parallel.

Feel free to run the async example as you follow along. Notice when the API response appears in the console—and what happens while Python is waiting for it.

How to Create an Async API Call with asyncio

Python doesn’t support asynchronous execution by default, but the asyncio library makes it possible to write concurrent, non-blocking code. In the steps below, you’ll install the required libraries, write an async API call, and run it alongside another async task to see how concurrency works.

Step 1: Verify Your Python Version

First, confirm that you’re running a supported version of Python.

Open a terminal and run:

python --version

or, on some systems:

python3 --version

You should see Python 3.8 or newer. If not, upgrade Python before continuing.

Step 2: Install Required Libraries

You’ll need two libraries:

  • asyncio (included with Python 3.4+)

  • aiohttp (an async HTTP client built on asyncio)

Install aiohttp using pip:

pip install aiohttp

Once installed, you’re ready to write async code.

Step 3: Import asyncio and aiohttp

Create a new Python file called async_api.py.

At the top of the file, add the following imports:

import asyncio
from aiohttp import ClientSession

These libraries allow Python to schedule asynchronous tasks and make non-blocking HTTP requests.

Step 4: Create a Simple Async Task

To visualize how async code works, create a function that counts once per second.

async def count():
    for i in range(1, 6):
        print(f"Count: {i}")
        await asyncio.sleep(1)

This function pauses for one second between prints without blocking other async tasks.

Step 5: Create an Async API Call

Now create an asynchronous function that makes an API request.

async def get_delay(seconds):
    base_url = "https://httpbin.org"
    endpoint = f"/delay/{seconds}"
    print(f"Making API call with {seconds}-second delay...")

    async with ClientSession() as session:
        async with session.get(base_url + endpoint) as response:
            data = await response.json()
            print("API response received:")
            print(data)

This function:

  • Calls a test API that intentionally delays its response

  • Uses await so Python can switch tasks while waiting

  • Prints the response once it’s received

Step 6: Run Async Functions Together

To run async functions, you must start them from a single entry point.

Add the following function:

async def main():
    await asyncio.gather(
        get_delay(5),
        count()
    )

The gather() method tells Python to run both functions concurrently.

Step 7: Start the Async Event Loop

At the bottom of the file, add:

asyncio.run(main())

This starts the asyncio event loop and runs all scheduled async tasks.

Run the script:

python async_api.py

You should see the counter printing once per second while the API request is still in progress. When the API responds, its output appears without stopping the counter.

Screenshot: Terminal output showing interleaved count and API response

Step 8: Compare with a Blocking API Call (Optional)

For comparison, here’s what a traditional blocking request looks like:

import requests

def get_delay_blocking(seconds):
    base_url = "https://httpbin.org"
    endpoint = f"/delay/{seconds}"
    response = requests.get(base_url + endpoint)
    print(response.json())

If you run this version, Python will do nothing else until the API call finishes—highlighting the advantage of async code.

Closing Thoughts

In this tutorial, you learned how to create an async API call in Python using asyncio and aiohttp. While Python is a blocking language by default, async code lets it remain productive while waiting for slow operations like network requests.

Asynchronous programming is especially useful for API-heavy applications, network automation, monitoring tools, and data collection scripts.

To go deeper into Python automation and real-world async use cases, check out our Introduction to Python for Network Engineers Online Training. You can also explore more hands-on guides in our main tutorials section.

Not a CBT Nuggest subscriber? Sign up for your first 7 days free.

Get CBT Nuggets IT training news and resources

I have read and understood the privacy policy and am able to consent to it.

© 2026 CBT Nuggets. All rights reserved.Terms | Privacy Policy | Accessibility | | Sitemap | 2850 Crescent Avenue, Eugene, OR 97408 | 541-284-5522