// plain
To set headers in an aiohttp request in Python, you can use the add_headers
method. This method takes a dictionary of headers as an argument. For example:
import aiohttp
async with aiohttp.ClientSession() as session:
async with session.get('http://example.com', headers={'User-Agent': 'My custom user agent'}) as response:
print(response.status)
200
The code above sets the User-Agent
header to My custom user agent
and prints the response status code.
The code consists of the following parts:
import aiohttp
- imports the aiohttp libraryasync with aiohttp.ClientSession() as session
- creates a client sessionasync with session.get('http://example.com', headers={'User-Agent': 'My custom user agent'}) as response
- sends a GET request tohttp://example.com
with theUser-Agent
header set toMy custom user agent
print(response.status)
- prints the response status code
group: aiohttp
onelinerhub: How to set headers in an aiohttp request in Python?