or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli-commands.mdcore-classes.mdindex.mdopenapi-models.mdutilities.mdvalidation.md

core-classes.mddocs/

0

# Core Application Classes

1

2

The main classes for building OpenAPI-enabled Flask applications. These classes provide the foundation for creating REST APIs with automatic documentation generation and request validation.

3

4

## Capabilities

5

6

### OpenAPI Application Class

7

8

The primary Flask application class that extends Flask with OpenAPI functionality, automatic request validation, and documentation generation.

9

10

```python { .api }

11

class OpenAPI(APIScaffold, Flask):

12

def __init__(

13

self,

14

import_name: str,

15

*,

16

info: Optional[Info] = None,

17

security_schemes: Optional[SecuritySchemesDict] = None,

18

responses: Optional[ResponseDict] = None,

19

servers: Optional[list[Server]] = None,

20

external_docs: Optional[ExternalDocumentation] = None,

21

operation_id_callback: Callable = get_operation_id_for_path,

22

openapi_extensions: Optional[dict[str, Any]] = None,

23

validation_error_status: Union[str, int] = 422,

24

validation_error_model: Type[BaseModel] = ValidationErrorModel,

25

validation_error_callback: Callable = make_validation_error_response,

26

doc_ui: bool = True,

27

doc_prefix: str = "/openapi",

28

doc_url: str = "/openapi.json",

29

**kwargs: Any

30

):

31

"""

32

OpenAPI class that provides REST API functionality along with Swagger UI and Redoc.

33

34

Args:

35

import_name: The import name for the Flask application.

36

info: Information about the API (title, version, etc.).

37

security_schemes: Security schemes for the API.

38

responses: API responses should be either a subclass of BaseModel, a dictionary, or None.

39

servers: An array of Server objects providing connectivity information to a target server.

40

external_docs: External documentation for the API.

41

operation_id_callback: Callback function for custom operation ID generation.

42

openapi_extensions: Extensions to the OpenAPI Schema.

43

validation_error_status: HTTP Status of the response given when a validation error is detected.

44

validation_error_model: Validation error response model for OpenAPI Specification.

45

validation_error_callback: Validation error response callback.

46

doc_ui: Enable OpenAPI document UI (Swagger UI and Redoc).

47

doc_prefix: URL prefix used for OpenAPI document and UI.

48

doc_url: URL for accessing the OpenAPI specification document in JSON format.

49

**kwargs: Additional kwargs to be passed to Flask.

50

"""

51

```

52

53

**Usage Example:**

54

55

```python

56

from flask_openapi3 import OpenAPI, Info, Tag

57

from pydantic import BaseModel

58

59

# Create API info

60

info = Info(title="My API", version="1.0.0", description="API documentation")

61

tags = [Tag(name="users", description="User management")]

62

63

# Create OpenAPI app

64

app = OpenAPI(__name__, info=info)

65

66

# Define models

67

class User(BaseModel):

68

name: str

69

email: str

70

71

# Add routes with automatic validation

72

@app.post("/users", tags=tags, responses={201: User})

73

def create_user(body: User):

74

return body.model_dump()

75

76

# Access OpenAPI spec at /openapi.json

77

# Access Swagger UI at /openapi

78

```

79

80

#### OpenAPI Methods

81

82

Additional methods available on the OpenAPI class:

83

84

```python { .api }

85

@property

86

def api_doc(self) -> dict:

87

"""

88

Generate the OpenAPI specification JSON.

89

90

Returns:

91

The OpenAPI specification JSON as a dictionary.

92

"""

93

94

def register_api_view(

95

self,

96

api_view: APIView,

97

url_prefix: Optional[str] = None,

98

view_kwargs: Optional[dict[Any, Any]] = None

99

) -> None:

100

"""

101

Register APIView instance with the application.

102

103

Args:

104

api_view: The APIView instance to register.

105

url_prefix: A path to prepend to all the APIView's urls

106

view_kwargs: Additional keyword arguments to pass to the API views.

107

"""

108

```

109

110

### APIBlueprint Class

111

