or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async-client.mdauthentication.mdconfiguration.mdindex.mdrequests-api.mdstreaming.mdsync-client.mdtypes.md

types.mddocs/

0

# Core Types API

1

2

Core data model classes for representing HTTP requests, responses, headers, and other fundamental httpx objects.

3

4

## Overview

5

6

These classes represent the fundamental data structures used throughout httpx. They provide rich APIs for inspecting and manipulating HTTP messages.

7

8

## Capabilities

9

10

### Response Class

11

12

```python { .api }

13

class Response:

14

"""

15

HTTP response object containing status, headers, and content.

16

17

Attributes:

18

status_code (int): HTTP status code (e.g., 200, 404)

19

headers (Headers): Response headers

20

content (bytes): Raw response body content

21

text (str): Response body as decoded text

22

url (URL): Final URL after any redirects

23

request (Request): Associated request object

24

history (list[Response]): List of redirect responses

25

cookies (Cookies): Response cookies

26

is_closed (bool): Whether response has been closed

27

is_stream_consumed (bool): Whether streaming content has been consumed

28

http_version (str): HTTP version used ("HTTP/1.1" or "HTTP/2")

29

reason_phrase (str): HTTP reason phrase

30

elapsed (timedelta): Request/response duration

31

encoding (str): Character encoding for text content

32

"""

33

34

def json(self, **kwargs):

35

"""

36

Parse response content as JSON.

37

38

Args:

39

**kwargs: Arguments passed to json.loads()

40

41

Returns:

42

any: Parsed JSON content

43

44

Raises:

45

JSONDecodeError: If content is not valid JSON

46

"""

47

48

def raise_for_status(self):

49

"""

50

Raise HTTPStatusError for 4xx/5xx status codes.

51

52

Raises:

53

HTTPStatusError: If status_code is 400 or higher

54

55

Returns:

56

Response: Self (for method chaining)

57

"""

58

59

def read(self):

60

"""

61

Read and return the response content as bytes.

62

63

Returns:

64

bytes: Response content

65

"""

66

67

async def aread(self):

68

"""

69

Read and return the response content as bytes (async).

70

71

Returns:

72

bytes: Response content

73

"""

74

75

def iter_bytes(self, chunk_size=1024):

76

"""

77

Iterate over response content as bytes chunks.

78

79

Args:

80

chunk_size (int): Size of each chunk (default: 1024)

81

82

Yields:

83

bytes: Chunks of response content

84

"""

85

86

async def aiter_bytes(self, chunk_size=1024):

87

"""

88

Iterate over response content as bytes chunks (async).

89

90

Args:

91

chunk_size (int): Size of each chunk (default: 1024)

92

93

Yields:

94

bytes: Chunks of response content

95

"""

96

97

def iter_text(self, chunk_size=1024):

98

"""

99

Iterate over response content as text chunks.

100

101

Args:

102

chunk_size (int): Size of each chunk in bytes (default: 1024)

103

104

Yields:

105

str: Text chunks of response content

106

"""

107

108

async def aiter_text(self, chunk_size=1024):

109

"""

110

Iterate over response content as text chunks (async).

111

112

Args:

113

chunk_size (int): Size of each chunk in bytes (default: 1024)

114

115

Yields:

116

str: Text chunks of response content

117

"""

118

119

def iter_lines(self):

120

"""

121

Iterate over response content as text lines.

122

123

Yields:

124

str: Lines of response content

125

"""

126

127

async def aiter_lines(self):

128

"""

129

Iterate over response content as text lines (async).

130

131

Yields:

132

str: Lines of response content

133

"""

134

135

def iter_raw(self, chunk_size=1024):

136

"""

137

Iterate over raw response content without decoding.

138

139

Args:

140

chunk_size (int): Size of each chunk (default: 1024)

141

142

Yields:

143

bytes: Raw chunks of response content

144

"""

145

146

async def aiter_raw(self, chunk_size=1024):

147

"""

148

Iterate over raw response content without decoding (async).

149

150

Args:

151

chunk_size (int): Size of each chunk (default: 1024)

152

153

Yields:

154

bytes: Raw chunks of response content

155

"""

156

157

def close(self):

158

"""Close the response and release connection."""

159

160

async def aclose(self):

161

"""Close the response and release connection (async)."""

162

163

# Status code properties

164

@property

165

def is_informational(self):

166

"""True for 1xx status codes."""

167

return 100 <= self.status_code < 200

168

169

@property

170

def is_success(self):

171

"""True for 2xx status codes."""

172

return 200 <= self.status_code < 300

173

174

@property

175

def is_redirect(self):

176

"""True for 3xx status codes."""

177

return 300 <= self.status_code < 400

178

179

@property

180

def is_client_error(self):

181

"""True for 4xx status codes."""

182

return 400 <= self.status_code < 500

183

184

@property

185

def is_server_error(self):

186

"""True for 5xx status codes."""

187

return 500 <= self.status_code < 600

188

189

@property

190

def is_error(self):

191

"""True for 4xx and 5xx status codes."""

192

return 400 <= self.status_code < 600

193

```

