Chủ Nhật, 20 tháng 7, 2025

🌐 BÀI 19: XÂY DỰNG REST API VỚI FLASK – GET, POST, PUT, DELETE DỮ LIỆU JSON

🎯 1. REST API là gì?

REST API (Representational State Transfer) cho phép:

  • Giao tiếp giữa các hệ thống qua HTTP

  • Truyền và nhận dữ liệu bằng JSON

  • Dùng các phương thức HTTP chuẩn:

    • GET: lấy dữ liệu

    • POST: thêm dữ liệu

    • PUT: cập nhật dữ liệu

    • DELETE: xóa dữ liệu


✅ 2. Yêu cầu: cài Flask và pandas

bash
pip install flask pandas

🧱 3. Tạo file api.py với nội dung hoàn chỉnh

python
from flask import Flask, request, jsonify import pandas as pd import os app = Flask(__name__) CSV_FILE = "students.csv" # Hàm đọc dữ liệu def load_data(): if os.path.exists(CSV_FILE): return pd.read_csv(CSV_FILE) return pd.DataFrame(columns=["id", "name", "score"]) # Hàm ghi dữ liệu def save_data(df): df.to_csv(CSV_FILE, index=False) # Lấy danh sách sinh viên @app.route("/api/students", methods=["GET"]) def get_students(): df = load_data() return jsonify(df.to_dict(orient="records")) # Lấy 1 sinh viên theo id @app.route("/api/students/<int:sid>", methods=["GET"]) def get_student(sid): df = load_data() student = df[df["id"] == sid] if student.empty: return jsonify({"error": "Student not found"}), 404 return jsonify(student.iloc[0].to_dict()) # Thêm sinh viên (POST) @app.route("/api/students", methods=["POST"]) def add_student(): data = request.get_json() df = load_data() if not all(k in data for k in ("id", "name", "score")): return jsonify({"error": "Thiếu trường id, name hoặc score"}), 400 if df[df["id"] == data["id"]].shape[0] > 0: return jsonify({"error": "ID đã tồn tại"}), 409 df = pd.concat([df, pd.DataFrame([data])], ignore_index=True) save_data(df) return jsonify({"message": "Thêm thành công"}), 201 # Cập nhật sinh viên (PUT) @app.route("/api/students/<int:sid>", methods=["PUT"]) def update_student(sid): df = load_data() data = request.get_json() index = df.index[df["id"] == sid] if index.empty: return jsonify({"error": "Không tìm thấy sinh viên"}), 404 for key in ["name", "score"]: if key in data: df.at[index[0], key] = data[key] save_data(df) return jsonify({"message": "Đã cập nhật"}), 200 # Xóa sinh viên (DELETE) @app.route("/api/students/<int:sid>", methods=["DELETE"]) def delete_student(sid): df = load_data() new_df = df[df["id"] != sid] if df.shape[0] == new_df.shape[0]: return jsonify({"error": "Không tìm thấy sinh viên"}), 404 save_data(new_df) return jsonify({"message": "Đã xóa sinh viên"}), 200 if __name__ == "__main__": app.run(debug=True)

🧪 4. Cách kiểm thử API

⚙️ a. Dùng curl hoặc Postman

GET danh sách:

bash
curl http://127.0.0.1:5000/api/students

POST thêm sinh viên:

bash
curl -X POST http://127.0.0.1:5000/api/students \ -H "Content-Type: application/json" \ -d '{"id": 1, "name": "Minh", "score": 8.5}'

PUT cập nhật:

bash
curl -X PUT http://127.0.0.1:5000/api/students/1 \ -H "Content-Type: application/json" \ -d '{"score": 9.0}'

DELETE sinh viên:

bash
curl -X DELETE http://127.0.0.1:5000/api/students/1

✅ 5. Tóm tắt endpoint REST API

Phương thứcEndpointMô tả
GET/api/studentsLấy danh sách
GET/api/students/<id>Lấy 1 sinh viên
POST/api/studentsThêm sinh viên
PUT/api/students/<id>Cập nhật thông tin
DELETE/api/students/<id>Xóa sinh viên

✅ 6. Kết luận

  • Bạn đã xây dựng một REST API đơn giản, chuẩn RESTful, xử lý bằng file CSV

  • Có thể gọi từ web app, mobile app, Postman, curl...

  • Là nền tảng để phát triển backend chuyên nghiệp: Flask + JSON + REST

