写一个独立的备忘录的restapi代码
时间: 2023-12-14 16:36:44 浏览: 192
codebase-nodejs-rest:NodeJS中REST API的代码库
好的,我可以给你一个Python的Flask框架的代码,实现一个简单的备忘录的RESTful API。
```python
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
# 初始化Flask应用
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
# 配置数据库
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'db.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# 初始化数据库和序列化工具
db = SQLAlchemy(app)
ma = Marshmallow(app)
# 定义备忘录模型
class Memo(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), unique=True)
content = db.Column(db.Text)
def __init__(self, title, content):
self.title = title
self.content = content
# 定义备忘录模型的序列化器
class MemoSchema(ma.Schema):
class Meta:
fields = ('id', 'title', 'content')
memo_schema = MemoSchema()
memos_schema = MemoSchema(many=True)
# 添加备忘录
@app.route('/memo', methods=['POST'])
def add_memo():
title = request.json['title']
content = request.json['content']
new_memo = Memo(title, content)
db.session.add(new_memo)
db.session.commit()
return memo_schema.jsonify(new_memo)
# 获取所有备忘录
@app.route('/memo', methods=['GET'])
def get_memos():
all_memos = Memo.query.all()
result = memos_schema.dump(all_memos)
return jsonify(result)
# 获取单个备忘录
@app.route('/memo/<id>', methods=['GET'])
def get_memo(id):
memo = Memo.query.get(id)
return memo_schema.jsonify(memo)
# 更新备忘录
@app.route('/memo/<id>', methods=['PUT'])
def update_memo(id):
memo = Memo.query.get(id)
title = request.json['title']
content = request.json['content']
memo.title = title
memo.content = content
db.session.commit()
return memo_schema.jsonify(memo)
# 删除备忘录
@app.route('/memo/<id>', methods=['DELETE'])
def delete_memo(id):
memo = Memo.query.get(id)
db.session.delete(memo)
db.session.commit()
return memo_schema.jsonify(memo)
# 启动应用
if __name__ == '__main__':
app.run(debug=True)
```
这个代码实现了以下RESTful API:
- POST /memo - 添加一个备忘录
- GET /memo - 获取所有备忘录
- GET /memo/{id} - 获取单个备忘录
- PUT /memo/{id} - 更新一个备忘录
- DELETE /memo/{id} - 删除一个备忘录
你可以使用Postman或类似的工具来测试这个API。
阅读全文