or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication.mdcore-app.mdexceptions.mdindex.mdmcp.mdopenapi.mdrequest-response.mdstatus-codes.mdtemplating.mdwebsocket.md

core-app.mddocs/

0

# Core Application

1

2

Main application functionality for creating Robyn web applications, including routing, middleware, static file serving, and server lifecycle management.

3

4

## Capabilities

5

6

### Application Initialization

7

8

Create a Robyn application instance with optional configuration, OpenAPI integration, and dependency injection.

9

10

```python { .api }

11

class Robyn:

12

def __init__(

13

self,

14

file_object: str,

15

config: Config = Config(),

16

openapi_file_path: Optional[str] = None,

17

openapi: Optional[OpenAPI] = None,

18

dependencies: DependencyMap = DependencyMap()

19

):

20

"""

21

Create a new Robyn application.

22

23

Args:

24

file_object: Usually __file__, used for relative path resolution

25

config: Application configuration options

26

openapi_file_path: Path to custom OpenAPI specification file

27

openapi: OpenAPI instance for documentation generation

28

dependencies: Dependency injection container

29

"""

30

```

31

32

### Server Management

33

34

Start the server with configurable host, port, and timeout settings.

35

36

```python { .api }

37

def start(

38

self,

39

host: str = "127.0.0.1",

40

port: int = 8080,

41

_check_port: bool = True,

42

client_timeout: int = 30,

43

keep_alive_timeout: int = 20

44

):

45

"""

46

Start the Robyn server.

47

48

Args:

49

host: Server host address

50

port: Server port number

51

_check_port: Whether to check if port is available

52

client_timeout: Client connection timeout in seconds

53

keep_alive_timeout: Keep-alive timeout in seconds

54

"""

55

```

56

57

### HTTP Route Decorators

58

59

Define routes using HTTP method decorators with optional authentication and OpenAPI documentation.

60

61

```python { .api }

62

def get(

63

self,

64

endpoint: str,

65

auth_required: bool = False,

66

openapi_name: str = "",

67

openapi_tags: Optional[list] = None

68

):

69

"""GET route decorator."""

70

71

def post(

72

self,

73

endpoint: str,

74

auth_required: bool = False,

75

openapi_name: str = "",

76

openapi_tags: Optional[list] = None

77

):

78

"""POST route decorator."""

79

80

def put(

81

self,

82

endpoint: str,

83

auth_required: bool = False,

84

openapi_name: str = "",

85

openapi_tags: Optional[list] = None

86

):

87

"""PUT route decorator."""

88

89

def delete(

90

self,

91

endpoint: str,

92

auth_required: bool = False,

93

openapi_name: str = "",

94

openapi_tags: Optional[list] = None

95

):

96

"""DELETE route decorator."""

97

98

def patch(

99

self,

100

endpoint: str,

101

auth_required: bool = False,

102

openapi_name: str = "",

103

openapi_tags: Optional[list] = None

104

):

105

"""PATCH route decorator."""

106

107

def head(

108

self,

109

endpoint: str,

110

auth_required: bool = False,

111

openapi_name: str = "",

112

openapi_tags: Optional[list] = None

113

):

114

"""HEAD route decorator."""

115

116

def options(

117

self,

118

endpoint: str,

119

auth_required: bool = False,

120

openapi_name: str = "",

121

openapi_tags: Optional[list] = None

122

):

123

"""OPTIONS route decorator."""

124

125

def connect(

126

self,

127

endpoint: str,

128

auth_required: bool = False,

129

openapi_name: str = "",

130

openapi_tags: Optional[list] = None

131

):

132

"""CONNECT route decorator."""

133

134

def trace(

135

self,

136

endpoint: str,

137

auth_required: bool = False,

138

openapi_name: str = "",

139

openapi_tags: Optional[list] = None

140

):

141

"""TRACE route decorator."""

142

```

143

144

### Route Management

145

146

Add routes programmatically with fine-grained control over route configuration.

147

148

```python { .api }

149

def add_route(

150

self,

151

route_type,

152

endpoint: str,

153

handler,

154

is_const: bool = False,

155

auth_required: bool = False,

156

openapi_name: str = "",

157

openapi_tags: Optional[list] = None

158

):

159

"""

160

Add a route programmatically.

161

162

Args:

163

route_type: HTTP method type

164

endpoint: URL endpoint pattern

165

handler: Route handler function

166

is_const: Whether route response is constant

167

auth_required: Whether authentication is required

168

openapi_name: Name for OpenAPI documentation

169

openapi_tags: Tags for OpenAPI documentation

170

"""

171

```

172

173

### Middleware

174

175

Add before-request and after-request middleware with global or endpoint-specific scope.

176

177

```python { .api }

178

def before_request(self, endpoint: Optional[str] = None):

179

"""

180

Decorator for before-request middleware.

181

182

Args:

183

endpoint: Specific endpoint to apply middleware to, or None for global

184

"""

185

186

def after_request(self, endpoint: Optional[str] = None):

187

"""

188

Decorator for after-request middleware.

189

190

Args:

191

endpoint: Specific endpoint to apply middleware to, or None for global

192

"""

193

```

