or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-responses.mdapi-routing.mdbackground-tasks.mdcore-application.mddata-utilities.mddependency-injection.mdexception-handling.mdindex.mdmiddleware.mdrequest-parameters.mdrequest-response.mdsecurity-authentication.mdstatic-templating.mdtesting.mdwebsocket-support.md

index.mddocs/

0

# FastAPI

1

2

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints. It provides automatic API documentation, data validation, serialization, and authentication capabilities with exceptional performance on par with NodeJS and Go.

3

4

## Package Information

5

6

- **Package Name**: fastapi

7

- **Language**: Python

8

- **Installation**: `pip install fastapi`

9

- **Requirements**: Python 3.8+

10

- **Main Dependencies**: Starlette, Pydantic

11

12

## Core Imports

13

14

```python

15

from fastapi import FastAPI

16

```

17

18

Common imports for building APIs:

19

20

```python

21

from fastapi import FastAPI, APIRouter, Depends, HTTPException

22

from fastapi import Query, Path, Body, Header, Cookie, Form, File

23

from fastapi import Request, Response, BackgroundTasks

24

from fastapi import WebSocket, WebSocketDisconnect

25

from fastapi import UploadFile, __version__, status

26

from fastapi.security import HTTPBearer, OAuth2PasswordBearer, APIKeyHeader

27

from fastapi.middleware.cors import CORSMiddleware

28

from fastapi.responses import JSONResponse, HTMLResponse, RedirectResponse

29

from fastapi.staticfiles import StaticFiles

30

from fastapi.templating import Jinja2Templates

31

from fastapi.testclient import TestClient

32

from fastapi.encoders import jsonable_encoder

33

```

34

35

## Basic Usage

36

37

```python

38

from fastapi import FastAPI, Query

39

from typing import Optional

40

41

# Create FastAPI application

42

app = FastAPI(

43

title="My API",

44

description="A simple API example",

45

version="1.0.0"

46

)

47

48

# Simple GET endpoint

49

@app.get("/")

50

def read_root():

51

return {"Hello": "World"}

52

53

# GET endpoint with path parameter

54

@app.get("/items/{item_id}")

55

def read_item(item_id: int, q: Optional[str] = Query(None)):

56

return {"item_id": item_id, "q": q}

57

58

# POST endpoint with request body

59

from pydantic import BaseModel

60

61

class Item(BaseModel):

62

name: str

63

price: float

64

is_offer: Optional[bool] = None

65

66

@app.post("/items/")

67

def create_item(item: Item):

68

return item

69

70

# Run the application (for development)

71

if __name__ == "__main__":

72

import uvicorn

73

uvicorn.run(app, host="0.0.0.0", port=8000)

74

```

75

76

## Architecture

77

78

FastAPI builds on the Starlette ASGI framework and uses Pydantic for data validation:

79

80

- **FastAPI Application**: Main application class that manages routes, middleware, and configuration

81

- **APIRouter**: Router for organizing and grouping related endpoints

82

- **Parameter Functions**: Type-safe parameter declaration (Query, Path, Body, etc.)

83

- **Pydantic Integration**: Automatic request/response validation and serialization

84

- **Starlette Foundation**: High-performance ASGI framework providing core web functionality

85

- **Automatic Documentation**: OpenAPI schema generation with interactive Swagger UI and ReDoc

86

87

This architecture enables rapid development of production-ready APIs with automatic validation, serialization, and documentation generation while maintaining high performance and type safety.

88

89

## Capabilities

90

91

### Core Application

92

93

Main FastAPI application class and basic routing functionality. The FastAPI class serves as the central application instance that manages all routes, middleware, dependencies, and configuration.

94

95

