iT邦幫忙

2024 iThome 鐵人賽

DAY 22
0
Python

Python自修系列 第 22

DAY22:構建一個簡單的 API

  • 分享至 

  • xImage
  •  

app.py

from flask import Flask, jsonify, request, abort

app = Flask(__name__)

# 模擬數據庫中的數據
data_store = [
    {"id": 1, "name": "Item 1", "description": "This is item 1"},
    {"id": 2, "name": "Item 2", "description": "This is item 2"},
    {"id": 3, "name": "Item 3", "description": "This is item 3"}
]

# 根路由,返回首頁
@app.route('/')
def index():
    return "Welcome to the Flask API"

# 獲取所有項目
@app.route('/api/items', methods=['GET'])
def get_items():
    return jsonify(data_store)

# 獲取單個項目
@app.route('/api/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
    item = next((item for item in data_store if item['id'] == item_id), None)
    if item is None:
        abort(404)
    return jsonify(item)

# 創建新項目
@app.route('/api/items', methods=['POST'])
def create_item():
    if not request.json or not 'name' in request.json:
        abort(400)
    new_item = {
        'id': data_store[-1]['id'] + 1 if data_store else 1,
        'name': request.json['name'],
        'description': request.json.get('description', "")
    }
    data_store.append(new_item)
    return jsonify(new_item), 201

# 更新項目
@app.route('/api/items/<int:item_id>', methods=['PUT'])
def update_item(item_id):
    item = next((item for item in data_store if item['id'] == item_id), None)
    if item is None:
        abort(404)
    if not request.json:
        abort(400)
    item['name'] = request.json.get('name', item['name'])
    item['description'] = request.json.get('description', item['description'])
    return jsonify(item)

# 刪除項目
@app.route('/api/items/<int:item_id>', methods=['DELETE'])
def delete_item(item_id):
    item = next((item for item in data_store if item['id'] == item_id), None)
    if item is None:
        abort(404)
    data_store.remove(item)
    return jsonify({'result': True})

if __name__ == '__main__':
    app.run(debug=True)

GET /api/items

curl http://127.0.0.1:5000/api/items

GET /api/items/1

curl http://127.0.0.1:5000/api/items/1

POST /api/items

curl -X POST -H "Content-Type: application/json" -d '{"name": "New Item", "description": "This is a new item"}' http://127.0.0.1:5000/api/items

PUT /api/items/1

curl -X PUT -H "Content-Type: application/json" -d '{"name": "Updated Item", "description": "This is an updated item"}' http://127.0.0.1:5000/api/items/1

DELETE /api/items/1

curl -X DELETE http://127.0.0.1:5000/api/items/1


上一篇
DAY21:介紹後端框架 Flask 或 Django 並構建一個基本的後端應用
下一篇
DAY23:數據爬取和分析功能
系列文
Python自修30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言