# aiohttp

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.

## Package Information

- **Package Name**: aiohttp
- **Language**: Python  
- **Installation**: `pip install aiohttp`

## Core Imports

```python
import aiohttp
```

For HTTP client operations:

```python
import aiohttp
# or import specific components
from aiohttp import ClientSession, ClientTimeout
```

For web server development:

```python
from aiohttp import web
# or import specific web components
from aiohttp.web import Application, Response, json_response, run_app
```

Complete web framework import:

```python
# Import the web framework
from aiohttp import web

# Access all web components through web module
app = web.Application()
response = web.Response(text="Hello World")
```

## Basic Usage

### HTTP Client

```python
import aiohttp
import asyncio

async def fetch_data():
    async with aiohttp.ClientSession() as session:
        async with session.get('https://api.example.com/data') as response:
            data = await response.json()
            return data

# Run the async function
data = asyncio.run(fetch_data())
```

### Web Server

```python
from aiohttp import web

async def hello_handler(request):
    return web.Response(text="Hello, World!")

app = web.Application()
app.router.add_get('/', hello_handler)

if __name__ == '__main__':
    web.run_app(app, host='localhost', port=8080)
```

## Architecture

aiohttp follows a layered architecture:

- **Client Layer**: HTTP client sessions with connection pooling, timeout management, and automatic cookie handling
- **Server Layer**: WSGI-compatible web server with application containers, routing, and middleware support
- **Transport Layer**: Asyncio-based network transport with SSL/TLS support and connection management
- **Protocol Layer**: HTTP/1.1 protocol implementation with WebSocket upgrade support
- **Data Layer**: Payload handling system supporting various data types and streaming

This design enables both high-performance HTTP clients and scalable web servers while maintaining full asyncio compatibility.

## Capabilities

### HTTP Client Operations

Comprehensive HTTP client functionality including sessions, connectors, authentication, and connection management. Supports all HTTP methods, automatic redirects, cookie handling, and extensive configuration options.

```python { .api }
class ClientSession:
    def __init__(self, timeout=None, connector=None, cookie_jar=None, **kwargs): ...
    
async def request(method, url, **kwargs): ...

class ClientResponse:
    async def text(self): ...
    async def json(self): ...
    async def read(self): ...
```

[HTTP Client](./client.md)

### Web Server Framework

Full-featured web server with applications, routing, middleware, and request/response handling. Includes support for static files, WebSocket connections, and extensible middleware system.

```python { .api }
class Application:
    def __init__(self, **kwargs): ...
    
class Request:
    async def text(self): ...
    async def json(self): ...
    async def post(self): ...

class Response:
    def __init__(self, text=None, body=None, status=200, **kwargs): ...

def run_app(app, host=None, port=None, **kwargs): ...
```

[Web Server](./server.md)

### WebSocket Support

Client and server WebSocket implementation with message handling, connection management, and protocol support. Enables real-time bidirectional communication.

```python { .api }
class ClientWebSocketResponse:
    async def send_str(self, data): ...
    async def receive(self): ...
    async def close(self): ...

class WebSocketResponse:
    async def prepare(self, request): ...
    async def send_str(self, data): ...
    async def receive(self): ...
```

[WebSocket Support](./websocket.md)

### Data Handling and Payloads

Comprehensive data processing system supporting various payload types, multipart handling, form data, and streaming. Includes automatic content encoding and decoding.

```python { .api }
class FormData:
    def add_field(self, name, value, **kwargs): ...

class MultipartReader:
    async def next(self): ...

class MultipartWriter:
    append(self, obj, headers=None): ...
```

[Data Handling](./data.md)

### Testing Infrastructure

Complete testing utilities including test servers, test clients, and pytest integration. Enables comprehensive testing of both client and server applications.

```python { .api }
class TestClient:
    async def get(self, path, **kwargs): ...
    async def post(self, path, **kwargs): ...

class TestServer:
    def __init__(self, app, **kwargs): ...
```

[Testing](./testing.md)

### Utilities and Extensions

Supporting utilities including tracing, DNS resolution, authentication helpers, and Gunicorn workers. Provides integration points and extensibility features.

```python { .api }
class TraceConfig:
    def on_request_start(self, callback): ...
    def on_request_end(self, callback): ...

class BasicAuth:
    def __init__(self, login, password): ...
```

[Utilities](./utilities.md)

## Types

### Core Types

```python { .api }
import json
from typing import Optional, Union, Dict, Any, Callable
from multidict import CIMultiDict
from yarl import URL

# Type aliases used throughout the API
StrOrURL = Union[str, URL]
LooseHeaders = Union[Dict[str, str], CIMultiDict]
JsonSerializable = Union[Dict[str, Any], list, str, int, float, bool, None]
```

### Client Types

```python { .api }
class ClientTimeout:
    def __init__(self, total=None, sock_connect=None, sock_read=None): ...

class RequestInfo:
    url: URL
    method: str
    headers: CIMultiDict
```

### Server Types

```python { .api }
class AppKey:
    def __init__(self, name: str, t: type): ...

Handler = Callable[[Request], Response]
Middleware = Callable[[Request, Handler], Response]
```