```python { .api }

96

class FastAPI:

97

def __init__(

98

self,

99

*,

100

debug: bool = False,

101

routes: List[BaseRoute] = None,

102

title: str = "FastAPI",

103

description: str = "",

104

version: str = "0.1.0",

105

openapi_url: str = "/openapi.json",

106

openapi_tags: List[dict] = None,

107

servers: List[dict] = None,

108

dependencies: List[Depends] = None,

109

default_response_class: Type[Response] = Default(JSONResponse),

110

docs_url: str = "/docs",

111

redoc_url: str = "/redoc",

112

swagger_ui_oauth2_redirect_url: str = "/docs/oauth2-redirect",

113

swagger_ui_init_oauth: dict = None,

114

middleware: List[Middleware] = None,

115

exception_handlers: dict = None,

116

on_startup: List[Callable] = None,

117

on_shutdown: List[Callable] = None,

118

lifespan: Lifespan = None,

119

**extra: Any,

120

) -> None: ...

121

122

def get(self, path: str, **kwargs) -> Callable: ...

123

def post(self, path: str, **kwargs) -> Callable: ...

124

def put(self, path: str, **kwargs) -> Callable: ...

125

def delete(self, path: str, **kwargs) -> Callable: ...

126

def patch(self, path: str, **kwargs) -> Callable: ...

127

def head(self, path: str, **kwargs) -> Callable: ...

128

def options(self, path: str, **kwargs) -> Callable: ...

129

def trace(self, path: str, **kwargs) -> Callable: ...

130

def websocket(self, path: str, **kwargs) -> Callable: ...

131

132

def include_router(self, router: APIRouter, **kwargs) -> None: ...

133

def add_api_route(self, path: str, endpoint: Callable, **kwargs) -> None: ...

134

def add_api_websocket_route(self, path: str, endpoint: Callable, **kwargs) -> None: ...

135

def middleware(self, middleware_type: str) -> Callable: ...

136

def exception_handler(self, exc_class_or_status_code: Union[int, Exception]) -> Callable: ...

137

```

138

139

[Core Application](./core-application.md)

140

141

### API Routing

142

143

Router for organizing and grouping related API endpoints with shared configuration, middleware, and dependencies.

144

145

```python { .api }

146

class APIRouter:

147

def __init__(

148

self,

149

*,

150

prefix: str = "",

151

tags: List[str] = None,

152

dependencies: List[Depends] = None,

153

default_response_class: Type[Response] = Default(JSONResponse),

154

responses: dict = None,

155

callbacks: List[BaseRoute] = None,

156

routes: List[BaseRoute] = None,

157

redirect_slashes: bool = True,

158

default: ASGIApp = None,

159

dependency_overrides_provider: Any = None,

160

route_class: Type[APIRoute] = APIRoute,

161

on_startup: List[Callable] = None,

162

on_shutdown: List[Callable] = None,

163

lifespan: Lifespan = None,

164

deprecated: bool = None,

165

include_in_schema: bool = True,

166

**kwargs: Any,

167

) -> None: ...

168

169

def get(self, path: str, **kwargs) -> Callable: ...

170

def post(self, path: str, **kwargs) -> Callable: ...

171

def put(self, path: str, **kwargs) -> Callable: ...

172

def delete(self, path: str, **kwargs) -> Callable: ...

173

def patch(self, path: str, **kwargs) -> Callable: ...

174

def head(self, path: str, **kwargs) -> Callable: ...

175

def options(self, path: str, **kwargs) -> Callable: ...

176

def trace(self, path: str, **kwargs) -> Callable: ...

177

def websocket(self, path: str, **kwargs) -> Callable: ...

178

179

def include_router(self, router: APIRouter, **kwargs) -> None: ...

180

def add_api_route(self, path: str, endpoint: Callable, **kwargs) -> None: ...

181

```

182

183

[API Routing](./api-routing.md)

184

185

### Request Parameters

186

187

Type-safe parameter declaration functions for handling path parameters, query parameters, headers, cookies, request bodies, form data, and file uploads.

188

189

