-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproducts.py
50 lines (41 loc) · 1.45 KB
/
products.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
from flask import Flask, jsonify, request
import json
from flask_cors import CORS
app = Flask("Product Server")
CORS(app)
products = [
{'id': 143, 'name': 'Notebook', 'price': 5.49},
{'id': 144, 'name': 'Black Marker', 'price': 1.99}
]
# Example request - http://localhost:5000/products
@app.route('/products', methods=['GET'])
def get_products():
return jsonify(products)
# Example request - http://localhost:5000/products/144 - with method GET
@app.route('/products/<id>', methods=['GET'])
def get_product(id):
id = int(id)
product = [x for x in products if x["id"] == id][0]
return jsonify(product)
# Example request - http://localhost:5000/products - with method POST
@app.route('/products', methods=['POST'])
def add_product():
products.append(request.get_json())
return '', 201
# Example request - http://localhost:5000/products/144 - with method PUT
@app.route('/products/<id>', methods=['PUT'])
def update_product(id):
id = int(id)
updated_product = json.loads(request.data)
product = [x for x in products if x["id"] == id][0]
for key, value in updated_product.items():
product[key] = value
return '', 204
# Example request - http://localhost:5000/products/144 - with method DELETE
@app.route('/products/<id>', methods=['DELETE'])
def remove_product(id):
id = int(id)
product = [x for x in products if x["id"] == id][0]
products.remove(product)
return '', 204
app.run(port=5000,debug=True)