以下是开发一个简单电商 API 的主要步骤:
一、需求分析与规划
二、技术选型与环境搭建
plaintext
pip install flask
同时,安装数据库相关的库,比如 SQLAlchemy(用于与数据库交互):
plaintext
pip install flask_sqlalchemy
三、数据库设计
id
(商品唯一标识,主键)name
(商品名称)description
(商品描述)price
(价格)stock
(库存数量)等。id
(用户唯一标识,主键)username
(用户名)password
(密码,注意加密存储)email
(邮箱)等。id
(主键)user_id
(关联用户)product_id
(关联商品)quantity
(商品数量)等。id
(主键)user_id
(关联用户)order_date
(下单时间)total_amount
(订单总金额)等。四、创建模型与数据库连接
python
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///ecommerce.db'
db = SQLAlchemy(app)
class Product(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
# 其他字段...
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), unique=True, nullable=False)
# 其他字段...
# 其他模型类似创建
plaintext
from your_app import db
db.create_all()
五、实现 API 路由和业务逻辑
python
@app.route('/products', methods=['GET'])
def get_products():
products = Product.query.all()
result = []
for product in products:
result.append({
'id': product.id,
'name': product.name,
'price': product.price
# 添加其他需要返回的字段
})
return {'products': result}
python
@app.route('/products/', methods=['GET'])
def get_product_detail(product_id):
product = Product.query.get(product_id)
if product:
return {
'id': product.id,
'name': product.name,
'description': product.description,
'price': product.price
# 其他字段
}
else:
return {'message': 'Product not found'}, 404
python
@app.route('/users/register', methods=['POST'])
def register_user():
data = request.get_json()
new_user = User(username=data['username'], password=data['password'], email=data['email'])
db.session.add(new_user)
db.session.commit()
return {'message': 'User registered successfully'}, 201
python
@app.route('/cart/add', methods=['POST'])
def add_to_cart():
data = request.get_json()
user_id = data['user_id']
product_id = data['product_id']
quantity = data['quantity']
# 检查商品库存等逻辑
# 添加到购物车
new_cart_item = Cart(user_id=user_id, product_id=product_id, quantity=quantity)
db.session.add(new_cart_item)
db.session.commit()
return {'message': 'Item added to cart'}, 201
@app.route('/cart/', methods=['GET'])
def get_cart(user_id):
cart_items = Cart.query.filter_by(user_id=user_id).all()
result = []
for item in cart_items:
product = Product.query.get(item.product_id)
result.append({
'product_name': product.name,
'quantity': item.quantity
# 其他字段
})
return {'cart_items': result}
python
@app.route('/orders/create', methods=['POST'])
def create_order():
data = request.get_json()
user_id = data['user_id']
cart_items = data['cart_items']
total_amount = calculate_total_amount(cart_items)
new_order = Order(user_id=user_id, total_amount=total_amount)
db.session.add(new_order)
# 处理购物车与订单关联及库存更新等逻辑
db.session.commit()
return {'message': 'Order created successfully'}, 201
六、测试与优化
七、部署
了解更多国内外电商API,可以私信或评论区交流 ,感谢你的关注。