forked from gitdagray/python-flask-rest-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
81 lines (67 loc) · 2.32 KB
/
api.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_restful import Resource, Api, reqparse, fields, marshal_with, abort
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db = SQLAlchemy(app)
api = Api(app)
class UserModel(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(80), unique=True, nullable=False)
def __repr__(self):
return f"User(name = {self.name}, email = {self.email})"
user_args = reqparse.RequestParser()
user_args.add_argument('name', type=str, required=True, help="Name cannot be blank")
user_args.add_argument('email', type=str, required=True, help="Email cannot be blank")
userFields = {
'id':fields.Integer,
'name':fields.String,
'email':fields.String,
}
class Users(Resource):
@marshal_with(userFields)
def get(self):
users = UserModel.query.all()
return users
@marshal_with(userFields)
def post(self):
args = user_args.parse_args()
user = UserModel(name=args["name"], email=args["email"])
db.session.add(user)
db.session.commit()
users = UserModel.query.all()
return users, 201
class User(Resource):
@marshal_with(userFields)
def get(self, id):
user = UserModel.query.filter_by(id=id).first()
if not user:
abort(404, message="User not found")
return user
@marshal_with(userFields)
def patch(self, id):
args = user_args.parse_args()
user = UserModel.query.filter_by(id=id).first()
if not user:
abort(404, message="User not found")
user.name = args["name"]
user.email = args["email"]
db.session.commit()
return user
@marshal_with(userFields)
def delete(self, id):
user = UserModel.query.filter_by(id=id).first()
if not user:
abort(404, message="User not found")
db.session.delete(user)
db.session.commit()
users = UserModel.query.all()
return users
api.add_resource(Users, '/api/users/')
api.add_resource(User, '/api/users/<int:id>')
@app.route('/')
def home():
return '<h1>Flask REST API</h1>'
if __name__ == '__main__':
app.run(debug=True)