```python { .api }

190

def Path(

191

default: Any = ...,

192

*,

193

alias: str = None,

194

title: str = None,

195

description: str = None,

196

gt: float = None,

197

ge: float = None,

198

lt: float = None,

199

le: float = None,

200

min_length: int = None,

201

max_length: int = None,

202

regex: str = None,

203

example: Any = None,

204

examples: dict = None,

205

deprecated: bool = None,

206

include_in_schema: bool = True,

207

**extra: Any,

208

) -> Any: ...

209

210

def Query(

211

default: Any = Undefined,

212

*,

213

alias: str = None,

214

title: str = None,

215

description: str = None,

216

gt: float = None,

217

ge: float = None,

218

lt: float = None,

219

le: float = None,

220

min_length: int = None,

221

max_length: int = None,

222

regex: str = None,

223

example: Any = None,

224

examples: dict = None,

225

deprecated: bool = None,

226

include_in_schema: bool = True,

227

**extra: Any,

228

) -> Any: ...

229

230

def Body(

231

default: Any = Undefined,

232

*,

233

embed: bool = None,

234

media_type: str = "application/json",

235

alias: str = None,

236

title: str = None,

237

description: str = None,

238

example: Any = None,

239

examples: dict = None,

240

deprecated: bool = None,

241

include_in_schema: bool = True,

242

**extra: Any,

243

) -> Any: ...

244

245

def Form(

246

default: Any = Undefined,

247

*,

248

media_type: str = "application/x-www-form-urlencoded",

249

alias: str = None,

250

title: str = None,

251

description: str = None,

252

example: Any = None,

253

examples: dict = None,

254

deprecated: bool = None,

255

include_in_schema: bool = True,

256

**extra: Any,

257

) -> Any: ...

258

259

def File(

260

default: Any = Undefined,

261

*,

262

media_type: str = "multipart/form-data",

263

alias: str = None,

264

title: str = None,

265

description: str = None,

266

example: Any = None,

267

examples: dict = None,

268

deprecated: bool = None,

269

include_in_schema: bool = True,

270

**extra: Any,

271

) -> Any: ...

272

```

273

274

[Request Parameters](./request-parameters.md)

275

276

### Dependency Injection

277

278

Powerful dependency injection system for sharing code, database connections, authentication, and other common functionality across endpoints.

279

280

```python { .api }

281

def Depends(dependency: Callable = None, *, use_cache: bool = True) -> Any: ...

282

283

def Security(

284

dependency: Callable = None,

285

*,

286

scopes: List[str] = None,

287

use_cache: bool = True,

288

) -> Any: ...

289

```

290

291

[Dependency Injection](./dependency-injection.md)

292

293

### Request and Response Handling

294

295

Request and response objects for accessing HTTP data and customizing response behavior.

296

297

```python { .api }

298

class Request:

299

# Starlette Request object with all HTTP request functionality

300

pass

301

302

class Response:

303

def __init__(

304

self,

305

content: Any = None,

306

status_code: int = 200,

307

headers: dict = None,

308

media_type: str = None,

309

background: BackgroundTask = None,

310

) -> None: ...

311

312

class JSONResponse(Response):

313

def __init__(

314

self,

315

content: Any = None,

316

status_code: int = 200,

317

headers: dict = None,

318

media_type: str = "application/json",

319

background: BackgroundTask = None,

320

) -> None: ...

321

322

class UploadFile:

323

filename: str

324

content_type: str

325

file: BinaryIO

326

327

async def read(self, size: int = -1) -> bytes: ...

328

async def readline(self, size: int = -1) -> bytes: ...

329

async def readlines(self) -> List[bytes]: ...

330

async def write(self, data: bytes) -> None: ...

331

async def seek(self, offset: int) -> None: ...

332

async def close(self) -> None: ...

333

```

334

335

[Request and Response](./request-response.md)

336

337

### WebSocket Support

338

339

WebSocket support for real-time bidirectional communication between client and server.

340

341

```python { .api }

342

class WebSocket:

343

# Starlette WebSocket object with full WebSocket functionality

344

async def accept(self, subprotocol: str = None, headers: dict = None) -> None: ...

345

async def receive_text(self) -> str: ...

346

async def receive_bytes(self) -> bytes: ...

347

async def receive_json(self) -> Any: ...

348

async def send_text(self, data: str) -> None: ...

349

async def send_bytes(self, data: bytes) -> None: ...

350

async def send_json(self, data: Any) -> None: ...

351

async def close(self, code: int = 1000, reason: str = None) -> None: ...

352

353

class WebSocketDisconnect(Exception):

354

def __init__(self, code: int = 1000, reason: str = None) -> None: ...

355

```

