or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-features.mdasync-requests.mdexceptions.mdindex.mdmodels.mdsessions.mdsync-requests.md

async-requests.mddocs/

0

# Asynchronous HTTP Requests

1

2

Async versions of all HTTP methods for high-performance concurrent request handling. These functions enable non-blocking HTTP operations and are ideal for applications requiring high throughput or concurrent request processing.

3

4

All async functions are prefixed with 'a' and return `AsyncResponse` objects. They support the same parameters as their synchronous counterparts.

5

6

## Capabilities

7

8

### Generic Async Request Function

9

10

The fundamental async request function that all other async HTTP methods build upon.

11

12

```python { .api }

13

async def arequest(

14

method: HttpMethodType,

15

url: str,

16

*,

17

params: QueryParameterType | None = None,

18

data: BodyType | AsyncBodyType | None = None,

19

headers: HeadersType | None = None,

20

cookies: CookiesType | None = None,

21

files: MultiPartFilesType | MultiPartFilesAltType | None = None,

22

auth: HttpAuthenticationType | AsyncHttpAuthenticationType | None = None,

23

timeout: TimeoutType | None = WRITE_DEFAULT_TIMEOUT,

24

allow_redirects: bool = True,

25

proxies: ProxyType | None = None,

26

hooks: AsyncHookType[PreparedRequest | Response] | None = None,

27

stream: bool | None = None,

28

verify: TLSVerifyType | None = None,

29

cert: TLSClientCertType | None = None,

30

json: Any | None = None,

31

retries: RetryType = DEFAULT_RETRIES,

32

) -> Response | AsyncResponse:

33

"""

34

Asynchronously constructs and sends a Request with the specified HTTP method.

35

36

Args:

37

method: HTTP method (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS)

38

url: Target URL for the request

39

params: Query parameters to append to URL

40

data: Request body data (supports async iterables)

41

json: JSON serializable object to send in request body

42

headers: HTTP headers to include in request

43

cookies: Cookies to send with request

44

files: Files for multipart upload

45

auth: Authentication credentials (supports async auth)

46

timeout: Request timeout in seconds

47

allow_redirects: Whether to follow HTTP redirects

48

proxies: Proxy configuration

49

verify: SSL certificate verification

50

stream: Controls response loading (None/False=immediate download as Response, True=lazy loading as AsyncResponse)

51

cert: Client SSL certificate

52

hooks: Request/response lifecycle hooks

53

retries: Retry configuration

54

55

Returns:

56

Response object if stream=None/False, AsyncResponse object if stream=True

57

"""

58

```

59

60

### Async GET Requests

61

62

Asynchronously retrieves data from the specified URL.

63

64

```python { .api }

65

async def aget(

66

url: str,

67

params: QueryParameterType | None = None,

68

*,

69

headers: HeadersType | None = None,

70

cookies: CookiesType | None = None,

71

auth: HttpAuthenticationType | AsyncHttpAuthenticationType | None = None,

72

timeout: TimeoutType | None = READ_DEFAULT_TIMEOUT,

73

allow_redirects: bool = True,

74

proxies: ProxyType | None = None,

75

hooks: AsyncHookType[PreparedRequest | Response] | None = None,

76

verify: TLSVerifyType | None = None,

77

stream: bool | None = None,

78

cert: TLSClientCertType | None = None,

79

retries: RetryType = DEFAULT_RETRIES,

80

**kwargs: Any,

81

) -> Response | AsyncResponse:

82

"""

83

Asynchronously sends a GET request to retrieve data.

84

85

Args:

86

url: Target URL

87

params: Query parameters

88

headers: HTTP headers

89

cookies: Cookies to send

90

auth: Authentication credentials

91

timeout: Request timeout (defaults to read timeout)

92

allow_redirects: Follow redirects (default: True)

93

proxies: Proxy configuration

94

verify: SSL verification

95

stream: Stream response content

96

cert: Client certificate

97

hooks: Request hooks

98

retries: Retry configuration

99

**kwargs: Additional arguments

100

101

Returns:

102

Response object if stream=None/False, AsyncResponse object if stream=True

103

"""

104

```

105

106

Usage example:

107

108

```python

109

import asyncio

110

import niquests

111

112

async def fetch_data():

113

# Simple async GET request

114

response = await niquests.aget('https://api.example.com/data')

115

data = await response.json()

116

return data

117

118

# Concurrent requests

119

async def fetch_multiple():

120

urls = [

121

'https://api.example.com/users/1',

122

'https://api.example.com/users/2',

123

'https://api.example.com/users/3'

124

]

125

126

tasks = [niquests.aget(url) for url in urls]

127

responses = await asyncio.gather(*tasks)

128

129

results = []

130

for response in responses:

131

data = await response.json()

132

results.append(data)

133

134

return results

135

136

# Run async functions

137

data = asyncio.run(fetch_data())

138

multiple_data = asyncio.run(fetch_multiple())

139

```

140

141

### Async POST Requests

142

143

Asynchronously sends data to the server for processing.

