Flask-RESTful
Flask-RESTful is an extension for Flask that adds support for quickly building REST APIs.
Install
1 | pip install flask-restful |
Basic Usage
1 | test |
Renaming Attributes
1 | resource_fields = { |
Default Values
1 | fields = { |
Fields
String (default=None, attribute=None)
FormattedString (src_str)
1
2# If the key is not found in the object, returns the default value.
fields.FormattedString("Hello {name}")Url (endpoint=None, absolute=False, scheme=None, **kwarg)
- endpoint (str) – Endpoint name. If endpoint is
None
,request.endpoint
is used instead - absolute (bool) – If
True
, ensures that the generated urls will have the hostname included - scheme (str) – URL scheme specifier (e.g.
http
,https
)
- endpoint (str) – Endpoint name. If endpoint is
DateTime (dt_format=’rfc822’, **kwargs)
- dt_format (str) –
'rfc822'
or'iso8601'
- dt_format (str) –
Float (default=None, attribute=None)
Integer (default=0, **kwargs)
Nested (nested, allow_null=False, **kwargs)
List (cls_or_instance, **kwargs)
Boolean (default=None, attribute=None)
Fixed (decimals=5, **kwargs)
marshal_with and marshal
marshal_with Return the processed data directly
1
2
3
4
5
6
7
8
9
10
11# @marshal_with(car_fields)
class CarView(Resource):
car_fields = {
'name': fields.String(attribute='carName'),
'id': fields.String(attribute='carId')
}
def get(self):
data = Car.query.all()
return datamarshal Can return the custom data structure
1
2
3
4
5
6
7
8
9
10
11
12
13
14class CarView(Resource):
car_fields = {
'name': fields.String(attribute='carName'),
'id': fields.String(attribute='carId')
}
# @marshal_with(car_fields)
def get(self):
data = Car.query.all()
data = marshal(data, CarView.car_fields)
return {
'data': data,
'status': 'successful'
}