Skip to content

Commit 9ee7457

Browse files
committed
create_response wrapper and cleaned up code
1 parent 0341007 commit 9ee7457

File tree

1 file changed

+37
-12
lines changed

1 file changed

+37
-12
lines changed

app.py

Lines changed: 37 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,47 @@
1-
from flask import Flask
2-
from flask import render_template
3-
from flask import jsonify, request
1+
from flask import Flask, jsonify, request
2+
43
app = Flask(__name__)
54

5+
def create_response(data={}, status=200, message=''):
6+
"""
7+
Wraps response in a consistent format throughout the API
8+
Format inspired by https://medium.com/@shazow/how-i-design-json-api-responses-71900f00f2db
9+
Modifications included:
10+
- make success a boolean since there's only 2 values
11+
- make message a single string since we will only use one message per response
12+
13+
IMPORTANT: data must be a dictionary where:
14+
- the key is the name of the type of data
15+
- the value is the data itself
16+
"""
17+
response = {
18+
'success': 200 <= status < 300,
19+
'code': status,
20+
'message': message,
21+
'result': data
22+
}
23+
return jsonify(response), status
24+
25+
"""
26+
~~~~~~~~~~~~ API ~~~~~~~~~~~~
27+
"""
28+
629
@app.route('/')
730
def my_first_route():
8-
return "<h1> Hello World! </h1>"
31+
return create_response(data='hello world!')
932

10-
@app.route('/route/<name>')
33+
@app.route('/mirror/<name>')
1134
def my_second_route(name):
12-
return name
35+
return create_response(name)
1336

14-
@app.route('/get_users', methods=['GET'])
37+
@app.route('/users', methods=['GET'])
1538
def get_all_users():
1639
if request.method == 'GET':
17-
return jsonify({'status': 'success', 'data': ['aria', 'tim', 'varun', 'alex']})
18-
else:
19-
return jsonify({"status": "failed"})
20-
40+
data = { 'users': ['aria', 'tim', 'varun', 'alex'] }
41+
return create_response(data)
42+
43+
"""
44+
~~~~~~~~~~~~ END API ~~~~~~~~~~~~
45+
"""
2146
if __name__ == '__main__':
22-
app.run(debug=True)
47+
app.run(debug=True)

0 commit comments

Comments
 (0)