or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication.mdcore-application.mddata-structures.mdexceptions-status.mdindex.mdmiddleware.mdrequests-responses.mdrouting.mdstatic-files.mdtesting.mdwebsockets.md

index.mddocs/

0

# Starlette

1

2

Starlette is a lightweight ASGI framework/toolkit, which is ideal for building async web services in Python. It's production-ready, and gives you the following features:

3

4

- **ASGI native**: Built from the ground up for async Python web development

5

- **WebSocket support**: First-class WebSocket handling

6

- **GraphQL support**: Built-in GraphQL schema and query execution

7

- **In-process background tasks**: Execute tasks during request/response cycle

8

- **Startup and shutdown events**: Application lifecycle management

9

- **Test client**: Built on HTTPX for comprehensive testing

10

- **CORS, GZip, Static Files, Streaming responses**: Common web features included

11

- **Session and Cookie based authentication**: Flexible authentication system

12

- **100% test coverage**: Thoroughly tested codebase

13

- **100% type annotated**: Complete type hints for better development experience

14

- **Zero hard dependencies**: Minimal, focused core with optional integrations

15

- **Compatible with `asyncio` and `trio` backends**: Flexible async runtime support

16

17

## Package Information

18

19

- **Package Name**: starlette

20

- **Package Type**: pypi

21

- **Language**: Python

22

- **Installation**: `pip install starlette`

23

24

```python { .api }

25

# Package metadata

26

__version__ = "0.47.3"

27

```

28

29

Starlette requires Python 3.8+ and is built on top of the ASGI (Asynchronous Server Gateway Interface) standard, making it compatible with servers like Uvicorn, Daphne, and Hypercorn.

30

31

## Core Imports

32

33

```python { .api }

34

# Core application class

35

from starlette.applications import Starlette

36

37

# Routing components

38

from starlette.routing import Route, WebSocketRoute, Mount, Router

39

40

# Request and response handling

41

from starlette.requests import Request

42

from starlette.responses import (

43

Response, JSONResponse, HTMLResponse, PlainTextResponse,

44

RedirectResponse, StreamingResponse, FileResponse

45

)

46

47

# WebSocket support

48

from starlette.websockets import WebSocket

49

50

# Middleware system

51

from starlette.middleware import Middleware

52

from starlette.middleware.cors import CORSMiddleware

53

from starlette.middleware.gzip import GZipMiddleware

54

from starlette.middleware.sessions import SessionMiddleware

55

56

# Background tasks

57

from starlette.background import BackgroundTask, BackgroundTasks

58

59

# Authentication

60

from starlette.authentication import (

61

requires, AuthenticationBackend, BaseUser,

62

SimpleUser, UnauthenticatedUser

63

)

64

65

# Data structures

66

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

67

68

# Configuration

69

from starlette.config import Config

70

71

# Status codes

72

from starlette import status

73

74

# Testing

75

from starlette.testclient import TestClient

76

77

# Exceptions

78

from starlette.exceptions import HTTPException, WebSocketException

79

80

# Static files

81

from starlette.staticfiles import StaticFiles

82

83

# Templating (requires Jinja2)

84

from starlette.templating import Jinja2Templates

85

```

86

87

## Basic Usage

88

89

### Simple ASGI Application

90

91

```python { .api }

92

from starlette.applications import Starlette

93

from starlette.responses import JSONResponse

94

from starlette.routing import Route

95

96

async def homepage(request):

97

return JSONResponse({'hello': 'world'})

98

99

app = Starlette(debug=True, routes=[

100

Route('/', homepage),

101

])

102

103

# Run with: uvicorn main:app

104

```

105

106

### Complete Application Example

107

108