112

Flask Blueprint with OpenAPI support for organizing related API endpoints into modules.

113

114

```python { .api }

115

class APIBlueprint(APIScaffold, Blueprint):

116

def __init__(

117

self,

118

name: str,

119

import_name: str,

120

*,

121

abp_tags: Optional[list[Tag]] = None,

122

abp_security: Optional[list[dict[str, list[str]]]] = None,

123

abp_responses: Optional[ResponseDict] = None,

124

doc_ui: bool = True,

125

operation_id_callback: Callable = get_operation_id_for_path,

126

**kwargs: Any

127

):

128

"""

129

Based on Flask Blueprint with OpenAPI functionality.

130

131

Args:

132

name: The name of the blueprint.

133

import_name: The name of the blueprint package, usually __name__.

134

abp_tags: APIBlueprint tags for every API.

135

abp_security: APIBlueprint security for every API.

136

abp_responses: API responses should be either a subclass of BaseModel, a dictionary, or None.

137

doc_ui: Enable OpenAPI document UI.

138

operation_id_callback: Callback function for custom operation_id generation.

139

**kwargs: Additional kwargs passed to Blueprint.

140

"""

141

```

142

143

**Usage Example:**

144

145

```python

146

from flask_openapi3 import OpenAPI, APIBlueprint, Info, Tag

147

from pydantic import BaseModel

148

149

# Create main app

150

app = OpenAPI(__name__, info=Info(title="API", version="1.0.0"))

151

152

# Create blueprint with tags

153

user_tag = Tag(name="users", description="User operations")

154

users_bp = APIBlueprint("users", __name__, abp_tags=[user_tag])

155

156

class User(BaseModel):

157

id: int

158

name: str

159

160

# Add routes to blueprint

161

@users_bp.get("/users", responses={200: list[User]})

162

def get_users():

163

return [{"id": 1, "name": "John"}]

164

165

# Register blueprint

166

app.register_api(users_bp)

167

```

168

169

### APIView Class

170

171

Class-based views for organizing related API endpoints using method-based routing.

172

173

```python { .api }

174

class APIView:

175

def __init__(

176

self,

177

url_prefix: Optional[str] = None,

178

view_tags: Optional[list[Tag]] = None,

179

view_security: Optional[list[dict[str, list[str]]]] = None,

180

view_responses: Optional[ResponseDict] = None,

181

doc_ui: bool = True,

182

operation_id_callback: Callable = get_operation_id_for_path,

183

):

184

"""

185

Create a class-based view

186

187

Args:

188

url_prefix: A path to prepend to all the APIView's urls

189

view_tags: APIView tags for every API.

190

view_security: APIView security for every API.

191

view_responses: API responses should be either a subclass of BaseModel, a dictionary, or None.

192

doc_ui: Enable OpenAPI document UI.

193

operation_id_callback: Callback function for custom operation_id generation.

194

"""

195

196

def route(self, rule: str):

197

"""Decorator for view class registration"""

198

199

def doc(

200

self,

201

*,

202

tags: Optional[list[Tag]] = None,

203

summary: Optional[str] = None,

204

description: Optional[str] = None,

205

external_docs: Optional[ExternalDocumentation] = None,

206

operation_id: Optional[str] = None,

207

responses: Optional[ResponseDict] = None,

208

deprecated: Optional[bool] = None,

209

security: Optional[list[dict[str, list[Any]]]] = None,

210

servers: Optional[list[Server]] = None,

211

openapi_extensions: Optional[dict[str, Any]] = None,

212

doc_ui: bool = True

213

) -> Callable:

214

"""

215

Decorator for view method documentation.

216

217

Args:

218

tags: Adds metadata to a single tag.

219

summary: A short summary of what the operation does.

220

description: A verbose explanation of the operation behavior.

221

external_docs: Additional external documentation for this operation.

222

operation_id: Unique string used to identify the operation.

223

responses: API responses should be either a subclass of BaseModel, a dictionary, or None.

224

deprecated: Declares this operation to be deprecated.

225

security: A declaration of which security mechanisms can be used for this operation.

226

servers: An alternative server array to service this operation.

227

openapi_extensions: Extensions to the OpenAPI Schema.

228

doc_ui: Enable OpenAPI document UI for this operation.

229

"""

230

231

def register(

232

self,

233

app: "OpenAPI",

234

url_prefix: Optional[str] = None,

235

view_kwargs: Optional[dict[Any, Any]] = None

236

) -> None:

237

"""

238

Register the API views with the given OpenAPI app.

239

240

Args:

241

app: An instance of the OpenAPI app.

242

url_prefix: A path to prepend to all the APIView's urls

243

view_kwargs: Additional keyword arguments to pass to the API views.

244

"""

245

```

