Wednesday, December 17, 2025

.::: Simulation API HEAD Using Phyton & MariaDB MySQL with HTTP Status Code 200,404 :::.

 
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/head_api_buy.py

[[root@teguhth ~]# cat /data/api/head_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', 'HEAD'])
def get_buy_period():

    # HEAD hanya untuk cek endpoint hidup
    if request.method == 'HEAD':
        return '', 200

    data = request.get_json()

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

    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 ~]#


4. run phyton script for test in new console

python3 /data/api/head_api_buy.py
 


5. simulation true

curl -I http://localhost:8080/get-buy-period

[root@teguhth ~]# curl -I http://localhost:8080/get-buy-period
HTTP/1.1 200 OK
Server: Werkzeug/3.1.3 Python/3.9.21
Date: Wed, 17 Dec 2025 09:08:25 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 0
Connection: close

[root@teguhth ~]#
 



6. Uji Simulasi salah url 

[root@teguhth ~]# curl -I http://10.10.10.90:8080/get-buy-period1
HTTP/1.1 404 NOT FOUND
Server: Werkzeug/3.1.3 Python/3.9.21
Date: Wed, 17 Dec 2025 09:13:38 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 207
Connection: close

[root@teguhth ~]#
 


 

No comments:

Post a Comment

Popular Posts