Browse Source

Flask and pyramid api example

Guénaël Muller 6 years ago
parent
commit
3a5a80c11f
2 changed files with 259 additions and 0 deletions
  1. 128 0
      example/fake_api/flask_api.py
  2. 131 0
      example/fake_api/pyramid_api.py

+ 128 - 0
example/fake_api/flask_api.py View File

@@ -0,0 +1,128 @@
1
+# -*- coding: utf-8 -*-
2
+import json
3
+from http import HTTPStatus
4
+
5
+import flask
6
+import time
7
+from datetime import datetime
8
+import hapic
9
+from example.fake_api.schema import *
10
+from hapic.data import HapicData
11
+
12
+
13
+class NoContentException(Exception):
14
+    pass
15
+
16
+
17
+class Controllers(object):
18
+    @hapic.with_api_doc()
19
+    @hapic.output_body(AboutResponseSchema())
20
+    def about(self):
21
+        """
22
+        General information about this API.
23
+        """
24
+        return {
25
+            'version': '1.2.3',
26
+            'datetime': datetime.now(),
27
+        }
28
+
29
+    @hapic.with_api_doc()
30
+    @hapic.output_body(ListsUserSchema())
31
+    def get_users(self):
32
+        """
33
+        Obtain users list.
34
+        """
35
+        return {
36
+            'item_nb': 1,
37
+            'items': [
38
+                {
39
+                    'id': 4,
40
+                    'username': 'some_user',
41
+                    'display_name': 'Damien Accorsi',
42
+                    'company': 'Algoo',
43
+                },
44
+            ],
45
+            'pagination': {
46
+                'first_id': 0,
47
+                'last_id': 5,
48
+                'current_id': 0,
49
+            }
50
+        }
51
+
52
+    @hapic.with_api_doc()
53
+    @hapic.input_path(UserPathSchema())
54
+    @hapic.output_body(UserSchema())
55
+    def get_user(self, id, hapic_data: HapicData):
56
+        """
57
+        Obtain one user
58
+        """
59
+        return {
60
+             'id': 4,
61
+             'username': 'some_user',
62
+             'email_address': 'some.user@hapic.com',
63
+             'first_name': 'Damien',
64
+             'last_name': 'Accorsi',
65
+             'display_name': 'Damien Accorsi',
66
+             'company': 'Algoo',
67
+        }
68
+
69
+    @hapic.with_api_doc()
70
+    # TODO - G.M - 2017-12-5 - Support input_forms ?
71
+    # TODO - G.M - 2017-12-5 - Support exclude, only ?
72
+    @hapic.input_body(UserSchema(exclude=('id',)))
73
+    @hapic.output_body(UserSchema())
74
+    def add_user(self, hapic_data: HapicData):
75
+        """
76
+        Add new user
77
+        """
78
+        return {
79
+             'id': 4,
80
+             'username': 'some_user',
81
+             'email_address': 'some.user@hapic.com',
82
+             'first_name': 'Damien',
83
+             'last_name': 'Accorsi',
84
+             'display_name': 'Damien Accorsi',
85
+             'company': 'Algoo',
86
+        }
87
+
88
+    @hapic.with_api_doc()
89
+    @hapic.handle_exception(NoContentException, http_code=HTTPStatus.NO_CONTENT)
90
+    @hapic.input_path(UserPathSchema())
91
+    def del_user(self, id, hapic_data: HapicData):
92
+        """
93
+        delete user
94
+        """
95
+
96
+        # TODO - G.M - 2017-12-05 - Add better
97
+        #  way to doc response of this function, using response object ?
98
+        # return bottle.Response(
99
+        #     status=204,
100
+        # )
101
+        raise NoContentException
102
+
103
+    def bind(self, app:flask.Flask):
104
+        app.add_url_rule('/about',
105
+                         view_func=self.about)
106
+        app.add_url_rule('/users',
107
+                         view_func=self.get_users)
108
+        app.add_url_rule('/users/<id>',
109
+                         view_func=self.get_user)
110
+        app.add_url_rule('/users/',
111
+                         view_func=self.add_user,
112
+                         methods=['POST'])
113
+        app.add_url_rule('/users/<id>',
114
+                         view_func=self.del_user,
115
+                         methods=['DELETE'])
116
+
117
+
118
+app = flask.Flask(__name__)
119
+controllers = Controllers()
120
+controllers.bind(app)
121
+hapic.set_context(hapic.ext.flask.FlaskContext(app))
122
+time.sleep(1)
123
+s = json.dumps(hapic.generate_doc())
124
+time.sleep(1)
125
+# print swagger doc
126
+print(s)
127
+# Run app
128
+app.run(host='localhost', port=8082, debug=True)

+ 131 - 0
example/fake_api/pyramid_api.py View File

