Thursday, November 27, 2025

.::: Simulation API POST Using Phyton & MariaDB MySQL with HTTP Status Code 500, 422, 200, 405 :::.

 


1. Install phyton

sudo dnf install python3 python3-pip -y
pip3 install flask mysql-connector-python


2. create database sample & insert data  

CREATE DATABASE hris;
USE hris;

CREATE TABLE buy_period (
    id INT AUTO_INCREMENT PRIMARY KEY,
    period_year INT NOT NULL,
    period_month INT NOT NULL,
    start_date DATE NOT NULL,
    end_date DATE NOT NULL
);

 INSERT INTO buy_period (period_year, period_month, start_date, end_date)
VALUES (2025, 1, '2025-01-01', '2025-01-31');

INSERT INTO buy_period (period_year, period_month, start_date, end_date)
VALUES (2025, 5, '2025-05-01', '2025-05-31');


3. create phyton script API 

cat /data/api/api_buy.py

[root@teguhth api]# pwd
/data/api
[root@teguhth api]# cat 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=['POST'])
def get_buy_period():
    data = request.get_json()

    # Jika parameter tidak dikirim ? ERROR 422
    if not data or "year" not in data or "month" not in data:
        return jsonify({
            "MESSAGE": "Unprocessable Entity",
            "ERRORS": ["failed get buy period"],
            "TRACE_ID": "sim123"
        }), 422

    year = data["year"]
    month = data["month"]

    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()

    # Jika tidak ditemukan
    if row is None:
        return jsonify({
            "MESSAGE": "Unprocessable Entity",
            "ERRORS": ["failed get buy period"],
            "TRACE_ID": "sim124"
        }), 422

    return jsonify({
        "MESSAGE": "SUCCESS",
        "DATA": row
    })

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8080)
from flask import Flask, request, jsonify
import mysql.connector

app = Flask(__name__)

def get_db():
    return mysql.connector.connect(
        host="localhost",
        user="root",
        password="YOURPASSWORD",
        database="hris"
    )

@app.route('/get-buy-period', methods=['POST'])
def get_buy_period():
    data = request.get_json()

    # Jika parameter tidak dikirim ? ERROR 422
    if not data or "year" not in data or "month" not in data:
        return jsonify({
            "MESSAGE": "Unprocessable Entity",
            "ERRORS": ["failed get buy period"],
            "TRACE_ID": "sim123"
        }), 422

    year = data["year"]
    month = data["month"]

    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()

    # Jika tidak ditemukan
    if row is None:
        return jsonify({
            "MESSAGE": "Unprocessable Entity",
            "ERRORS": ["failed get buy period"],
            "TRACE_ID": "sim124"
        }), 422

    return jsonify({
        "MESSAGE": "SUCCESS",
        "DATA": row
    })

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8080)
[root@teguhth api]#

4. run phyton script for test in new console

python3 /data/api/api_buy.py

5. simulation true

curl -X POST http://127.0.0.1:8080/get-buy-period -H "Content-Type: application/json" -d '{"year": 2025, "month": 1}'
curl -X POST http://10.10.10.90:8080/get-buy-period -H "Content-Type: application/json" -d '{"year": 2025, "month": 1}'

[root@teguhth api]# curl -X POST http://10.10.10.90:8080/get-buy-period -H "Content-Type: application/json" -d '{"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]#

 


 


6. Uji Simulasi (menghasilkan ERROR yang sama) Contoh request yang salah (tanpa parameter)

curl -X POST http://127.0.0.1:8080/get-buy-period -H "Content-Type: application/json" -d '{}'
curl -X POST http://10.10.10.90:8080/get-buy-period -H "Content-Type: application/json" -d '{}'

[root@teguhth api]# curl -X POST http://10.10.10.90:8080/get-buy-period -H "Content-Type: application/json" -d '{}'
{"ERRORS":["failed get buy period"],"MESSAGE":"Unprocessable Entity","TRACE_ID":"sim123"}
[root@teguhth api]#

 

 


7. Contoh request dengan periode yang tidak ada

curl -X POST http://127.0.0.1:8080/get-buy-period -H "Content-Type: application/json" -d '{"year": 2025, "month": 7}'
curl -X POST http://10.10.10.90:8080/get-buy-period -H "Content-Type: application/json" -d '{"year": 2025, "month": 7}'

[root@teguhth api]# curl -X POST http://10.10.10.90:8080/get-buy-period -H "Content-Type: application/json" -d '{"year": 2025, "month": 7}'
{"ERRORS":["failed get buy period"],"MESSAGE":"Unprocessable Entity","TRACE_ID":"sim124"}
[root@teguhth api]#

 


8. simulasi jika database & table tidak ada 

curl -X POST http://10.10.10.90:8080/get-buy-period -H "Content-Type: application/json" -d '{"year": 2025, "month": 1}'

[root@teguhth api]# curl -X POST http://10.10.10.90:8080/get-buy-period -H "Content-Type: application/json" -d '{"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]#
 

 


9. simulasi jika table data masih belum ada isi  


curl -X POST http://10.10.10.90:8080/get-buy-period -H "Content-Type: application/json" -d '{"year": 2025, "month": 1}'

[root@teguhth api]# curl -X POST http://10.10.10.90:8080/get-buy-period -H "Content-Type: application/json" -d '{"year": 2025, "month": 1}'
{"ERRORS":["failed get buy period"],"MESSAGE":"Unprocessable Entity","TRACE_ID":"sim124"}
[root@teguhth api]#

 

 


10. menggunakan GET & PUT 

curl -X GET http://10.10.10.90:8080/get-buy-period -H "Content-Type: application/json" -d '{"year": 2025, "month": 1}'
curl -X PUT http://10.10.10.90:8080/get-buy-period -H "Content-Type: application/json" -d '{"year": 2025, "month": 1}'

[root@teguhth api]# curl -X GET http://10.10.10.90:8080/get-buy-period -H "Content-Type: application/json" -d '{"year": 2025, "month": 1}'
<!doctype html>
<html lang=en>
<title>405 Method Not Allowed</title>
<h1>Method Not Allowed</h1>
<p>The method is not allowed for the requested URL.</p>
[root@teguhth api]#

[root@teguhth api]# curl -X PUT http://10.10.10.90:8080/get-buy-period -H "Content-Type: application/json" -d '{"year": 2025, "month": 1}'
<!doctype html>
<html lang=en>
<title>405 Method Not Allowed</title>
<h1>Method Not Allowed</h1>
<p>The method is not allowed for the requested URL.</p>
[root@teguhth api]#
[root@teguhth api]#
 
 


  


11. Tutorial
 



 

No comments:

Post a Comment

Popular Posts