sarahciston commited on
Commit
c531ff1
·
verified ·
1 Parent(s): 6a6185a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -0
app.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from apiflask import APIFlask, Schema, abort
2
+ from apiflask.fields import Integer, String
3
+ from apiflask.validators import Length, OneOf
4
+
5
+ app = APIFlask(__name__)
6
+
7
+ pets = [
8
+ {'id': 0, 'name': 'Kitty', 'category': 'cat'},
9
+ {'id': 1, 'name': 'Coco', 'category': 'dog'}
10
+ ]
11
+
12
+
13
+ class PetIn(Schema):
14
+ name = String(required=True, validate=Length(0, 10))
15
+ category = String(required=True, validate=OneOf(['dog', 'cat']))
16
+
17
+
18
+ class PetOut(Schema):
19
+ id = Integer()
20
+ name = String()
21
+ category = String()
22
+
23
+
24
+ @app.get('/')
25
+ def say_hello():
26
+ # returning a dict or list equals to use jsonify()
27
+ return {'message': 'Hello!'}
28
+
29
+
30
+ @app.get('/pets/<int:pet_id>')
31
+ @app.output(PetOut)
32
+ def get_pet(pet_id):
33
+ if pet_id > len(pets) - 1:
34
+ abort(404)
35
+ # you can also return an ORM/ODM model class instance directly
36
+ # APIFlask will serialize the object into JSON format
37
+ return pets[pet_id]
38
+
39
+
40
+ @app.patch('/pets/<int:pet_id>')
41
+ @app.input(PetIn(partial=True)) # -> json_data
42
+ @app.output(PetOut)
43
+ def update_pet(pet_id, json_data):
44
+ # the validated and parsed input data will
45
+ # be injected into the view function as a dict
46
+ if pet_id > len(pets) - 1:
47
+ abort(404)
48
+ for attr, value in json_data.items():
49
+ pets[pet_id][attr] = value
50
+ return pets[pet_id]