144

145

```python { .api }

146

async def apost(

147

url: str,

148

data: BodyType | AsyncBodyType | None = None,

149

json: Any | None = None,

150

*,

151

params: QueryParameterType | None = None,

152

headers: HeadersType | None = None,

153

cookies: CookiesType | None = None,

154

files: MultiPartFilesType | MultiPartFilesAltType | None = None,

155

auth: HttpAuthenticationType | AsyncHttpAuthenticationType | None = None,

156

timeout: TimeoutType | None = WRITE_DEFAULT_TIMEOUT,

157

allow_redirects: bool = True,

158

proxies: ProxyType | None = None,

159

hooks: AsyncHookType[PreparedRequest | Response] | None = None,

160

verify: TLSVerifyType | None = None,

161

stream: bool | None = None,

162

cert: TLSClientCertType | None = None,

163

retries: RetryType = DEFAULT_RETRIES,

164

) -> Response | AsyncResponse:

165

"""

166

Asynchronously sends a POST request with optional data payload.

167

168

Args:

169

url: Target URL

170

data: Request body data (supports async iterables)

171

json: JSON data to serialize and send

172

params: Query parameters

173

headers: HTTP headers

174

cookies: Cookies

175

files: Files for multipart upload

176

auth: Authentication

177

timeout: Request timeout

178

allow_redirects: Follow redirects

179

proxies: Proxy configuration

180

verify: SSL verification

181

stream: Stream response

182

cert: Client certificate

183

hooks: Request hooks

184

retries: Retry configuration

185

186

Returns:

187

Response object if stream=None/False, AsyncResponse object if stream=True

188

"""

189

```

190

191

Usage example:

192

193

```python

194

async def create_user():

195

user_data = {

196

'name': 'John Doe',

197

'email': 'john@example.com',

198

'age': 30

199

}

200

201

response = await niquests.apost(

202

'https://api.example.com/users',

203

json=user_data

204

)

205

206

if response.status_code == 201:

207

created_user = await response.json()

208

return created_user

209

else:

210

raise Exception(f"Failed to create user: {response.status_code}")

211

```

212

213

### Async PUT Requests

214

215

Asynchronously updates or replaces a resource on the server.

216

217

```python { .api }

218

async def aput(

219

url: str,

220

data: AsyncBodyType | None = None,

221

*,

222

json: Any | None = None,

223

params: QueryParameterType | None = None,

224

headers: HeadersType | None = None,

225

cookies: CookiesType | None = None,

226

files: MultiPartFilesType | MultiPartFilesAltType | None = None,

227

auth: AsyncHttpAuthenticationType | None = None,

228

timeout: TimeoutType | None = WRITE_DEFAULT_TIMEOUT,

229

allow_redirects: bool = True,

230

proxies: ProxyType | None = None,

231

verify: TLSVerifyType = True,

232

stream: bool = False,

233

cert: TLSClientCertType | None = None,

234

hooks: HookType[PreparedRequest | AsyncResponse] | None = None,

235

retries: RetryType = DEFAULT_RETRIES,

236

) -> AsyncResponse:

237

"""

238

Asynchronously sends a PUT request to update or replace a resource.

239

"""

240

```

241

242

### Async PATCH Requests

243

244

Asynchronously performs partial updates on a resource.

245

246

```python { .api }

247

async def apatch(

248

url: str,

249

data: AsyncBodyType | None = None,

250

*,

251

json: Any | None = None,

252

params: QueryParameterType | None = None,

253

headers: HeadersType | None = None,

254

cookies: CookiesType | None = None,

255

files: MultiPartFilesType | MultiPartFilesAltType | None = None,

256

auth: AsyncHttpAuthenticationType | None = None,

257

timeout: TimeoutType | None = WRITE_DEFAULT_TIMEOUT,

258

allow_redirects: bool = True,

259

proxies: ProxyType | None = None,

260

verify: TLSVerifyType = True,

261

stream: bool = False,

262

cert: TLSClientCertType | None = None,

263

hooks: HookType[PreparedRequest | AsyncResponse] | None = None,

264

retries: RetryType = DEFAULT_RETRIES,

265

) -> AsyncResponse:

266

"""

267

Asynchronously sends a PATCH request for partial resource updates.

268

"""

269

```

270

271

### Async DELETE Requests

272

273

Asynchronously removes a resource from the server.

274

275

```python { .api }

276

async def adelete(

277

url: str,

278

*,

279

params: QueryParameterType | None = None,

280

headers: HeadersType | None = None,

281

cookies: CookiesType | None = None,

282

auth: AsyncHttpAuthenticationType | None = None,

283

timeout: TimeoutType | None = WRITE_DEFAULT_TIMEOUT,

284

allow_redirects: bool = True,

285

proxies: ProxyType | None = None,

286

verify: TLSVerifyType = True,

287

stream: bool = False,

288

cert: TLSClientCertType | None = None,

289

hooks: HookType[PreparedRequest | AsyncResponse] | None = None,

290

retries: RetryType = DEFAULT_RETRIES,

291

**kwargs: Any,

292

) -> AsyncResponse:

293

"""

294

Asynchronously sends a DELETE request to remove a resource.

295

"""

296

```

