or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

api-resources.mddocumentation.mderror-handling.mdfields.mdindex.mdinput-validation.mdmodels-marshalling.mdrequest-parsing.md

index.mddocs/

0

# Flask-RESTPlus

1

2

A comprehensive extension for the Flask web framework that provides tools to rapidly build REST APIs with automatic documentation generation. Flask-RESTPlus offers a decorator-based approach for defining API endpoints, request/response marshalling with field validation, namespace organization for API structure, and built-in Swagger/OpenAPI documentation generation.

3

4

## Package Information

5

6

- **Package Name**: flask-restplus

7

- **Package Type**: Flask extension

8

- **Language**: Python

9

- **Installation**: `pip install flask-restplus`

10

11

## Core Imports

12

13

```python

14

from flask_restplus import Api, Resource, Namespace

15

```

16

17

Common imports for API development:

18

19

```python

20

from flask_restplus import Api, Resource, Namespace, fields, reqparse

21

from flask_restplus import marshal_with, marshal_with_field, abort

22

```

23

24

Additional imports for advanced features:

25

26

```python

27

from flask_restplus import Model, OrderedModel, SchemaModel, Mask

28

from flask_restplus import RestError, ValidationError, SpecsError

29

from flask_restplus import Swagger, inputs, cors, apidoc

30

```

31

32

## Basic Usage

33

34

```python

35

from flask import Flask

36

from flask_restplus import Api, Resource, fields

37

38

app = Flask(__name__)

39

api = Api(app, doc='/doc/')

40

41

# Define a model for request/response marshalling

42

todo_model = api.model('Todo', {

43

'id': fields.Integer(required=True, description='Task ID'),

44

'task': fields.String(required=True, description='Task description'),

45

'completed': fields.Boolean(description='Task completion status')

46

})

47

48

# Create a namespace

49

ns = api.namespace('todos', description='Todo operations')

50

51

@ns.route('/')

52

class TodoList(Resource):

53

@ns.marshal_list_with(todo_model)

54

def get(self):

55

"""List all todos"""

56

return [

57

{'id': 1, 'task': 'Build an API', 'completed': False},

58

{'id': 2, 'task': 'Write documentation', 'completed': True}

59

]

60

61

@ns.expect(todo_model)

62

@ns.marshal_with(todo_model, code=201)

63

def post(self):

64

"""Create a new todo"""

65

# Implementation would handle the request

66

return {'id': 3, 'task': 'New task', 'completed': False}, 201

67

68

if __name__ == '__main__':

69

app.run(debug=True)

70

```

71

72

## Architecture

73

74

Flask-RESTPlus is built around several key components that work together to create RESTful APIs:

75

76

- **Api**: The main class that wraps a Flask app and provides API functionality

77

