以下是一个使用Python Flask框架编写的API设计示例,用于验证和保存场景。
from flask import Flask, request, jsonify
app = Flask(__name__)
# 存储场景的字典
scenes = {}
# POST请求用于创建新的场景
@app.route('/api/scene', methods=['POST'])
def create_scene():
scene_data = request.json
# 验证请求中的数据是否完整
if 'name' not in scene_data or 'description' not in scene_data:
return jsonify({'error': 'Missing data'}), 400
name = scene_data['name']
description = scene_data['description']
# 存储场景到字典中
scenes[name] = description
return jsonify({'message': 'Scene created successfully'}), 201
# GET请求用于获取特定场景的描述
@app.route('/api/scene/', methods=['GET'])
def get_scene(name):
# 检查场景是否存在
if name not in scenes:
return jsonify({'error': 'Scene not found'}), 404
description = scenes[name]
return jsonify({'name': name, 'description': description}), 200
if __name__ == '__main__':
app.run()
使用上述代码,你可以通过发送POST请求来创建新的场景,并使用GET请求获取特定场景的描述。
要创建新的场景,可以发送以下JSON数据到/api/scene
端点:
{
"name": "场景名称",
"description": "场景描述"
}
要获取特定场景的描述,可以发送GET请求到/api/scene/场景名称
端点。
请注意,以上代码只提供了基本的API设计示例,你可以根据自己的需求进行修改和扩展。
上一篇:API设计通知调用模块并继续执行
下一篇:API设计中的内部可变性滥用?