[파이썬] aiohttp JSON 데이터 전송 및 수신하기

In this blog post, we will explore how to send and receive JSON data using the aiohttp library in Python. aiohttp is a powerful asynchronous HTTP client/server library that is commonly used for web scraping, web API requests, and building web applications.

Sending JSON Data

To send JSON data using aiohttp, we can use the POST method along with the json parameter. Let’s take a look at an example:

import aiohttp
import asyncio

async def send_json_data():
    url = "https://example.com/api"
    data = {
        "name": "John Doe",
        "age": 25,
        "email": "johndoe@example.com"
    }

    async with aiohttp.ClientSession() as session:
        async with session.post(url, json=data) as response:
            if response.status == 200:
                print("JSON data sent successfully.")
            else:
                print("Failed to send JSON data.")

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

In the above example, we first define the JSON data we want to send as a Python dictionary. Then, we create an aiohttp ClientSession and use the post method to send a POST request to the specified URL with the JSON payload. The json parameter automatically serializes the dictionary to JSON format.

Receiving JSON Data

To receive JSON data using aiohttp, we can use the GET method and then parse the received JSON response. Here’s an example:

import aiohttp
import asyncio

async def receive_json_data():
    url = "https://example.com/api"

    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            if response.status == 200:
                data = await response.json()
                print("Received JSON data:")
                print(data)
            else:
                print("Failed to receive JSON data.")

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

In the above example, we again create an aiohttp ClientSession and use the get method to send a GET request to the specified URL. If the response status is 200 (OK), we can use the json method of the response object to parse the JSON data into a Python dictionary. We can then access and manipulate the received JSON data as needed.

Conclusion

In this blog post, we learned how to send and receive JSON data using the aiohttp library in Python. Sending JSON data is as simple as using the json parameter with the POST method, while receiving JSON data involves parsing the JSON response using the json method of the response object. With these techniques, you can easily interact with JSON-based APIs and services using asynchronous programming in Python.