0
# aiohttp
1
2
A comprehensive asynchronous HTTP client/server framework built on Python's asyncio. aiohttp supports both client and server side of HTTP protocol with built-in WebSocket support, avoiding callback hell through async/await syntax. The framework offers a web server with middleware and pluggable routing capabilities, making it suitable for building modern web applications and APIs.
3
4
## Package Information
5
6
- **Package Name**: aiohttp
7
- **Language**: Python
8
- **Installation**: `pip install aiohttp`
9
10
## Core Imports
11
12
```python
13
import aiohttp
14
```
15
16
For HTTP client operations:
17
18
```python
19
import aiohttp
20
# or import specific components
21
from aiohttp import ClientSession, ClientTimeout
22
```
23
24
For web server development:
25
26
```python
27
from aiohttp import web
28
# or import specific web components
29
from aiohttp.web import Application, Response, json_response, run_app
30
```
31
32
Complete web framework import:
33
34
```python
35
# Import the web framework
36
from aiohttp import web
37
38
# Access all web components through web module
39
app = web.Application()
40
response = web.Response(text="Hello World")
41
```
42
43
## Basic Usage
44
45
### HTTP Client
46
47
```python
48
import aiohttp
49
import asyncio
50
51
async def fetch_data():
52
async with aiohttp.ClientSession() as session:
53
async with session.get('https://api.example.com/data') as response:
54
data = await response.json()
55
return data
56
57
# Run the async function
58
data = asyncio.run(fetch_data())
59
```
60
61
### Web Server
62
63
```python
64
from aiohttp import web
65
66
async def hello_handler(request):
67
return web.Response(text="Hello, World!")
68
69
app = web.Application()
70
app.router.add_get('/', hello_handler)
71
72
if __name__ == '__main__':
73
web.run_app(app, host='localhost', port=8080)
74
```
75
76
## Architecture
77
78
aiohttp follows a layered architecture:
79
80
- **Client Layer**: HTTP client sessions with connection pooling, timeout management, and automatic cookie handling
81
- **Server Layer**: WSGI-compatible web server with application containers, routing, and middleware support
82
- **Transport Layer**: Asyncio-based network transport with SSL/TLS support and connection management
83
- **Protocol Layer**: HTTP/1.1 protocol implementation with WebSocket upgrade support
84
- **Data Layer**: Payload handling system supporting various data types and streaming
85
86
This design enables both high-performance HTTP clients and scalable web servers while maintaining full asyncio compatibility.
87
88
## Capabilities
89
90
### HTTP Client Operations
91
92
Comprehensive HTTP client functionality including sessions, connectors, authentication, and connection management. Supports all HTTP methods, automatic redirects, cookie handling, and extensive configuration options.
93
94
```python { .api }
95
class ClientSession:
96
def __init__(self, timeout=None, connector=None, cookie_jar=None, **kwargs): ...
97
98
async def request(method, url, **kwargs): ...
99
100
class ClientResponse:
101
async def text(self): ...
102
async def json(self): ...
103
async def read(self): ...
104
```
105
106
[HTTP Client](./client.md)
107
108
### Web Server Framework
109
110
Full-featured web server with applications, routing, middleware, and request/response handling. Includes support for static files, WebSocket connections, and extensible middleware system.
111
112
```python { .api }
113
class Application:
114
def __init__(self, **kwargs): ...
115
116
class Request:
117
async def text(self): ...
118
async def json(self): ...
119
async def post(self): ...
120
121
class Response:
122
def __init__(self, text=None, body=None, status=200, **kwargs): ...
123
124
def run_app(app, host=None, port=None, **kwargs): ...
125
```
126
127
[Web Server](./server.md)
128
129
### WebSocket Support
130
131
Client and server WebSocket implementation with message handling, connection management, and protocol support. Enables real-time bidirectional communication.
132
133
```python { .api }
134
class ClientWebSocketResponse:
135
async def send_str(self, data): ...
136
async def receive(self): ...
137
async def close(self): ...
138
139
class WebSocketResponse:
140
async def prepare(self, request): ...
141
async def send_str(self, data): ...
142
async def receive(self): ...
143
```
144
145
[WebSocket Support](./websocket.md)
146
147
### Data Handling and Payloads
148
149
Comprehensive data processing system supporting various payload types, multipart handling, form data, and streaming. Includes automatic content encoding and decoding.
150
151
```python { .api }
152
class FormData:
153
def add_field(self, name, value, **kwargs): ...
154
155
class MultipartReader:
156
async def next(self): ...
157
158
class MultipartWriter:
159
append(self, obj, headers=None): ...
160
```
161
162
[Data Handling](./data.md)
163
164
### Testing Infrastructure
165
166
Complete testing utilities including test servers, test clients, and pytest integration. Enables comprehensive testing of both client and server applications.
167
168
```python { .api }
169
class TestClient:
170
async def get(self, path, **kwargs): ...
171
async def post(self, path, **kwargs): ...
172
173
class TestServer:
174
def __init__(self, app, **kwargs): ...
175
```
176
177
[Testing](./testing.md)
178
179
### Utilities and Extensions
180
181
Supporting utilities including tracing, DNS resolution, authentication helpers, and Gunicorn workers. Provides integration points and extensibility features.
182
183
```python { .api }
184
class TraceConfig:
185
def on_request_start(self, callback): ...
186
def on_request_end(self, callback): ...
187
188
class BasicAuth:
189
def __init__(self, login, password): ...
190
```
191
192
[Utilities](./utilities.md)
193
194
## Types
195
196
### Core Types
197
198
```python { .api }
199
import json
200
from typing import Optional, Union, Dict, Any, Callable
201
from multidict import CIMultiDict
202
from yarl import URL
203
204
# Type aliases used throughout the API
205
StrOrURL = Union[str, URL]
206
LooseHeaders = Union[Dict[str, str], CIMultiDict]
207
JsonSerializable = Union[Dict[str, Any], list, str, int, float, bool, None]
208
```
209
210
### Client Types
211
212
```python { .api }
213
class ClientTimeout:
214
def __init__(self, total=None, sock_connect=None, sock_read=None): ...
215
216
class RequestInfo:
217
url: URL
218
method: str
219
headers: CIMultiDict
220
```
221
222
### Server Types
223
224
```python { .api }
225
class AppKey:
226
def __init__(self, name: str, t: type): ...
227
228
Handler = Callable[[Request], Response]
229
Middleware = Callable[[Request, Handler], Response]
230
```