```python { .api }

109

from starlette.applications import Starlette

110

from starlette.middleware import Middleware

111

from starlette.middleware.cors import CORSMiddleware

112

from starlette.middleware.sessions import SessionMiddleware

113

from starlette.requests import Request

114

from starlette.responses import JSONResponse, PlainTextResponse

115

from starlette.routing import Route, WebSocketRoute

116

from starlette.websockets import WebSocket

117

118

# HTTP endpoints

119

async def homepage(request: Request) -> PlainTextResponse:

120

return PlainTextResponse('Hello, world!')

121

122

async def user_profile(request: Request) -> JSONResponse:

123

user_id = request.path_params['user_id']

124

return JSONResponse({'user_id': user_id, 'name': f'User {user_id}'})

125

126

# WebSocket endpoint

127

async def websocket_endpoint(websocket: WebSocket) -> None:

128

await websocket.accept()

129

await websocket.send_text("Hello WebSocket!")

130

await websocket.close()

131

132

# Application startup/shutdown

133

async def startup():

134

print("Application starting up...")

135

136

async def shutdown():

137

print("Application shutting down...")

138

139

# Application configuration

140

middleware = [

141

Middleware(CORSMiddleware, allow_origins=['*']),

142

Middleware(SessionMiddleware, secret_key='secret-key'),

143

]

144

145

routes = [

146

Route('/', homepage),

147

Route('/users/{user_id:int}', user_profile),

148

WebSocketRoute('/ws', websocket_endpoint),

149

]

150

151

app = Starlette(

152

debug=True,

153

routes=routes,

154

middleware=middleware,

155

on_startup=[startup],

156

on_shutdown=[shutdown]

157

)

158

```

159

160

## Architecture

161

162

### ASGI Foundation

163

164

Starlette is built on ASGI (Asynchronous Server Gateway Interface), which provides:

165

166

- **Async-first design**: Native support for async/await patterns

167

- **HTTP and WebSocket support**: Handle both protocols seamlessly

168

- **Streaming support**: Handle large requests and responses efficiently

169

- **Server independence**: Works with any ASGI server

170

- **Middleware composition**: Stackable middleware components

171

172

```python { .api }

173

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

174

175

# ASGI application type signature

176

ASGIApp = Callable[[Scope, Receive, Send], Awaitable[None]]

177

178

# Core ASGI types

179

Scope = MutableMapping[str, Any]

180

Message = MutableMapping[str, Any]

181

Receive = Callable[[], Awaitable[Message]]

182

Send = Callable[[Message], Awaitable[None]]

183

```

184

185

### Request/Response Lifecycle

186

187

1. **Request arrives** at ASGI server (Uvicorn, Daphne, etc.)

188

2. **Middleware stack** processes request (CORS, authentication, etc.)

189

3. **Router** matches URL pattern to route handler

190

4. **Endpoint** processes request and returns response

191

5. **Middleware stack** processes response in reverse order

192

6. **Response** sent back to client

193

194

### Application Structure

195

196

```python { .api }

197

# Application class with all configuration options

198

class Starlette:

199

def __init__(

200

self,

201

debug: bool = False,

202

routes: Sequence[BaseRoute] | None = None,

203

middleware: Sequence[Middleware] | None = None,

204

exception_handlers: Mapping[Any, Callable] | None = None,

205

on_startup: Sequence[Callable] | None = None,

206

on_shutdown: Sequence[Callable] | None = None,

207

lifespan: Lifespan[Any] | None = None,

208

) -> None: ...

209

```

210

211

## Capabilities

212

213

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

214

Application lifecycle, configuration, and state management.

215

216

```python { .api }

217

# Application instance with startup/shutdown events

218

app = Starlette(

219

on_startup=[startup_handler],

220

on_shutdown=[shutdown_handler],

221

lifespan=lifespan_context

222

)

223

224

# Application state for sharing data

225

app.state.database = Database()

226

```

227

228

### [Routing System](./routing.md)

229

URL routing, path parameters, and endpoint organization.

230

231

```python { .api }

232

from starlette.routing import Route, WebSocketRoute, Mount

233

234

routes = [

235

Route("/", homepage),

236

Route("/users/{user_id:int}", user_detail, methods=["GET", "POST"]),

237

WebSocketRoute("/ws", websocket_endpoint),

238

Mount("/static", StaticFiles(directory="static"), name="static"),

239

]

240

```

