|
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 | + |
4 | 3 | app = Flask(__name__) |
5 | 4 |
|
| 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 | + |
6 | 29 | @app.route('/') |
7 | 30 | def my_first_route(): |
8 | | - return "<h1> Hello World! </h1>" |
| 31 | + return create_response(data='hello world!') |
9 | 32 |
|
10 | | -@app.route('/route/<name>') |
| 33 | +@app.route('/mirror/<name>') |
11 | 34 | def my_second_route(name): |
12 | | - return name |
| 35 | + return create_response(name) |
13 | 36 |
|
14 | | -@app.route('/get_users', methods=['GET']) |
| 37 | +@app.route('/users', methods=['GET']) |
15 | 38 | def get_all_users(): |
16 | 39 | 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 | +""" |
21 | 46 | if __name__ == '__main__': |
22 | | - app.run(debug=True) |
| 47 | + app.run(debug=True) |
0 commit comments