All Course > Python > Build Apis With Python Aiohttp Dec 07, 2023

Asynchronous CRUD operations in python

Python offers a diverse range of libraries, and two notable ones for executing asynchronous CRUD operations are asyncio and aiohttp. These libraries enable the creation of efficient and responsive programs by allowing tasks to run concurrently.

Asynchronous operations in Python are particularly useful when dealing with tasks that involve waiting for external resources, such as fetching data from a remote server. The asyncio library facilitates the creation of coroutines, which are functions designed to perform asynchronous tasks. These coroutines can be scheduled to run concurrently, enhancing the overall efficiency of the program.

A crucial component in the process is the aiohttp library, which serves as the tool for making HTTP requests within the asynchronous framework. This library is well-suited for handling concurrent requests efficiently, making it an excellent choice for scenarios where multiple CRUD operations need to be executed asynchronously.

Implement asynchronous-crud-operations

To initiate the execution of request coroutines in Asyncio, we rely on the run() function, accessible through the asyncio library. When the run() function is invoked, it triggers the creation of a fresh event loop. This event loop is essentially a mechanism that allows asynchronous tasks, or coroutines, to be managed and scheduled efficiently.

Once a given coroutine has completed its task, the run() function takes charge of terminating the event loop. At this point, it returns the result of the coroutine or, in case of an exception during execution, provides information about the encountered error.

The role of the run() function is crucial in orchestrating the asynchronous operations in Asyncio. It simplifies the process by automating the setup and teardown of the event loop, making it more convenient for developers to handle and manage asynchronous tasks in Python.

In the examples provided for CRUD operations, our focus is on the /users API endpoint, which is freely accessible on gorest.co.in. This specific API endpoint serves as the gateway for performing Create, Read, Update, and Delete operations on user data. By interacting with this endpoint, we can manipulate user information through simple and standardized HTTP requests.

Asynchronous GET using asyncio and aiohttp

To perform an asynchronous GET request using asyncio and aiohttp, you can utilize the provided Python code. Start by replacing the existing URL in the code with your specific one. Upon execution, the code sends a request to the updated URL. If the request is successful, it prints both the response code and the response content in the terminal.

The code employs JSON’s dumps() method to convert the JSON-formatted response into a string with an indented structure, enhancing readability. This step is particularly valuable when dealing with APIs that provide data in JSON format, as it allows for a well-organized presentation of the information.

Examining the code, it establishes an asynchronous function named get() that includes the necessary components for making an asynchronous GET request. The use of aiohttp.ClientSession() facilitates the creation of a session, and the code checks the response status to handle potential errors. If the response status is not 200 (OK), an error message is printed.

import asyncio
import aiohttp
import json

async def get():
    url = "https://gorest.co.in/public/v2/users"
    headers = {"Content-Type": "application/json"}
    async with aiohttp.ClientSession() as session:
        async with session.get(url, headers=headers, ssl=False) as response:
            if response.status != 200:
                print(f"Request failed {response.status}")
            res = json.loads(await response.text())
            print(response.status)
            print(json.dumps(res, indent=4))

if __name__ == "__main__":
    asyncio.run(get())

Asynchronous POST using asyncio and aiohttp

To perform an asynchronous POST request using asyncio and aiohttp, you can utilize the provided Python code. Before executing, make sure to replace the existing URL, token, and payload with your specific values.

For this demonstration, a Bearer token is utilized, and it is passed in the request headers along with other necessary details. The payload, containing information about the user to be created, is structured as a dictionary.

Upon execution, the code initiates an asynchronous POST request using the specified URL, headers, and payload. If the request is successful and the response code is 201 (Created), it prints both the response code and the formatted response content in the terminal. In case of an error, the code displays the encountered response code to facilitate quick identification of issues.

Examining the code structure, the asynchronous function named post() incorporates the essential components for making a POST request. The use of aiohttp.ClientSession() establishes a session for the request, and the code checks the response status to handle potential errors.

import asyncio
import aiohttp
import json