241

242

### [Request & Response Handling](./requests-responses.md)

243

HTTP request parsing and response generation.

244

245

```python { .api }

246

async def endpoint(request: Request) -> Response:

247

# Access request data

248

method = request.method

249

headers = request.headers

250

body = await request.json()

251

252

# Return various response types

253

return JSONResponse({"message": "success"})

254

```

255

256

### [WebSocket Support](./websockets.md)

257

Real-time bidirectional communication.

258

259

```python { .api }

260

async def websocket_endpoint(websocket: WebSocket):

261

await websocket.accept()

262

data = await websocket.receive_json()

263

await websocket.send_json({"response": data})

264

await websocket.close()

265

```

266

267

### [Middleware System](./middleware.md)

268

Request/response processing pipeline.

269

270

```python { .api }

271

from starlette.middleware.cors import CORSMiddleware

272

from starlette.middleware.gzip import GZipMiddleware

273

274

middleware = [

275

Middleware(CORSMiddleware, allow_origins=["*"]),

276

Middleware(GZipMiddleware, minimum_size=1000),

277

]

278

```

279

280

### [Authentication Framework](./authentication.md)

281

User authentication and authorization.

282

283

```python { .api }

284

from starlette.authentication import requires, AuthenticationBackend

285

286

@requires("authenticated")

287

async def protected_endpoint(request: Request):

288

user = request.user

289

return JSONResponse({"user": user.display_name})

290

```

291

292

### [Static File Serving](./static-files.md)

293

Efficient static asset serving.

294

295

```python { .api }

296

from starlette.staticfiles import StaticFiles

297

298

app.mount("/static", StaticFiles(directory="static"), name="static")

299

```

300

301

### [Testing Utilities](./testing.md)

302

Comprehensive testing support.

303

304

```python { .api }

305

from starlette.testclient import TestClient

306

307

client = TestClient(app)

308

response = client.get("/")

309

assert response.status_code == 200

310

```

311

312

### [Data Structures](./data-structures.md)

313

URLs, headers, forms, and other web data types.

314

315

```python { .api }

316

from starlette.datastructures import URL, Headers, QueryParams

317

318

url = URL("https://example.com/path?param=value")

319

headers = Headers({"content-type": "application/json"})

320

params = QueryParams("name=john&age=30")

321

```

322

323

### [Exception Handling & Status Codes](./exceptions-status.md)

324

HTTP exceptions and status code constants.

325

326

```python { .api }

327

from starlette.exceptions import HTTPException

328

from starlette import status

329

330

raise HTTPException(

331

status_code=status.HTTP_404_NOT_FOUND,

332

detail="Resource not found"

333

)

334

```

335

336

## Key Features

337

338

### Background Tasks

339

Execute tasks after response is sent to client:

340

341

```python { .api }

342

from starlette.background import BackgroundTask

343

344

def send_email(email: str, message: str):

345

# Send email implementation

346

pass

347

348

async def endpoint(request: Request):

349

task = BackgroundTask(send_email, "user@example.com", "Welcome!")

350

return JSONResponse({"message": "User created"}, background=task)

351

```

352

353

### Configuration Management

354

Environment-based configuration:

355

356

```python { .api }

357

from starlette.config import Config

358

359

config = Config(".env")

360

DEBUG = config("DEBUG", cast=bool, default=False)

361

DATABASE_URL = config("DATABASE_URL")

362

```

363

364

### Type Safety

365

Complete type annotations throughout:

366

367

```python { .api }

368

from typing import Any

369

from starlette.requests import Request

370

from starlette.responses import Response

371

372

async def typed_endpoint(request: Request) -> Response:

373

data: dict[str, Any] = await request.json()

374

return JSONResponse(data)

375

```

376

377

Starlette provides a solid foundation for building modern Python web applications with async/await, comprehensive testing support, and a clean, composable architecture.