194

195

### Request Class

196

197

```python { .api }

198

class Request:

199

"""

200

HTTP request object containing method, URL, headers, and content.

201

202

Attributes:

203

method (str): HTTP method (GET, POST, etc.)

204

url (URL): Request URL

205

headers (Headers): Request headers

206

content (bytes): Request body content (after reading)

207

extensions (dict): Request extensions/metadata

208

"""

209

210

def read(self):

211

"""

212

Read and return the request content as bytes.

213

214

Returns:

215

bytes: Request content

216

"""

217

218

async def aread(self):

219

"""

220

Read and return the request content as bytes (async).

221

222

Returns:

223

bytes: Request content

224

"""

225

```

226

227

### Headers Class

228

229

```python { .api }

230

class Headers:

231

"""

232

Case-insensitive HTTP headers collection.

233

234

Implements MutableMapping[str, str] interface.

235

236

Attributes:

237

encoding (str): Header encoding (ascii, utf-8, or iso-8859-1)

238

raw (list[tuple[bytes, bytes]]): Raw header items as bytes

239

"""

240

241

def __init__(self, headers=None, encoding=None):

242

"""

243

Initialize headers collection.

244

245

Args:

246

headers (dict | list | Headers, optional): Initial headers

247

encoding (str, optional): Header encoding

248

"""

249

250

def get(self, key, default=None):

251

"""

252

Get header value with default.

253

254

Args:

255

key (str): Header name (case-insensitive)

256

default (str, optional): Default value if header not found

257

258

Returns:

259

str: Header value or default

260

"""

261

262

def get_list(self, key, split_commas=False):

263

"""

264

Get all values for a header as a list.

265

266

Args:

267

key (str): Header name (case-insensitive)

268

split_commas (bool): Whether to split comma-separated values

269

270

Returns:

271

list[str]: List of header values

272

"""

273

274

def update(self, headers):

275

"""

276

Update headers with new values.

277

278

Args:

279

headers (dict | list | Headers): Headers to add/update

280

"""

281

282

def copy(self):

283

"""

284

Create a copy of the headers.

285

286

Returns:

287

Headers: New headers instance

288

"""

289

290

def keys(self):

291

"""Return header names."""

292

293

def values(self):

294

"""Return header values."""

295

296

def items(self):

297

"""Return header name-value pairs."""

298

299

def multi_items(self):

300

"""

301

Return all header pairs including duplicates.

302

303

Returns:

304

list[tuple[str, str]]: All header name-value pairs

305

"""

306

```

307

308

### Cookies Class

309

310

```python { .api }

311

class Cookies:

312

"""

313

HTTP cookies as mutable mapping.

314

315

Implements MutableMapping[str, str] interface.

316

317

Attributes:

318

jar (CookieJar): Underlying cookie jar

319

"""

320

321

def __init__(self, cookies=None):

322

"""

323

Initialize cookies collection.

324

325

Args:

326

cookies (dict | list | Cookies, optional): Initial cookies

327

"""

328

329

def set(self, name, value, domain="", path="/"):

330

"""

331

Set a cookie.

332

333

Args:

334

name (str): Cookie name

335

value (str): Cookie value

336

domain (str): Cookie domain (default: "")

337

path (str): Cookie path (default: "/")

338

"""

339

340

def get(self, name, default=None, domain=None, path=None):

341

"""

342

Get cookie value.

343

344

Args:

345

name (str): Cookie name

346

default (str, optional): Default value if cookie not found

347

domain (str, optional): Cookie domain

348

path (str, optional): Cookie path

349

350

Returns:

351

str: Cookie value or default

352

"""

353

354

def delete(self, name, domain=None, path=None):

355

"""

356

Delete a cookie.

357

358

Args:

359

name (str): Cookie name

360

domain (str, optional): Cookie domain

361

path (str, optional): Cookie path

362

"""

363

364

def clear(self, domain=None, path=None):

365

"""

366

Clear cookies.

367

368

Args:

369

domain (str, optional): Only clear cookies for this domain

370

path (str, optional): Only clear cookies for this path

371

"""

372

373

def update(self, cookies):

374

"""

375

Update cookies with new values.

376

377

Args:

378

cookies (dict | Cookies): Cookies to add/update

379

"""

380

381

def extract_cookies(self, response):

382

"""

383

Extract cookies from response Set-Cookie headers.

384

385

Args:

386

response (Response): Response to extract cookies from

387

"""

388

389

def set_cookie_header(self, request):

390

"""

391

Set Cookie header on request.

392

393

Args:

394

request (Request): Request to set Cookie header on

395

"""

396

```