=============================
Website không chứa bất kỳ quảng cáo nào, mọi đóng góp để duy trì phát triển cho website (donation) xin vui lòng gửi về STK 90.2142.8888 - Ngân hàng Vietcombank Thăng Long - TRAN VAN BINH
=============================
Nếu bạn không muốn bị AI thay thế và tiết kiệm 3-5 NĂM trên con đường trở thành DBA chuyên nghiệp hay làm chủ Database thì hãy đăng ký ngay KHOÁ HỌC ORACLE DATABASE A-Z ENTERPRISE, được Coaching trực tiếp từ tôi với toàn bộ bí kíp thực chiến, thủ tục, quy trình của gần 20 năm kinh nghiệm (mà bạn sẽ KHÔNG THỂ tìm kiếm trên Internet/Google) từ đó giúp bạn dễ dàng quản trị mọi hệ thống Core tại Việt Nam và trên thế giới, đỗ OCP.
- CÁCH ĐĂNG KÝ: Gõ (.) hoặc để lại số điện thoại hoặc inbox https://m.me/tranvanbinh.vn hoặc Hotline/Zalo 090.29.12.888
- Chi tiết tham khảo:
https://bit.ly/oaz_w
=============================
2 khóa học online qua video giúp bạn nhanh chóng có những kiến thức nền tảng về Linux, Oracle, học mọi nơi, chỉ cần có Internet/4G:
- Oracle cơ bản: https://bit.ly/admin_1200
- Linux: https://bit.ly/linux_1200
=============================
KẾT NỐI VỚI CHUYÊN GIA TRẦN VĂN BÌNH:
📧 Mail: binhoracle@gmail.com
☎️ Mobile/Zalo: 0902912888
👨 Facebook: https://www.facebook.com/BinhOracleMaster
👨 Inbox Messenger: https://m.me/101036604657441 (profile)
👨 Fanpage: https://www.facebook.com/tranvanbinh.vn
👨 Inbox Fanpage: https://m.me/tranvanbinh.vn
👨👩 Group FB: https://www.facebook.com/groups/DBAVietNam
👨 Website: https://www.tranvanbinh.vn
👨 Blogger: https://tranvanbinhmaster.blogspot.com
🎬 Youtube: https://www.youtube.com/@binhguru
👨 Tiktok: https://www.tiktok.com/@binhguru
👨 Linkin: https://www.linkedin.com/in/binhoracle
👨 Twitter: https://twitter.com/binhguru
👨 Podcast: https://www.podbean.com/pu/pbblog-eskre-5f82d6
👨 Địa chỉ: Tòa nhà Sun Square - 21 Lê Đức Thọ - Phường Mỹ Đình 1 - Quận Nam Từ Liêm - TP.Hà Nội

=============================
AI, trí tuệ nhân tạo, artificial intelligence, machine learning, deep learning, LLM, ChatGPT, DeepSeek, Grok, oracle tutorial, học oracle database, Tự học Oracle, Tài liệu Oracle 12c tiếng Việt, Hướng dẫn sử dụng Oracle Database, Oracle SQL cơ bản, Oracle SQL là gì, Khóa học Oracle Hà Nội, Học chứng chỉ Oracle ở đầu, Khóa học Oracle online,sql tutorial, khóa học pl/sql tutorial, học dba, học dba ở việt nam, khóa học dba, khóa học dba sql, tài liệu học dba oracle, Khóa học Oracle online, học oracle sql, học oracle ở đâu tphcm, học oracle bắt đầu từ đâu, học oracle ở hà nội, oracle database tutorial, oracle database 12c, oracle database là gì, oracle database 11g, oracle download, oracle database 19c, oracle dba tutorial, oracle tunning, sql tunning , oracle 12c, oracle multitenant, Container Databases (CDB), Pluggable Databases (PDB), oracle cloud, oracle security, oracle fga, audit_trail,oracle RAC, ASM, oracle dataguard, oracle goldengate, mview, oracle exadata, oracle oca, oracle ocp, oracle ocm , oracle weblogic, postgresql tutorial, mysql tutorial, mariadb tutorial, ms sql server tutorial, nosql, mongodb tutorial, oci, cloud, middleware tutorial, hoc solaris tutorial, hoc linux tutorial, hoc aix tutorial, unix tutorial, securecrt, xshell, mobaxterm, putty

ĐỌC NHIỀU

Trần Văn Bình - Oracle Database Master