Pass a dictionary (or any mapping) to the request’s headers= argument. For headers shared by every call, pass the mapping when you create aiohttp.ClientSession. Header names are case-insensitive, so Authorization, authorization, and other spellings identify the same field.
The examples below use a reusable session, explicit error handling, environment-stored credentials, and both JSON and raw-body requests.
Add headers to one aiohttp request
Install aiohttp in the environment used by your application:
python -m pip install aiohttp
This complete program sends an ID, an Accept value, and a bearer token on one request:
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minute#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
import asyncio
import aiohttp
async def main():
url = "https://api.example.com/items"
headers = {
"X-Request-ID": "abc123",
"Accept": "application/json",
"Authorization": "Bearer YOUR_TOKEN",
}
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers) as response:
response.raise_for_status()
data = await response.json()
print(data)
asyncio.run(main())
The mapping is applied to that call only. response.raise_for_status() turns HTTP 4xx and 5xx responses into an exception before the JSON is processed; this prevents an error document from being mistaken for a successful result.
For a one-off call without a reusable session, aiohttp also exposes aiohttp.request(). The session interface is normally preferable because it manages a connection pool and keep-alive connections.
Set default headers for every request in a session
Supply headers= to ClientSession when a value belongs on all requests made by that session:
import asyncio
import aiohttp
async def main():
default_headers = {
"User-Agent": "my-aiohttp-client/1.0",
"Accept": "application/json",
}
async with aiohttp.ClientSession(headers=default_headers) as session:
async with session.get("https://api.example.com/items") as response:
response.raise_for_status()
print(await response.json())
asyncio.run(main())
Session defaults are useful for a stable user agent, an API version, or authorization shared by a group of calls. Use a per-request mapping when a value is specific to one operation or must be changed temporarily. Keep tokens out of source code by reading them from an environment variable or secret manager.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Repair Windows errors before they cause bigger problems3Fix the driver behind crashes, sound loss and screen glitchesimport os
import aiohttp
TOKEN = os.environ["API_TOKEN"]
async with aiohttp.ClientSession(
headers={"Authorization": f"Bearer {TOKEN}"}
) as session:
...
Choose per-request or session-wide headers
| Decision | headers= on request |
headers= on ClientSession |
|---|---|---|
| Scope | One call | Every call made by that session |
| Override needs | Best for request-specific values | Defaults can be overridden for an individual call |
| Credential rotation | Easy to supply a newly fetched token per call | Update the session’s default mapping deliberately when credentials change |
| Lifecycle | Still benefits from a shared session | Designed around one session reused and closed with async with |
A request mapping is the clearest choice when two calls use different tenants, correlation IDs, or tokens. A session mapping avoids repeating genuinely common fields.
Send an Authorization header
Bearer authentication is just a string value in the mapping. Do not include extra quotes around the token:
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
headers = {
"Authorization": f"Bearer {token}",
"Accept": "application/json",
}
async with session.get(url, headers=headers) as response:
response.raise_for_status()
Other schemes use the same mechanism, for example Basic credentials or an API key header defined by the service. Follow that API’s exact scheme and spelling; aiohttp itself does not interpret the authentication value.
Combine headers with JSON or other request bodies
JSON payloads
Use json= when the body is a Python object that should be serialized as JSON. Add authorization, correlation, or explicit accept values through headers=:
Recommended Free Tools
payload = {"name": "Ada", "active": True}
headers = {
"Authorization": f"Bearer {token}",
"X-Request-ID": "create-42",
"Accept": "application/json",
}
async with session.post(
"https://api.example.com/items",
json=payload,
headers=headers,
) as response:
response.raise_for_status()
item = await response.json()
The json= convenience argument handles JSON serialization and the appropriate content type. You generally should not manually serialize the object with json.dumps() unless you have a specific reason.
Raw bytes or text
When sending already encoded bytes, set the content type yourself:
body = b"raw payload"
headers = {
"Content-Type": "application/octet-stream",
"Authorization": f"Bearer {token}",
}
async with session.post(url, data=body, headers=headers) as response:
response.raise_for_status()
For form data, use aiohttp’s supported data argument and choose the content type required by the endpoint.
Header names, values, and middleware
The client reference describes request.headers as a case-insensitive multidict. Header spelling is therefore not a reliable way to create two separate fields. A server may still impose its own requirements for a particular value, so follow the API documentation.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Client middleware can add, replace, or inspect headers before transmission. In a larger application, document which layer owns authentication, tracing IDs, user-agent changes, and retries. Otherwise a middleware rule can silently replace a value you supplied at the call site.
Headers should be text values. Convert numbers, UUID objects, and other types to strings before placing them in the mapping. Never log authorization tokens or cookies when logging the mapping or a prepared request.
Reuse and close the ClientSession
ClientSession encapsulates a connection pool and supports keep-alives. Reusing one session for related requests avoids repeatedly creating TCP and TLS connections:
async with aiohttp.ClientSession(headers=common_headers) as session:
async with session.get(first_url) as first:
first.raise_for_status()
first_data = await first.json()
async with session.get(second_url, headers={"X-Request-ID": "second"}) as second:
second.raise_for_status()
second_data = await second.json()
The async with block closes the session even when an exception occurs. If your application owns a long-lived session, close it during application shutdown. Creating a new session for every small request defeats connection reuse and can exhaust sockets under load.
Override a session default for one call
Pass another mapping on the individual request when one call needs a different value:
async with aiohttp.ClientSession(
headers={"Accept": "application/json", "X-Environment": "production"}
) as session:
async with session.get(
url,
headers={"X-Environment": "staging", "X-Request-ID": "abc123"},
) as response:
response.raise_for_status()
Use this pattern for per-request tracing IDs, alternate media types, or a token selected for one tenant. Keep the intended precedence clear in code and tests, especially when middleware also modifies headers.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Why a custom header may not be sent
The request is not the one you changed
Check that the mapping is passed to the actual session.get(), post(), or other method being executed. A mapping defined elsewhere has no effect until supplied through headers=.
A middleware or wrapper replaced it
Inspect middleware, retry helpers, and API-client wrappers for code that rebuilds the mapping. Apply the final value in one documented layer and avoid mutating a shared dictionary concurrently.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →The server rejects the value
Confirm the required header name, authentication scheme, media type, and value format in that service’s documentation. A case difference in the name is not normally the cause because aiohttp treats names case-insensitively.
The token is empty or expired
Print a redacted diagnostic such as the token’s presence and length, not the token itself. Read it from the expected environment or secret store, refresh it according to the provider’s rules, and retry only when the API permits safe retries.
You are inspecting the wrong response
Call raise_for_status(), then inspect the status and response body for the server’s explanation. Redirects, proxies, and authentication gateways can produce a response different from the origin API you intended to call.
Raw JSON was sent with the wrong content type
If you pass bytes or a string through data=, set Content-Type: application/json and ensure the bytes are valid JSON. Prefer json=payload for ordinary JSON requests.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Debug headers safely
Log the destination, status code, request ID, and a redacted header map. Remove or mask Authorization, cookies, API keys, and any personal data. Never paste complete production request headers into an issue tracker. For reproducible tests, use a local or dedicated endpoint that records requests without exposing secrets.
Remember that an HTTP client cannot force a browser-only header or bypass a proxy’s policy. A proxy, gateway, or server may remove, add, or reject fields after aiohttp has prepared the request.
Performance, reliability, and security considerations
- Reuse a
ClientSessionto gain connection pooling and keep-alives. - Use explicit timeouts appropriate to the API and handle
aiohttpconnection and timeout exceptions at the application boundary. - Generate a unique correlation header such as
X-Request-IDper operation when the service supports tracing. - Do not put secrets in URLs, source control, debug logs, or exception messages.
- Retry only failures that are safe to retry; pair retries with an idempotency key for APIs that support one.
- Keep shared header mappings stable. Build a new mapping for a request-specific change instead of mutating a dictionary while other coroutines use it.
Or skip the browser setup
If your goal is to obtain a clean screenshot of a URL rather than build a browser automation stack, ScreenshotNeo provides a website screenshot API. Its endpoint accepts a URL and can return PNG, JPEG, WebP, or PDF. A one-call request looks like this (see the ScreenshotNeo API documentation for all options):
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Before capture it accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. An MCP server supplies take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Official references
- aiohttp client reference — sessions, request methods, headers, and lifecycle.
- aiohttp advanced client usage — custom headers, JSON requests, and advanced client behavior.
- aiohttp documentation source.
Frequently Asked Questions
Can I pass a regular dictionary as aiohttp headers?
Yes. A dictionary or another mapping is accepted by the request and session headers parameters.
Are aiohttp header names case-sensitive?
No. aiohttp exposes request headers through a case-insensitive multidict, so capitalization does not distinguish fields.
Should I create a new ClientSession for every request?
Usually no. Reuse a session for related calls so its connection pool and keep-alive connections can be used, and close it with async with or during application shutdown.
How can I prevent an Authorization token from leaking into logs?
Redact sensitive fields before logging and keep credentials in environment variables or a secret manager rather than source code.
Free tools Windows power users keep installed
One-click scans. No signup required.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