@@ -0,0 +1,131 @@
1
+# -*- coding: utf-8 -*-
2
+import json
3
+from http import HTTPStatus
4
+
5
+from pyramid.config import Configurator
6
+from wsgiref.simple_server import make_server
7
+import time
8
+from datetime import datetime
9
+import hapic
10
+from example.fake_api.schema import *
11
+from hapic.data import HapicData
12
+
13
+
14
+class NoContentException(Exception):
15
+    pass
16
+
17
+
18
+class Controllers(object):
19
+    @hapic.with_api_doc()
20
+    @hapic.output_body(AboutResponseSchema())
21
+    def about(self, context, request):
22
+        """
23
+        General information about this API.
24
+        """
25
+        return {
26
+            'version': '1.2.3',
27
+            'datetime': datetime.now(),
28
+        }
29
+
30
+    @hapic.with_api_doc()
31
+    @hapic.output_body(ListsUserSchema())
32
+    def get_users(self, context, request):
33
+        """
34
+        Obtain users list.
35
+        """
36
+        return {
37
+            'item_nb': 1,
38
+            'items': [
39
+                {
40
+                    'id': 4,
41
+                    'username': 'some_user',
42
+                    'display_name': 'Damien Accorsi',
43
+                    'company': 'Algoo',
44
+                },
45
+            ],
46
+            'pagination': {
47
+                'first_id': 0,
48
+                'last_id': 5,
49
+                'current_id': 0,
50
+            }
51
+        }
52
+
53
+    @hapic.with_api_doc()
54
+    @hapic.input_path(UserPathSchema())
55
+    @hapic.output_body(UserSchema())
56
+    def get_user(self, context, request, hapic_data: HapicData):
57
+        """
58
+        Obtain one user
59
+        """
60
+        return {
61
+             'id': 4,
62
+             'username': 'some_user',
63
+             'email_address': 'some.user@hapic.com',
64
+             'first_name': 'Damien',
65
+             'last_name': 'Accorsi',
66
+             'display_name': 'Damien Accorsi',
67
+             'company': 'Algoo',
68
+        }
69
+
70
+    @hapic.with_api_doc()
71
+    # TODO - G.M - 2017-12-5 - Support input_forms ?
72
+    # TODO - G.M - 2017-12-5 - Support exclude, only ?
73
+    @hapic.input_body(UserSchema(exclude=('id',)))
74
+    @hapic.output_body(UserSchema())
75
+    def add_user(self, context, request, hapic_data: HapicData):
76
+        """
77
+        Add new user
78
+        """
79
+        return {
80
+             'id': 4,
81
+             'username': 'some_user',
82
+             'email_address': 'some.user@hapic.com',
83
+             'first_name': 'Damien',
84
+             'last_name': 'Accorsi',
85
+             'display_name': 'Damien Accorsi',
86
+             'company': 'Algoo',
87
+        }
88
+
89
+    @hapic.with_api_doc()
90
+    @hapic.handle_exception(NoContentException, http_code=HTTPStatus.NO_CONTENT)
91
+    @hapic.input_path(UserPathSchema())
92
+    def del_user(self, context, request, hapic_data: HapicData):
93
+        """
94
+        delete user
95
+        """
96
+
97
+        # TODO - G.M - 2017-12-05 - Add better
98
+        #  way to doc response of this function, using response object ?
99
+        # return bottle.Response(
100
+        #     status=204,
101
+        # )
102
+        raise NoContentException
103
+
104
+    def bind(self, configurator: Configurator):
105
+        configurator.add_route('about', '/about', request_method='GET')
106
+        configurator.add_view(self.about, route_name='about', renderer='json')
107
+
108
+        configurator.add_route('get_users', '/users', request_method='GET')  # nopep8
109
+        configurator.add_view(self.get_users, route_name='get_users', renderer='json')  # nopep8
110
+
111
+        configurator.add_route('get_user', '/users/{id}', request_method='GET')  # nopep8
112
+        configurator.add_view(self.get_user, route_name='get_user', renderer='json')  # nopep8
113
+
114
+        configurator.add_route('add_user', '/users/', request_method='POST')  # nopep8
115
+        configurator.add_view(self.add_user, route_name='add_user', renderer='json')  # nopep8
116
+
117
+        configurator.add_route('del_user', '/users/{id}', request_method='DELETE')  # nopep8
118
+        configurator.add_view(self.del_user, route_name='del_user', renderer='json')  # nopep8
119
+
120
+configurator = Configurator(autocommit=True)
121
+controllers = Controllers()
122
+controllers.bind(configurator)
123
+hapic.set_context(hapic.ext.pyramid.PyramidContext(configurator))
124
+time.sleep(1)
125
+s = json.dumps(hapic.generate_doc())
126
+time.sleep(1)
127
+# print swagger doc
128
+print(s)
129
+# Run app
130
+server = make_server('0.0.0.0', 8081, configurator.make_wsgi_app())
131
+server.serve_forever()