0
# Requests
1
2
Python HTTP for Humans - an elegant and simple HTTP library that abstracts the complexities of making HTTP requests behind a beautiful, simple API. Requests allows you to send HTTP/1.1 requests extremely easily with features like automatic content decoding, connection pooling, cookie persistence, authentication, and comprehensive SSL verification.
3
4
## Package Information
5
6
- **Package Name**: requests
7
- **Language**: Python
8
- **Installation**: `pip install requests`
9
- **Version**: 2.32.4
10
11
## Core Imports
12
13
```python
14
import requests
15
```
16
17
Individual components:
18
19
```python
20
from requests import Session, Request, PreparedRequest, Response, codes
21
from requests.auth import HTTPBasicAuth, HTTPDigestAuth, HTTPProxyAuth, AuthBase
22
from requests.exceptions import (
23
RequestException, HTTPError, ConnectionError, Timeout, ConnectTimeout,
24
ReadTimeout, URLRequired, TooManyRedirects, SSLError, JSONDecodeError
25
)
26
from requests.adapters import HTTPAdapter, BaseAdapter
27
from requests.structures import CaseInsensitiveDict, LookupDict
28
from requests.cookies import RequestsCookieJar
29
```
30
31
## Basic Usage
32
33
```python
34
import requests
35
36
# Simple GET request
37
response = requests.get('https://api.github.com/user', auth=('user', 'pass'))
38
print(response.status_code)
39
print(response.json())
40
41
# POST request with JSON data
42
data = {'key': 'value'}
43
response = requests.post('https://httpbin.org/post', json=data)
44
45
# Using sessions for persistent settings
46
session = requests.Session()
47
session.auth = ('user', 'pass')
48
session.headers.update({'Custom-Header': 'value'})
49
50
response = session.get('https://api.example.com/data')
51
```
52
53
## Architecture
54
55
Requests is built around several key components:
56
57
- **HTTP Methods**: Simple functions (get, post, put, etc.) that create and send requests
58
- **Session**: Persistent configuration and connection pooling across requests
59
- **Request/PreparedRequest**: Request objects representing HTTP requests before sending
60
- **Response**: Response objects containing server responses with convenient access methods
61
- **Authentication**: Pluggable authentication handlers for various auth schemes
62
- **Adapters**: Transport adapters that handle the actual HTTP communication
63
- **Exceptions**: Comprehensive exception hierarchy for different error conditions
64
65
## Capabilities
66
67
### HTTP Methods
68
69
Core HTTP method functions for making requests with various verbs. These are the primary interface most users interact with.
70
71
```python { .api }
72
def request(method: str, url: str, **kwargs) -> Response: ...
73
def get(url: str, params=None, **kwargs) -> Response: ...
74
def post(url: str, data=None, json=None, **kwargs) -> Response: ...
75
def put(url: str, data=None, **kwargs) -> Response: ...
76
def patch(url: str, data=None, **kwargs) -> Response: ...
77
def delete(url: str, **kwargs) -> Response: ...
78
def head(url: str, **kwargs) -> Response: ...
79
def options(url: str, **kwargs) -> Response: ...
80
```
81
82
[HTTP Methods](./http-methods.md)
83
84
### Sessions
85
86
Session objects provide persistent configuration, connection pooling, and cookie persistence across multiple requests.
87
88
```python { .api }
89
class Session:
90
def __init__(self): ...
91
def request(self, method: str, url: str, **kwargs) -> Response: ...
92
def get(self, url: str, **kwargs) -> Response: ...
93
def post(self, url: str, **kwargs) -> Response: ...
94
def close(self): ...
95
96
def session() -> Session: ...
97
```
98
99
[Sessions](./sessions.md)
100
101
### Request and Response Objects
102
103
Core objects representing HTTP requests and responses with full control over request preparation and response handling.
104
105
```python { .api }
106
class Request:
107
def __init__(self, method=None, url=None, headers=None, files=None,
108
data=None, params=None, auth=None, cookies=None,
109
hooks=None, json=None): ...
110
def prepare(self) -> PreparedRequest: ...
111
112
class Response:
113
content: bytes
114
text: str
115
status_code: int
116
headers: dict
117
cookies: dict
118
url: str
119
def json(self, **kwargs) -> dict: ...
120
def raise_for_status(self): ...
121
```
122
123
[Request and Response Objects](./models.md)
124
125
### Authentication
126
127
Authentication handlers for various HTTP authentication schemes including Basic, Digest, and custom authentication.
128
129
```python { .api }
130
class HTTPBasicAuth:
131
def __init__(self, username: str, password: str): ...
132
133
class HTTPDigestAuth:
134
def __init__(self, username: str, password: str): ...
135
136
class HTTPProxyAuth(HTTPBasicAuth): ...
137
```
138
139
[Authentication](./authentication.md)
140
141
### Exception Handling
142
143
Comprehensive exception hierarchy for handling various error conditions that can occur during HTTP requests.
144
145
```python { .api }
146
class RequestException(IOError): ...
147
class HTTPError(RequestException): ...
148
class ConnectionError(RequestException): ...
149
class Timeout(RequestException): ...
150
class ConnectTimeout(ConnectionError, Timeout): ...
151
class ReadTimeout(Timeout): ...
152
class URLRequired(RequestException): ...
153
class TooManyRedirects(RequestException): ...
154
class SSLError(ConnectionError): ...
155
```
156
157
[Exception Handling](./exceptions.md)
158
159
### Status Codes
160
161
Convenient access to HTTP status codes through named constants and lookup functionality.
162
163
```python { .api }
164
codes: dict # Lookup dict for status codes
165
# Usage: codes.ok == 200, codes['not_found'] == 404
166
```
167
168
[Status Codes](./status-codes.md)
169
170
### Cookie Handling
171
172
Cookie management functionality providing a dict-like interface for handling HTTP cookies with compatibility for both client and server-side cookie operations.
173
174
```python { .api }
175
class RequestsCookieJar:
176
def __init__(self, policy=None): ...
177
def get(self, name: str, default=None, domain=None, path=None) -> str: ...
178
def set(self, name: str, value: str, **kwargs): ...
179
def __getitem__(self, name: str) -> str: ...
180
def __setitem__(self, name: str, value: str): ...
181
182
def cookiejar_from_dict(cookie_dict: dict, cookiejar=None, overwrite=True): ...
183
def merge_cookies(cookiejar, cookies): ...
184
```
185
186
[Cookie Handling](./cookies.md)
187
188
### Transport Adapters
189
190
Transport adapters handle the actual HTTP communication, providing the interface between requests and underlying HTTP libraries.
191
192
```python { .api }
193
class BaseAdapter:
194
def send(self, request, stream=False, timeout=None, verify=True,
195
cert=None, proxies=None) -> Response: ...
196
def close(self): ...
197
198
class HTTPAdapter(BaseAdapter):
199
def __init__(self, pool_connections=10, pool_maxsize=10, max_retries=0,
200
pool_block=False): ...
201
def send(self, request, **kwargs) -> Response: ...
202
def mount(self, prefix: str, adapter): ...
203
```
204
205
[Transport Adapters](./adapters.md)
206
207
### Data Structures
208
209
Data structure classes that provide enhanced dictionary interfaces with special behaviors for HTTP-related operations.
210
211
```python { .api }
212
class CaseInsensitiveDict(dict):
213
def __init__(self, data=None, **kwargs): ...
214
def __getitem__(self, key): ...
215
def __setitem__(self, key, value): ...
216
def copy(self) -> 'CaseInsensitiveDict': ...
217
218
class LookupDict(dict):
219
def __init__(self, name=None): ...
220
def __getitem__(self, key): ...
221
def get(self, key, default=None): ...
222
```
223
224
[Data Structures](./structures.md)
225
226
### Event Hooks
227
228
Event hook system that allows custom functions to be called at specific points during request processing.
229
230
```python { .api }
231
HOOKS: list[str] # ['response']
232
233
def default_hooks() -> dict: ...
234
def dispatch_hook(key: str, hooks: dict, hook_data, **kwargs): ...
235
```
236
237
[Event Hooks](./hooks.md)
238
239
## Types
240
241
```python { .api }
242
from typing import Dict, Optional, Union, Any, List, Tuple, IO
243
from datetime import timedelta
244
245
# Common type aliases
246
JSONType = Union[Dict[str, Any], List[Any], str, int, float, bool, None]
247
AuthType = Union[Tuple[str, str], HTTPBasicAuth, HTTPDigestAuth, HTTPProxyAuth, AuthBase]
248
CookiesType = Union[Dict[str, str], RequestsCookieJar]
249
HeadersType = Union[Dict[str, str], CaseInsensitiveDict]
250
ParamsType = Union[Dict[str, str], List[Tuple[str, str]], bytes]
251
DataType = Union[Dict[str, Any], List[Tuple[str, str]], str, bytes, IO]
252
FilesType = Dict[str, Union[str, bytes, IO, Tuple[str, Union[str, bytes, IO]],
253
Tuple[str, Union[str, bytes, IO], str],
254
Tuple[str, Union[str, bytes, IO], str, Dict[str, str]]]]
255
ProxiesType = Dict[str, str]
256
TimeoutType = Union[float, Tuple[float, float]]
257
VerifyType = Union[bool, str]
258
CertType = Union[str, Tuple[str, str]]
259
HooksType = Dict[str, List[callable]]
260
AdapterType = BaseAdapter
261
```