-
Notifications
You must be signed in to change notification settings - Fork 0
/
flaskAPI.py
62 lines (51 loc) · 1.69 KB
/
flaskAPI.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from flask import Flask, jsonify, request
import json
users = [
{'id': 1, 'name':'Leonardo', 'lastname': 'Amorim', 'age': 42 },
{'id': 2, 'name': 'Luana', 'lastname': 'Menezes', 'age': 35}
]
def id_generator():
return max(user['id'] for user in users)+1
app = Flask(__name__)
@app.route('/')
def index():
return jsonify({'message': 'Welcome to the users list!'})
# List endpoint
@app.route('/users')
def get_users():
return jsonify({'users':users})
# Specific user endpoint
@app.route('/users/<int:id>', methods = ['GET'])
def get_user_byId(id):
user = next((user for user in users if user['id'] == id), None)
if user:
return jsonify(user)
else:
return jsonify({'message':'User not found'}), 404
# Create user endpoint
@app.route('/users', methods=['POST'])
def create_user():
new_user = request.get_json()
new_user['id'] = id_generator()
users.append(new_user), 201
return jsonify(new_user, {'message':'User created successfully!'})
# Update user endpoint
@app.route('/users/<int:id>', methods=['PUT'])
def update_user(id):
user = next((user for user in users if user['id'] == id), None)
if user:
user.update(request.get_json())
return jsonify(user)
else:
return jsonify({'message':'User not found'}), 404
# Delete user endpoint
@app.route('/users/<int:id>', methods=['DELETE'])
def delete_user(id):
user = next ((user for user in users if user['id'] == id), None)
if user:
users.remove(user)
return jsonify({'message': 'User {user.name} removed successfully!'})
else:
return jsonify({'message': 'User not found!'}), 404
if __name__ == '__main__':
app.run(debug=True)