397

398

### URL Class

399

400

```python { .api }

401

class URL:

402

"""

403

URL parsing and manipulation.

404

405

Attributes:

406

scheme (str): URL scheme (normalized lowercase)

407

userinfo (bytes): Raw userinfo as bytes

408

username (str): URL-decoded username

409

password (str): URL-decoded password

410

host (str): Host (normalized, IDNA decoded)

411

port (int | None): Port number (None for default ports)

412

path (str): URL-decoded path

413

query (bytes): Raw query string as bytes

414

params (QueryParams): Parsed query parameters

415

fragment (str): URL fragment (without #)

416

is_absolute_url (bool): True if absolute URL

417

is_relative_url (bool): True if relative URL

418

"""

419

420

def __init__(self, url=""):

421

"""

422

Initialize URL.

423

424

Args:

425

url (str): URL string to parse

426

"""

427

428

def copy_with(self, **kwargs):

429

"""

430

Create modified copy of URL.

431

432

Args:

433

**kwargs: URL components to modify (scheme, host, port, path, etc.)

434

435

Returns:

436

URL: New URL instance with modifications

437

"""

438

439

def copy_set_param(self, key, value):

440

"""

441

Create copy with query parameter set.

442

443

Args:

444

key (str): Parameter name

445

value (str): Parameter value

446

447

Returns:

448

URL: New URL with parameter set

449

"""

450

451

def copy_add_param(self, key, value):

452

"""

453

Create copy with query parameter added.

454

455

Args:

456

key (str): Parameter name

457

value (str): Parameter value

458

459

Returns:

460

URL: New URL with parameter added

461

"""

462

463

def copy_remove_param(self, key):

464

"""

465

Create copy with query parameter removed.

466

467

Args:

468

key (str): Parameter name to remove

469

470

Returns:

471

URL: New URL with parameter removed

472

"""

473

474

def copy_merge_params(self, params):

475

"""

476

Create copy with query parameters merged.

477

478

Args:

479

params (dict | QueryParams): Parameters to merge

480

481

Returns:

482

URL: New URL with parameters merged

483

"""

484

485

def join(self, url):

486

"""

487

Join with relative URL.

488

489

Args:

490

url (str | URL): Relative URL to join

491

492

Returns:

493

URL: Joined URL

494

"""

495

```

496

497

### QueryParams Class

498

499

```python { .api }

500

class QueryParams:

501

"""

502

URL query parameters as immutable multi-dict.

503

504

Implements Mapping[str, str] interface.

505

"""

506

507

def __init__(self, params=None):

508

"""

509

Initialize query parameters.

510

511

Args:

512

params (str | dict | list | QueryParams, optional): Initial parameters

513

"""

514

515

def get(self, key, default=None):

516

"""

517

Get first value for parameter.

518

519

Args:

520

key (str): Parameter name

521

default (str, optional): Default if parameter not found

522

523

Returns:

524

str: Parameter value or default

525

"""

526

527

def get_list(self, key):

528

"""

529

Get all values for parameter.

530

531

Args:

532

key (str): Parameter name

533

534

Returns:

535

list[str]: All values for parameter

536

"""

537

538

def set(self, key, value):

539

"""

540

Return new instance with parameter set.

541

542

Args:

543

key (str): Parameter name

544

value (str): Parameter value

545

546

Returns:

547

QueryParams: New instance with parameter set

548

"""

549

550

def add(self, key, value):

551

"""

552

Return new instance with parameter added.

553

554

Args:

555

key (str): Parameter name

556

value (str): Parameter value

557

558

Returns:

559

QueryParams: New instance with parameter added

560

"""

561

562

def remove(self, key):

563

"""

564

Return new instance with parameter removed.

565

566

Args:

567

key (str): Parameter name to remove

568

569

Returns:

570

QueryParams: New instance with parameter removed

571

"""

572

573

def merge(self, params):

574

"""

575

Return merged instance.

576

577

Args:

578

params (dict | QueryParams): Parameters to merge

579

580

Returns:

581

QueryParams: New merged instance

582

"""

583

584

def keys(self):

585

"""Return parameter names."""

586

587

def values(self):

588

"""Return parameter values."""

589

590

def items(self):

591

"""Return parameter name-value pairs."""

592

593

def multi_items(self):

594

"""

595

Return all parameter pairs including duplicates.

596

597

Returns:

598

list[tuple[str, str]]: All parameter name-value pairs

599

"""

600

```

601

602

## Usage Examples

603

604

### Working with Response

605

606

