When building web applications and APIs with aiohttp, we often need to send data in our requests to the server. This data allows the client to provide information to the server for processing, storage, or to influence application flow.
There are a few common ways to send data in aiohttp requests:
JSON Data
JSON is a ubiquitous data format in web APIs and aiohttp makes it easy to send. We simply pass a Python dict to the
import aiohttp
data = {'key1': 'value1', 'key2': 'value2'}
async with aiohttp.ClientSession() as session:
async with session.post('https://api.example.com/endpoint', json=data) as response:
print(response.status)
The aiohttp request will automatically JSON encode the data and send it with a
Form Data
To send form data, the same way an HTML form would send data, we can use the
data = {'username': 'john', 'password': '1234'}
async with session.post('https://api.example.com/login', data=data) as response:
print(await response.text())
The data dict will be form encoded and the correct header will also be added.
File Uploads
aiohttp makes it easy to upload files in requests as well. We use the
files = {'upload_file': open('report.pdf', 'rb')}
async with session.post('https://api.example.com/upload', files=files) as response:
print(response.status)
This will properly handle the file upload including multi-part encoding and random boundary generation.
Custom Headers
We can also add custom headers to requests using the
headers = {'X-Auth-Token': 'secret-token'}
async with session.get('https://api.example.com/data', headers=headers) as response:
print(await response.json())
This allows adding authentication, content-type, or any other custom headers needed.
Handling Errors
When posting data, errors may occur so its important to handle them properly:
try:
async with session.post('https://api.example.com/create', json=data) as response:
print(response.status)
except aiohttp.ClientResponseError as e:
print(e.status)
print(e.message)
This makes sure any 4xx or 5xx errors from the server are handled cleanly.
Posting data is essential for most aiohttp based apps and APIs. Using json, form data, file uploads, and custom headers gives the flexibility needed for interacting with third party APIs or building your own. By handling errors and exceptions properly, we can build robust apps and clients.