356

357

[WebSocket Support](./websocket-support.md)

358

359

### Security and Authentication

360

361

Comprehensive security components for API key authentication, HTTP authentication (Basic, Bearer, Digest), and OAuth2 flows.

362

363

```python { .api }

364

class HTTPBearer:

365

def __init__(

366

self,

367

*,

368

bearerFormat: str = None,

369

scheme_name: str = None,

370

description: str = None,

371

auto_error: bool = True,

372

) -> None: ...

373

374

class OAuth2PasswordBearer:

375

def __init__(

376

self,

377

tokenUrl: str,

378

*,

379

scheme_name: str = None,

380

scopes: dict = None,

381

description: str = None,

382

auto_error: bool = True,

383

) -> None: ...

384

385

class APIKeyHeader:

386

def __init__(

387

self,

388

*,

389

name: str,

390

scheme_name: str = None,

391

description: str = None,

392

auto_error: bool = True,

393

) -> None: ...

394

```

395

396

[Security and Authentication](./security-authentication.md)

397

398

### Exception Handling

399

400

Exception classes for handling HTTP errors and WebSocket errors with proper status codes and error details.

401

402

```python { .api }

403

class HTTPException(Exception):

404

def __init__(

405

self,

406

status_code: int,

407

detail: Any = None,

408

headers: dict = None,

409

) -> None: ...

410

411

status_code: int

412

detail: Any

413

headers: dict

414

415

class WebSocketException(Exception):

416

def __init__(self, code: int, reason: str = None) -> None: ...

417

418

code: int

419

reason: str

420

```

421

422

[Exception Handling](./exception-handling.md)

423

424

### Middleware

425

426

Middleware components for cross-cutting concerns like CORS, compression, security headers, and custom request/response processing.

427

428

```python { .api }

429

class CORSMiddleware:

430

def __init__(

431

self,

432

app: ASGIApp,

433

*,

434

allow_origins: List[str] = None,

435

allow_methods: List[str] = None,

436

allow_headers: List[str] = None,

437

allow_credentials: bool = False,

438

allow_origin_regex: str = None,

439

expose_headers: List[str] = None,

440

max_age: int = 600,

441

) -> None: ...

442

```

443

444

[Middleware](./middleware.md)

445

446

### Background Tasks

447

448

Background task execution system for running tasks after sending the response to the client.

449

450

```python { .api }

451

class BackgroundTasks:

452

def add_task(

453

self,

454

func: Callable,

455

*args: Any,

456

**kwargs: Any,

457

) -> None: ...

458

```

459

460

[Background Tasks](./background-tasks.md)

461

462

### Static Files and Templating

463

464

Static file serving and HTML template rendering capabilities for web applications that need to serve frontend content alongside API endpoints.

465

466

```python { .api }

467

class StaticFiles:

468

def __init__(

469

self,

470

*,

471

directory: str = None,

472

packages: List[str] = None,

473

html: bool = False,

474

check_dir: bool = True,

475

follow_symlink: bool = False,

476

) -> None: ...

477

478

class Jinja2Templates:

479

def __init__(self, directory: str) -> None: ...

480

def TemplateResponse(

481

self,

482

name: str,

483

context: dict,

484

status_code: int = 200,

485

headers: dict = None,

486

media_type: str = None,

487

background: BackgroundTask = None,

488

) -> TemplateResponse: ...

489

```

490

491

[Static Files and Templating](./static-templating.md)

492

493

### Testing Support

494

495

Test client for testing FastAPI applications with comprehensive HTTP request simulation capabilities.

496

497