246

247

**Usage Example:**

248

249

```python

250

from flask_openapi3 import OpenAPI, APIView, Info, Tag

251

from pydantic import BaseModel

252

253

app = OpenAPI(__name__, info=Info(title="API", version="1.0.0"))

254

255

class User(BaseModel):

256

id: int

257

name: str

258

email: str

259

260

class UserQuery(BaseModel):

261

name: str

262

263

# Create class-based view

264

user_tag = Tag(name="users", description="User management")

265

266

class UserView(APIView):

267

def __init__(self):

268

super().__init__(view_tags=[user_tag])

269

270

def get(self, query: UserQuery):

271

"""Get users by name"""

272

return [{"id": 1, "name": query.name, "email": "user@example.com"}]

273

274

def post(self, body: User):

275

"""Create a new user"""

276

return {"id": 2, **body.model_dump()}

277

278

# Register view

279

user_view = UserView()

280

user_view.register(app, "/users")

281

```

282

283

### APIScaffold Base Class

284

285

Base class providing common API functionality shared between OpenAPI and APIBlueprint classes.

286

287

```python { .api }

288

class APIScaffold:

289

def _collect_openapi_info(

290

self,

291

rule: str,

292

func: Callable,

293

*,

294

tags: Optional[list[Tag]] = None,

295

summary: Optional[str] = None,

296

description: Optional[str] = None,

297

external_docs: Optional[ExternalDocumentation] = None,

298

operation_id: Optional[str] = None,

299

responses: Optional[ResponseDict] = None,

300

deprecated: Optional[bool] = None,

301

security: Optional[list[dict[str, list[Any]]]] = None,

302

servers: Optional[list[Server]] = None,

303

openapi_extensions: Optional[dict[str, Any]] = None,

304

doc_ui: bool = True,

305

method: str = HTTPMethod.GET

306

) -> ParametersTuple:

307

"""Collect OpenAPI information for endpoint registration"""

308

309

def register_api(self, api) -> None:

310

"""Register an API component (blueprint or view)"""

311

312

def _add_url_rule(

313

self,

314

rule,

315

endpoint=None,

316

view_func=None,

317

provide_automatic_options=None,

318

**options,

319

) -> None:

320

"""Add URL rule with OpenAPI information collection"""

321

```

322

323

## Common Decorator Methods

324

325

All main classes (OpenAPI, APIBlueprint) provide HTTP method decorators for route registration:

326

327

```python { .api }

328

def get(

329

self,

330

rule: str,

331

*,

332

tags: Optional[list[Tag]] = None,

333

summary: Optional[str] = None,

334

description: Optional[str] = None,

335

external_docs: Optional[ExternalDocumentation] = None,

336

operation_id: Optional[str] = None,

337

responses: Optional[ResponseDict] = None,

338

deprecated: Optional[bool] = None,

339

security: Optional[list[dict[str, list[Any]]]] = None,

340

servers: Optional[list[Server]] = None,

341

openapi_extensions: Optional[dict[str, Any]] = None,

342

doc_ui: bool = True,

343

**options: Any

344

) -> Callable: ...

345

346

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

347

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

348

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

349

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

350

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

351

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

352

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

353

```

354

355

These decorators automatically handle:

356

- Request validation based on function parameter types

357

- Response serialization and validation

358

- OpenAPI specification generation

359

- Documentation UI integration