[파이썬] aiohttp GET 요청 수행하기

aiohttp is a powerful asynchronous HTTP client and server library for Python. It provides a convenient way to make HTTP requests and handle responses asynchronously. In this blog post, we will learn how to perform a GET request using aiohttp in Python.

Installation

First, let’s install aiohttp using pip:

pip install aiohttp

Once installed, we can start making GET requests to retrieve data from a server.

Importing Required Libraries

Start by importing the necessary libraries for our example:

import aiohttp
import asyncio

Making a GET Request

Next, let’s define a function that will make a GET request to a given URL:

async def get_data(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.text()

In the above code, we create a new ClientSession and use it to make the GET request. We then retrieve the response and return its content as text.

Executing the Request

To execute the GET request, we need to create an event loop and call our get_data function inside it:

async def main():
    url = "https://api.example.com/data"
    data = await get_data(url)
    print(data)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

In the above code, we define the main function that calls the get_data function with a specific URL. We then retrieve the data and print it.

Finally, we create an event loop using asyncio.get_event_loop() and run the main function until it completes using loop.run_until_complete(main()).

Conclusion

In this blog post, we learned how to perform a GET request using aiohttp in Python. We saw how to install aiohttp, import the required libraries, make a GET request, and execute the request using an event loop.

aiohttp provides a simple and efficient way to perform HTTP requests asynchronously, making it a great choice for building Python applications that interact with external APIs or web services.