```python { .api }

498

class TestClient:

499

def __init__(

500

self,

501

app: ASGIApp,

502

base_url: str = "http://testserver",

503

raise_server_exceptions: bool = True,

504

root_path: str = "",

505

backend: str = "asyncio",

506

backend_options: dict = None,

507

cookies: httpx.Cookies = None,

508

headers: dict = None,

509

follow_redirects: bool = False,

510

) -> None: ...

511

512

def get(self, url: str, **kwargs) -> httpx.Response: ...

513

def post(self, url: str, **kwargs) -> httpx.Response: ...

514

def put(self, url: str, **kwargs) -> httpx.Response: ...

515

def delete(self, url: str, **kwargs) -> httpx.Response: ...

516

def patch(self, url: str, **kwargs) -> httpx.Response: ...

517

def head(self, url: str, **kwargs) -> httpx.Response: ...

518

def options(self, url: str, **kwargs) -> httpx.Response: ...

519

```

520

521

[Testing Support](./testing.md)

522

523

### Data Utilities

524

525

Utility functions for data encoding and serialization, particularly for converting Python objects to JSON-compatible formats.

526

527

```python { .api }

528

def jsonable_encoder(

529

obj: Any,

530

include: Union[Set[int], Set[str], Dict[int, Any], Dict[str, Any]] = None,

531

exclude: Union[Set[int], Set[str], Dict[int, Any], Dict[str, Any]] = None,

532

by_alias: bool = True,

533

exclude_unset: bool = False,

534

exclude_defaults: bool = False,

535

exclude_none: bool = False,

536

round_trip: bool = True,

537

timedelta_isoformat: str = "iso8601",

538

sqlalchemy_safe: bool = True,

539

fallback: Callable[[Any], Any] = None,

540

) -> Any: ...

541

```

542

543

[Data Utilities](./data-utilities.md)

544

545

### Advanced Response Types

546

547

High-performance JSON response classes and additional response types for various content delivery needs.

548

549

```python { .api }

550

class UJSONResponse(Response):

551

def __init__(

552

self,

553

content: Any = None,

554

status_code: int = 200,

555

headers: dict = None,

556

media_type: str = "application/json",

557

background: BackgroundTask = None,

558

) -> None: ...

559

560

class ORJSONResponse(Response):

561

def __init__(

562

self,

563

content: Any = None,

564

status_code: int = 200,

565

headers: dict = None,

566

media_type: str = "application/json",

567

background: BackgroundTask = None,

568

) -> None: ...

569

570

class HTMLResponse(Response):

571

def __init__(

572

self,

573

content: str = "",

574

status_code: int = 200,

575

headers: dict = None,

576

media_type: str = "text/html",

577

background: BackgroundTask = None,

578

) -> None: ...

579

580

class RedirectResponse(Response):

581

def __init__(

582

self,

583

url: str,

584

status_code: int = 307,

585

headers: dict = None,

586

background: BackgroundTask = None,

587

) -> None: ...

588

589

class FileResponse(Response):

590

def __init__(

591

self,

592

path: str,

593

status_code: int = 200,

594

headers: dict = None,

595

media_type: str = None,

596

filename: str = None,

597

background: BackgroundTask = None,

598

) -> None: ...

599

600

class StreamingResponse(Response):

601

def __init__(

602

self,

603

content: Iterator[Any],

604

status_code: int = 200,

605

headers: dict = None,

606

media_type: str = None,

607

background: BackgroundTask = None,

608

) -> None: ...

609

```

610

611

[Advanced Response Types](./advanced-responses.md)

612

613

## Types

614

615

```python { .api }

616

# Core type definitions used across FastAPI

617

618

from typing import Any, Callable, Dict, List, Optional, Union, Set, Iterator

619

from starlette.types import ASGIApp, Receive, Scope, Send

620

from starlette.responses import Response

621

from starlette.routing import BaseRoute

622

from starlette.middleware import Middleware

623

from starlette.background import BackgroundTask

624

from starlette.templating import _TemplateResponse as TemplateResponse

625

from starlette.datastructures import URL, Address, FormData, Headers, QueryParams, State

626

from pydantic import BaseModel

627

import httpx

628

629

# FastAPI specific types

630

DecoratedCallable = Callable[..., Any]

631

DependsCallable = Callable[..., Any]

632

IncEx = Union[Set[int], Set[str], Dict[int, Any], Dict[str, Any], None]

633

Lifespan = Callable[[Any], Any]

634

635

# Version information

636

__version__: str # Current FastAPI version

637

```