async def post():
    url = "https://gorest.co.in/public/v2/users"
    headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer <ACCESS-TOKEN>",
        "Accept": "application/json"
    }
    payload = {
        "name": "Tenali Ramakrishna",
        "gender": "male",
        "email": "[email protected]",
        "status": "active"
    }
    async with aiohttp.ClientSession() as session:
        async with session.post(url, headers=headers, ssl=False, data=json.dumps(payload)) as response:
            if response.status != 201:
                print(f"Request failed {response.status}")
            res = json.loads(await response.text())
            print(response.status)
            print(json.dumps(res, indent=4))

if __name__ == "__main__":
    asyncio.run(post())

Asynchronous PUT using asyncio and aiohttp

PUT request is almost similar to POST request. The only difference is, instead of calling post() method, we are calling put() method in aiohtpp. If the response code is not 204, it will print the error response code.

import asyncio
import aiohttp
import json

async def put():
    url = "https://gorest.co.in/public/v2/users/547"
    headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer <ACCESS-TOKEN>",
        "Accept": "application/json"
    }
    payload = {
        "name": "Tenali Ramakrishna",
        "gender": "male",
        "email": "[email protected]",
        "status": "active"
    }
    async with aiohttp.ClientSession() as session:
        async with session.put(url, headers=headers, ssl=False, data=json.dumps(payload)) as response:
            if response.status != 204:
                print(f"Request failed {response.status}")
            res = json.loads(await response.text())
            print(response.status)
            print(json.dumps(res, indent=4))

if __name__ == "__main__":
    asyncio.run(put())

Asynchronous DELETE using asyncio and aiohttp

The structure of the delete() request is tailored for asynchronous deletion of resources. The code establishes a connection to the specified URL, accompanied by the necessary headers, including the Authorization token and the content type. The asynchronous nature of the operation is facilitated by the use of aiohttp.ClientSession(), allowing for efficient handling of the DELETE request.

Analyzing the code, the asynchronous function named delete() encapsulates the essential components for making a DELETE request. The session is managed by the aiohttp.ClientSession() to ensure proper handling of the asynchronous operation, and the response status is checked to handle potential errors during the deletion process.

# asyncio_aiohttp_delete.py
import asyncio
import aiohttp
import json

async def delete():
    url = "https://gorest.co.in/public/v2/users/547"
    headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer <ACCESS-TOKEN>",
        "Accept": "application/json"
    }
    async with aiohttp.ClientSession() as session:
        async with session.delete(url, headers=headers, ssl=False) as response:
            if response.status != 200:
                print(f"Request failed {response.status}")
            res = json.loads(await response.text())
            print(response.status)
            print(json.dumps(res, indent=4))

if __name__ == "__main__":
    asyncio.run(delete())

Efficient Resource Management with aiohttp

To optimize the efficiency of operations, it is advisable to minimize the creation of a new ClientSession for each operation, as doing so can incur unnecessary costs. Instead, a more economical approach is to create a single ClientSession section and reuse it for making multiple requests.

In the provided Python scripts for asynchronous operations, you’ll notice the use of aiohttp.ClientSession() within an asynchronous context manager. By establishing a single ClientSession and utilizing it across various operations, you significantly reduce the overhead associated with creating new sessions for each request.

This consolidated approach enhances resource utilization and responsiveness, as the session setup and teardown processes are handled efficiently. It also promotes better code organization and readability, as the shared ClientSession becomes a central component for managing asynchronous requests.

Retrying Requests with Aiohttp

In real-world scenarios, network issues or server errors may cause requests to fail intermittently. Aiohttp provides built-in support for retrying failed requests, ensuring robustness in your application. By configuring retry strategies, developers can specify conditions for retries, such as maximum attempts and backoff intervals.

Conclusion

The integration of Asyncio and aiohttp libraries in Python provides a valuable means for executing asynchronous requests. Throughout this tutorial, we have explored the practical implementation of asynchronous RESTful CRUD requests in Python. By leveraging these libraries, developers can enhance the efficiency of their programs when dealing with tasks that involve communication with external servers or APIs.

Comments

There are no comments yet.

Write a comment

You can use the Markdown syntax to format your comment.

Tags: asyncio python python async