- **Resource**: Base class for API endpoints (extends Flask's MethodView)

78

- **Namespace**: Groups related resources together (similar to Flask Blueprints)

79

- **Models**: Define data structures for request/response validation and documentation

80

- **Fields**: Type system for validation, marshalling, and documentation

81

- **Marshalling**: Automatic serialization of Python objects to JSON responses

82

83

This design enables rapid API development with automatic documentation generation, comprehensive input validation, and structured error handling while maintaining Flask's flexibility and extensibility.

84

85

## Capabilities

86

87

### API and Resource Management

88

89

Core classes for creating RESTful APIs with automatic documentation, including the main Api class for Flask integration and Resource base class for endpoint definition.

90

91

```python { .api }

92

class Api:

93

def __init__(self, app=None, **kwargs): ...

94

def add_resource(self, resource, *urls, **kwargs): ...

95

def namespace(self, name, **kwargs): ...

96

97

class Resource:

98

def __init__(self, api=None, *args, **kwargs): ...

99

def dispatch_request(self, *args, **kwargs): ...

100

```

101

102

[API and Resources](./api-resources.md)

103

104

### Models and Marshalling

105

106

Data model definition and automatic marshalling system for request/response handling, including model classes and marshalling decorators.

107

108

```python { .api }

109

class Model(dict):

110

def __init__(self, name, *args, **kwargs): ...

111

112

def marshal_with(fields, **kwargs): ...

113

def marshal(data, fields, **kwargs): ...

114

```

115

116

[Models and Marshalling](./models-marshalling.md)

117

118

### Field Types

119

120

Comprehensive field type system for validation, marshalling, and documentation generation, supporting strings, numbers, dates, nested objects, and custom validators.

121

122

```python { .api }

123

class Raw: ...

124

class String(Raw): ...

125

class Integer(Raw): ...

126

class DateTime(Raw): ...

127

class Nested(Raw): ...

128

class List(Raw): ...

129

```

130

131

[Field Types](./fields.md)

132

133

### Request Parsing

134

135

Request parsing system for handling URL parameters, form data, JSON payloads, and file uploads with validation and type conversion.

136

137

```python { .api }

138

class RequestParser:

139

def add_argument(self, name, **kwargs): ...

140

def parse_args(self, **kwargs): ...

141

142

class Argument:

143

def __init__(self, name, **kwargs): ...

144

```

145

146

[Request Parsing](./request-parsing.md)

147

148

### Input Validation

149

150

Pre-built validation functions for common input types including emails, URLs, IP addresses, dates, and custom regular expression patterns.

151

152

```python { .api }

153

def email(value): ...

154

def url(value): ...

155

def ipv4(value): ...

156

def date(value): ...

157

def boolean(value): ...

158

```

159

160

[Input Validation](./input-validation.md)

161

162

### Error Handling

163

164

Structured error handling with HTTP status codes, custom exception classes, and automatic error response formatting.

165

166

```python { .api }

167

def abort(code, message=None, **kwargs): ...

168

169

class RestError(Exception): ...

170

class ValidationError(RestError): ...

171

```

172

173

[Error Handling](./error-handling.md)

174

175

### Documentation and Swagger

176

177

Automatic API documentation generation with Swagger/OpenAPI support, including interactive documentation interface and specification export.

178

179

```python { .api }

180

class Swagger:

181

def __init__(self, api): ...

182

def as_dict(self): ...

183

184

def ui_for(api): ...

185

```

186

187

[Documentation](./documentation.md)

188

189

## Global Functions

190

191

```python { .api }

192

def marshal(data, fields, envelope=None, skip_none=False, mask=None, ordered=False):

193

"""

194

Marshal data using field definitions.

195

196

Args:

197

data: The data to marshal

198

fields (dict): Field definitions for marshalling

199

envelope (str, optional): Envelope key for response wrapping

200

skip_none (bool): Skip None values in output

201

mask (str, optional): Field mask for partial responses

202

ordered (bool): Preserve field ordering

203

204

Returns:

205

dict: Marshalled data

206

"""

207

208

def marshal_with_field(field, **kwargs):

209

"""

210

Marshal return data with a single field.

211

212

Args:

213

field: Field instance for marshalling

214

envelope (str, optional): Envelope key for response wrapping

215

mask (str, optional): Field mask for partial responses

216

217

Returns:

218

function: Decorator function

219

"""

220

221

def abort(code=500, message=None, **kwargs):

222

"""

223

Abort request with HTTP error.

224

225

Args:

226

code (int): HTTP status code

227

message (str, optional): Error message

228

**kwargs: Additional error data

229

230

Raises:

231

HTTPException: Flask HTTP exception

232

"""

233

```

234

235

## Advanced Components

236

237

### Model Classes

238

239

Core model classes for data structure definition and validation, including ordered models and JSON schema support.

240

241

```python { .api }

242

class Model(dict):

243

def __init__(self, name, *args, **kwargs): ...

244

def inherit(self, name, *parents): ...

245

def clone(self, name=None): ...

246

247

class OrderedModel(Model):

248

def __init__(self, name, *args, **kwargs): ...

249

250

class SchemaModel(Model):

251

def __init__(self, name, schema=None): ...

252

```

253

254

### Field Masking

255

256

Response field masking system for controlling API output and partial responses.

257

258

```python { .api }

259

class Mask:

260

def __init__(self, mask=None, skip=False, **kwargs): ...

261

def apply(self, data): ...

262

def __str__(self): ...

263

```

264

265

### Exception Classes

266

267

Additional exception classes for comprehensive error handling.

268

269

```python { .api }

270

class SpecsError(RestError):

271

def __init__(self, msg): ...

272

```

273

274

### Core Modules

275

276

Advanced functionality modules.

277

278

```python { .api }

279

# CORS support module

280

import cors

281

282

# API documentation utilities

283

import apidoc

284

285

# Swagger/OpenAPI specification generation

286

class Swagger:

287

def __init__(self, api): ...

288

def as_dict(self): ...

289

```

290

291

## Package Metadata

292

293

```python { .api }

294

__version__: str # Package version

295

__description__: str # Package description

296

```