```python

607

import httpx

608

609

response = httpx.get('https://httpbin.org/json')

610

611

# Status and headers

612

print(response.status_code) # 200

613

print(response.headers['content-type']) # 'application/json'

614

615

# Content access

616

print(response.text) # Response as text

617

print(response.content) # Response as bytes

618

print(response.json()) # Parse JSON

619

620

# Status checks

621

if response.is_success:

622

print("Request succeeded")

623

624

# Raise exception for error status

625

response.raise_for_status()

626

```

627

628

### Headers Manipulation

629

630

```python

631

import httpx

632

633

headers = httpx.Headers({

634

'User-Agent': 'MyApp/1.0',

635

'Accept': 'application/json'

636

})

637

638

# Case-insensitive access

639

print(headers['user-agent']) # 'MyApp/1.0'

640

print(headers.get('accept')) # 'application/json'

641

642

# Multiple values

643

headers.update({'Accept': 'text/html'})

644

all_accepts = headers.get_list('accept')

645

```

646

647

### URL Construction

648

649

```python

650

import httpx

651

652

url = httpx.URL('https://example.com/path')

653

print(url.host) # 'example.com'

654

print(url.path) # '/path'

655

656

# URL manipulation

657

new_url = url.copy_with(path='/new-path')

658

with_params = url.copy_set_param('page', '1')

659

660

# Join URLs

661

base = httpx.URL('https://api.example.com/')

662

endpoint = base.join('users/123')

663

```

664

665

### Query Parameters

666

667

```python

668

import httpx

669

670

params = httpx.QueryParams({'page': '1', 'limit': '10'})

671

print(params.get('page')) # '1'

672

673

# Immutable operations

674

new_params = params.set('page', '2')

675

more_params = params.add('filter', 'active')

676

```

677

678

### Response Streaming

679

680

```python

681

import httpx

682

683

with httpx.stream('GET', 'https://example.com/large-file') as response:

684

for chunk in response.iter_bytes():

685

process_chunk(chunk)

686

687

# Or iterate text

688

for line in response.iter_lines():

689

process_line(line)

690

```

691

692

## Type Aliases

693

694

These type aliases define the parameter types accepted by httpx functions and classes.

695

696

```python { .api }

697

# URL types

698

URL = URL # URL class

699

URLTypes = Union[URL, str]

700

701

# Query parameter types

702

QueryParamTypes = Union[

703

QueryParams,

704

Mapping[str, Union[str, int, float, bool, None, Sequence[Union[str, int, float, bool, None]]]],

705

List[Tuple[str, Union[str, int, float, bool, None]]],

706

Tuple[Tuple[str, Union[str, int, float, bool, None]], ...],

707

str,

708

bytes,

709

]

710

711

# Header types

712

HeaderTypes = Union[

713

Headers,

714

Mapping[str, str],

715

Mapping[bytes, bytes],

716

Sequence[Tuple[str, str]],

717

Sequence[Tuple[bytes, bytes]],

718

]

719

720

# Cookie types

721

CookieTypes = Union[Cookies, CookieJar, Dict[str, str], List[Tuple[str, str]]]

722

723

# Timeout types

724

TimeoutTypes = Union[

725

Optional[float],

726

Tuple[Optional[float], Optional[float], Optional[float], Optional[float]],

727

Timeout,

728

]

729

730

# Proxy types

731

ProxyTypes = Union[URL, str, Proxy]

732

733

# SSL certificate types

734

CertTypes = Union[str, Tuple[str, str], Tuple[str, str, str]]

735

736

# Authentication types

737

AuthTypes = Union[

738

Tuple[Union[str, bytes], Union[str, bytes]],

739

Callable[[Request], Request],

740

Auth,

741

]

742

743

# Request content types

744

RequestContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]]

745

ResponseContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]]

746

747

# Request data types

748

RequestData = Mapping[str, Any]

749

750

# File upload types

751

FileContent = Union[IO[bytes], bytes, str]

752

FileTypes = Union[

753

FileContent,

754

Tuple[Optional[str], FileContent],

755

Tuple[Optional[str], FileContent, Optional[str]],

756

Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]],

757

]

758

RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]]

759

760

# Request extension types

761

RequestExtensions = Mapping[str, Any]

762

ResponseExtensions = Mapping[str, Any]

763

764

# Event hook types

765

EventHook = Callable[..., Any]

766

767

# Stream types

768

SyncByteStream = Iterator[bytes]

769

AsyncByteStream = AsyncIterator[bytes]

770

```

771

772

## Constants

773

774

```python { .api }

775

# Default timeout configuration

776

DEFAULT_TIMEOUT_CONFIG: Timeout

777

778

# Default connection limits

779

DEFAULT_LIMITS: Limits

780

781

# Default maximum redirects

782

DEFAULT_MAX_REDIRECTS: int

783

784

# Client default sentinel value

785

USE_CLIENT_DEFAULT: UseClientDefault

786

787

class UseClientDefault:

788

"""Sentinel value indicating client default should be used."""

789

```