297

298

### Async HEAD Requests

299

300

Asynchronously retrieves only headers without downloading the body content.

301

302

```python { .api }

303

async def ahead(

304

url: str,

305

*,

306

params: QueryParameterType | None = None,

307

headers: HeadersType | None = None,

308

cookies: CookiesType | None = None,

309

auth: AsyncHttpAuthenticationType | None = None,

310

timeout: TimeoutType | None = READ_DEFAULT_TIMEOUT,

311

allow_redirects: bool = False,

312

proxies: ProxyType | None = None,

313

verify: TLSVerifyType = True,

314

stream: bool = False,

315

cert: TLSClientCertType | None = None,

316

hooks: HookType[PreparedRequest | AsyncResponse] | None = None,

317

retries: RetryType = DEFAULT_RETRIES,

318

**kwargs: Any,

319

) -> AsyncResponse:

320

"""

321

Asynchronously sends a HEAD request to retrieve only response headers.

322

323

Note: allow_redirects defaults to False for HEAD requests.

324

"""

325

```

326

327

### Async OPTIONS Requests

328

329

Asynchronously queries server capabilities for a resource.

330

331

```python { .api }

332

async def aoptions(

333

url: str,

334

*,

335

params: QueryParameterType | None = None,

336

headers: HeadersType | None = None,

337

cookies: CookiesType | None = None,

338

auth: AsyncHttpAuthenticationType | None = None,

339

timeout: TimeoutType | None = READ_DEFAULT_TIMEOUT,

340

allow_redirects: bool = True,

341

proxies: ProxyType | None = None,

342

verify: TLSVerifyType = True,

343

stream: bool = False,

344

cert: TLSClientCertType | None = None,

345

hooks: HookType[PreparedRequest | AsyncResponse] | None = None,

346

retries: RetryType = DEFAULT_RETRIES,

347

**kwargs: Any,

348

) -> AsyncResponse:

349

"""

350

Asynchronously sends an OPTIONS request to query server capabilities.

351

"""

352

```

353

354

## Async-Specific Features

355

356

### Concurrent Request Processing

357

358

Async functions enable efficient concurrent request processing:

359

360

```python

361

import asyncio

362

import niquests

363

364

async def process_urls_concurrently(urls):

365

"""Process multiple URLs concurrently for maximum throughput."""

366

367

# Create tasks for all requests

368

tasks = []

369

for url in urls:

370

task = niquests.aget(url)

371

tasks.append(task)

372

373

# Execute all requests concurrently

374

responses = await asyncio.gather(*tasks, return_exceptions=True)

375

376

# Process results

377

results = []

378

for i, response in enumerate(responses):

379

if isinstance(response, Exception):

380

results.append({'url': urls[i], 'error': str(response)})

381

else:

382

try:

383

data = await response.json()

384

results.append({'url': urls[i], 'data': data})

385

except Exception as e:

386

results.append({'url': urls[i], 'error': str(e)})

387

388

return results

389

390

# Usage

391

urls = ['https://api.example.com/endpoint1', 'https://api.example.com/endpoint2']

392

results = asyncio.run(process_urls_concurrently(urls))

393

```

394

395

### Async Body Data

396

397

Async functions support async iterables for request body data:

398

399

```python

400

async def stream_data():

401

"""Example of streaming data asynchronously."""

402

403

async def data_generator():

404

for i in range(1000):

405

yield f"chunk-{i}\n".encode()

406

await asyncio.sleep(0.001) # Simulate async data production

407

408

response = await niquests.apost(

409

'https://api.example.com/stream',

410

data=data_generator(),

411

headers={'Content-Type': 'text/plain'}

412

)

413

414

return await response.text()

415

```

416

417

## Type Definitions

418

419

```python { .api }

420

AsyncBodyType = Union[str, bytes, dict, list, IOBase, AsyncIterable[bytes]]

421

AsyncHttpAuthenticationType = Union[

422

Tuple[str, str],

423

HTTPBasicAuth,

424

BearerTokenAuth,

425

Callable[[PreparedRequest], Awaitable[PreparedRequest]]

426

]

427

```

428

429

## Error Handling

430

431

Async functions raise the same exceptions as their synchronous counterparts. Use try-except blocks within async functions:

432

433

```python

434

async def safe_request(url):

435

"""Example of proper async error handling."""

436

try:

437

response = await niquests.aget(url, timeout=10.0)

438

response.raise_for_status() # Raise exception for HTTP errors

439

return await response.json()

440

except niquests.ConnectionError:

441

return {'error': 'Connection failed'}

442

except niquests.Timeout:

443

return {'error': 'Request timed out'}

444

except niquests.HTTPError as e:

445

return {'error': f'HTTP error: {e.response.status_code}'}

446

except Exception as e:

447

return {'error': f'Unexpected error: {str(e)}'}

448

```