-
Notifications
You must be signed in to change notification settings - Fork 0
/
restful_api.py
148 lines (119 loc) · 3.88 KB
/
restful_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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
basedir = os.path.abspath(os.path.dirname(__file__))
# Init app
app = Flask(__name__)
# Database config
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'db.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Init DB
db = SQLAlchemy(app)
# Init Marshmallow
ma = Marshmallow(app)
# Product Class/Model
class Product(db.Model):
# Define parameters
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), unique=True)
description = db.Column(db.String(200))
price = db.Column(db.Float)
qty = db.Column(db.Integer)
# Init
def __init__(self, name, description, price, qty):
self.name = name
self.description = description
self.price = price
self.qty = qty
# Product Schema
class ProductSchema(ma.Schema):
class Meta:
fields = ('id', 'name', 'description', 'price', 'qty')
# Init Schemas
product_schema = ProductSchema()
products_schema = ProductSchema(many=True)
# Create a product
@app.route('/product', methods=['POST'])
def add_product():
try:
# Create vars from request data
name = request.json['name']
description = request.json['description']
price = request.json['price']
qty = request.json['qty']
# Create object with vars
new_product = Product(name, description, price, qty)
# Add to DB and commit
db.session.add(new_product)
db.session.commit()
# API response
return product_schema.jsonify(new_product)
except Exception as err:
# Handle exception
return jsonify({'msg': err.args, 'error': 'Exception'}), 400
# Get all products
@app.route('/product', methods=['GET'])
def get_products():
# Query DB for all objects
all_products = Product.query.all()
# Create object from data
result = products_schema.dump(all_products)
# API response
return jsonify(result)
# Get single products
@app.route('/product/<id>', methods=['GET'])
def get_product(id):
# Create object equal to DB query for specific object
product = Product.query.get(id)
# API response
return product_schema.jsonify(product)
# Update a product
@app.route('/product/<id>', methods=['PUT'])
def update_product(id):
try:
# Create object equal to DB query for specific object
product = Product.query.get(id)
# Create vars from request data
name = request.json['name']
description = request.json['description']
price = request.json['price']
qty = request.json['qty']
# Update new object with vars
product.name = name
product.description = description
product.price = price
product.qty = qty
# Commit to DB
db.session.commit()
# API response
return product_schema.jsonify(product)
except Exception as err:
# Handle exception
return jsonify({'msg': err.args, 'error': 'Exception'})
# Delete a product
@app.route('/product/<id>', methods=['DELETE'])
def delete_product(id):
try:
# Create object equal to DB query for specific object
product = Product.query.get(id)
# Delete from DB and commit
db.session.delete(product)
db.session.commit()
# API response
return product_schema.jsonify(product)
except Exception as err:
# Handle exception
return jsonify({'msg': err.args, 'error': 'Exception'})
# Delete all products
@app.route('/product', methods=['DELETE'])
def delete_all_products():
# Delete all objects of class
Product.query.delete()
# Commit to DB
db.session.commit()
# API response
return jsonify({ 'msg': 'All Products deleted'})
# Run server
if __name__ == '__main__':
app.run()