continue from https://teguhth.blogspot.com/2025/11/simulation-api-post-using-phyton.html
1. script get sample
[root@teguhth api]# cat /data/api/get_api_buy.py
from flask import Flask, request, jsonify
import mysql.connector
app = Flask(__name__)
def get_db():
return mysql.connector.connect(
host="localhost",
user="admin",
password="admin",
database="hris"
)
@app.route('/get-buy-period', methods=['GET'])
def get_buy_period():
# Ambil data dari query string
year = request.args.get("year")
month = request.args.get("month")
# Validasi input
if year is None or month is None:
return jsonify({
"MESSAGE": "Bad Request",
"ERRORS": ["missing year or month"],
"TRACE_ID": "sim123"
}), 400
db = get_db()
cursor = db.cursor(dictionary=True)
cursor.execute("""
SELECT * FROM buy_period
WHERE period_year=%s AND period_month=%s
""", (year, month))
row = cursor.fetchone()
if row is None:
return jsonify({
"MESSAGE": "Not Found",
"ERRORS": ["buy period not found"],
"TRACE_ID": "sim124"
}), 404
return jsonify({
"MESSAGE": "SUCCESS",
"DATA": row
}), 200
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8080)
[root@teguhth api]#
2. Testing success
curl "http://10.10.10.90:8080/get-buy-period?year=2025&month=1"
[root@teguhth api]# curl "http://10.10.10.90:8080/get-buy-period?year=2025&month=1"
{"DATA":{"end_date":"Fri, 31 Jan 2025 00:00:00 GMT","id":1,"period_month":1,"period_year":2025,"start_date":"Wed, 01 Jan 2025 00:00:00 GMT"},"MESSAGE":"SUCCESS"}
[root@teguhth api]#
3. Contoh request dengan periode yang tidak ada
curl "http://10.10.10.90:8080/get-buy-period?year=2025&month=7"
[root@teguhth api]# curl "http://10.10.10.90:8080/get-buy-period?year=2025&month=7"
{"ERRORS":["buy period not found"],"MESSAGE":"Not Found","TRACE_ID":"sim124"}
[root@teguhth api]#
4. Contoh request dengan parameter tidak ada
curl "http://10.10.10.90:8080/get-buy-period?"
[root@teguhth api]# curl "http://10.10.10.90:8080/get-buy-period?"
{"ERRORS":["missing year or month"],"MESSAGE":"Bad Request","TRACE_ID":"sim123"}
[root@teguhth api]#
5. simulasi jika database & table tidak ada
curl "http://10.10.10.90:8080/get-buy-period?year=2025&month=1"
[root@teguhth api]# curl "http://10.10.10.90:8080/get-buy-period?year=2025&month=1"
<!doctype html>
<html lang=en>
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>
[root@teguhth api]#
6. simulasi jika table data masih belum ada isi
curl "http://10.10.10.90:8080/get-buy-period?year=2025&month=1"
[root@teguhth api]# curl "http://10.10.10.90:8080/get-buy-period?year=2025&month=1"
{"ERRORS":["buy period not found"],"MESSAGE":"Not Found","TRACE_ID":"sim124"}
[root@teguhth api]#


















No comments:
Post a Comment