194

195

### Static File Serving

196

197

Serve static files and directories with optional index files and directory listing.

198

199

```python { .api }

200

def serve_directory(

201

self,

202

route: str,

203

directory_path: str,

204

index_file: Optional[str] = None,

205

show_files_listing: bool = False

206

):

207

"""

208

Serve static files from a directory.

209

210

Args:

211

route: URL route pattern

212

directory_path: Local directory path to serve

213

index_file: Default file to serve (e.g., "index.html")

214

show_files_listing: Whether to show directory listing

215

"""

216

```

217

218

### Application Events

219

220

Handle application startup and shutdown events.

221

222

```python { .api }

223

def startup_handler(self, handler):

224

"""

225

Register a startup event handler.

226

227

Args:

228

handler: Function to call on application startup

229

"""

230

231

def shutdown_handler(self, handler):

232

"""

233

Register a shutdown event handler.

234

235

Args:

236

handler: Function to call on application shutdown

237

"""

238

```

239

240

### Sub-Routers

241

242

Include sub-routers for organizing large applications with route prefixes.

243

244

```python { .api }

245

def include_router(self, router):

246

"""

247

Include a sub-router in the application.

248

249

Args:

250

router: SubRouter instance to include

251

"""

252

253

class SubRouter:

254

def __init__(

255

self,

256

file_object: str,

257

prefix: str = "",

258

config: Config = Config(),

259

openapi: OpenAPI = OpenAPI()

260

):

261

"""

262

Create a sub-router with optional prefix.

263

264

Args:

265

file_object: Usually __file__

266

prefix: URL prefix for all routes in this router

267

config: Router configuration

268

openapi: OpenAPI instance for documentation

269

"""

270

```

271

272

### Authentication Configuration

273

274

Configure application-wide authentication handling.

275

276

```python { .api }

277

def configure_authentication(self, authentication_handler: AuthenticationHandler):

278

"""

279

Configure authentication for the application.

280

281

Args:

282

authentication_handler: Authentication handler instance

283

"""

284

```

285

286

### Exception Handling

287

288

Set global exception handlers for unhandled errors.

289

290

```python { .api }

291

def exception(self, exception_handler):

292

"""

293

Register a global exception handler.

294

295

Args:

296

exception_handler: Function to handle uncaught exceptions

297

"""

298

```

299

300

### CORS Configuration

301

302

Configure Cross-Origin Resource Sharing (CORS) for the application.

303

304

```python { .api }

305

def ALLOW_CORS(

306

app: Robyn,

307

origins: Union[List[str], str],

308

headers: Union[List[str], str] = None

309

):

310

"""

311

Configure CORS for a Robyn application.

312

313

Args:

314

app: Robyn application instance

315

origins: Allowed origins (string or list of strings)

316

headers: Allowed headers (string or list of strings)

317

"""

318

```

319

320

## Usage Examples

321

322

### Basic Application

323

324

```python

325

from robyn import Robyn

326

327

app = Robyn(__file__)

328

329

@app.get("/")

330

def home(request):

331

return "Welcome to Robyn!"

332

333

@app.get("/api/status")

334

def status(request):

335

return {"status": "healthy", "version": "1.0.0"}

336

337

if __name__ == "__main__":

338

app.start(host="0.0.0.0", port=8080)

339

```

340

341

### Application with Middleware

342

343

```python

344

from robyn import Robyn

345

import time

346

347

app = Robyn(__file__)

348

349

@app.before_request()

350

def add_cors_headers(request):

351

print(f"Processing request to {request.url.path}")

352

353

@app.after_request()

354

def log_response(request, response):

355

print(f"Response status: {response.status_code}")

356

return response

357

358

@app.before_request("/api")

359

def api_middleware(request):

360

request.start_time = time.time()

361

362

@app.get("/api/data")

363

def get_data(request):

364

return {"message": "API data", "timestamp": time.time()}

365

366

app.start()

367

```

368

369

### Application with Sub-Routers

370

371

```python

372

from robyn import Robyn, SubRouter

373

374

app = Robyn(__file__)

375

376

# Create API router

377

api_router = SubRouter(__file__, prefix="/api/v1")

378

379

@api_router.get("/users")

380

def list_users(request):

381

return {"users": ["alice", "bob"]}

382

383

@api_router.post("/users")

384

def create_user(request):

385

user_data = request.json()

386

return {"message": "User created", "user": user_data}

387

388

# Include the router

389

app.include_router(api_router)

390

391

# Regular routes

392

@app.get("/")

393

def home(request):

394

return "Main application"

395

396

app.start()

397

```

398

399

### Static File Serving

400

401

```python

402

from robyn import Robyn

403

404

app = Robyn(__file__)

405

406

# Serve static files

407

app.serve_directory("/static", "./public", show_files_listing=True)

408

409

# Serve SPA with index.html fallback

410

app.serve_directory("/", "./dist", index_file="index.html")

411

412

@app.get("/api/info")

413

def api_info(request):

414

return {"api": "v1", "static": "available at /static"}

415

416

app.start()

417

```