use my api

This commit is contained in:
Syahdan Hafiz Ashari 2025-07-15 13:27:55 +07:00
parent 18240d264d
commit 03b2647f1e
16 changed files with 261 additions and 349 deletions

View File

@ -1,105 +1,84 @@
## Instalasi dan Penggunaan Web API # CostaPy
### Instalasi a Python WSGI Web Framework. Build with Bottle and Mako.
1. Install python
2. Buka CMD atau Command-prompt
3. cd nama/folder/costapy (di copy)
4. Jalankan command ini di CMD:
```sh
py -m pip install --upgrade pip
py -m pip install bottle
py -m pip install beaker
py -m pip install mako
py -m pip install mysql-connector
py -m pip install bcrypt
py -m pip install pyjwt[crypto]
```
5. Buka folder project pake VSCode
6. Buka file di config/server.py
7. servernya ganti dari 'gunicorn' ke 'wsgiref' (di save)
### Penggunaan
8. Buka CMD lalu jalanin service-nya:
- Untuk Windows:
```dos
cd C:\direktori\folder\kamu
py costa.py
```
- Untuk Linux/MacOS:
```sh
cd directory/folder/kamu
python costapy
```
9. kalau keluar output http://localhost:11000 artinya berhasil
10. Install bruno
11. bikin collection
12. test localhost:11000
13. Praktek ke VSCode
## Instalasi dan Implementasi MariaDB ## License
### Instalasi CostaPy
- Windows: Download dari mariadb.org atau dari xampp lalu install Copyright (C) 2022 Dita Aji Pratama
- Mac: Install melalui brew
- Debian/Ubuntu: sudo apt install mariadb-server
- Alternative lain: Pakai container (Docker)
### Penggunaan This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
- Terminal (Linux/MacOS): mariadb -u root -p This program is distributed in the hope that it will be useful,
- MySQL Client Command Prompt: Buka MySQL client lalu masukan password but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
### Implementasi (Buat Table di dalam MySQL Client) You should have received a copy of the GNU General Public License
along with this program. If not, see https://www.gnu.org/licenses/.
1. CREATE DATABASE latihan; # Getting Starter
2. USE latihan;
3. CREATE TABLE member (
id int(11) not null auto_increment primary key,
name varchar(36) not null,
phone varchar(14) null
);
4. SHOW COLUMNS FROM member;
5. INSERT INTO member VALUES (
DEFAULT,
'Nama_Kalian',
'Telp_Kalian'
);
6. SELECT * FROM member;
7. exit
## Persiapan bagi yang ketinggalan sebelum jalanin Widuri Client ## Requirement
- Download Python [disini](https://www.python.org/downloads/) lalu install
- Selesaikan task Instalasi dan Implementasi MariaDB dulu You need a `git`, `python`, `pip`, and `venv` before using CostaPy.
- Clone atau Download Widuri Client [disini](https://gitea.ditaajipratama.net/istek-widuri/widuri-client)
- Clone atau Download Widuri API [disini](https://gitea.ditaajipratama.net/istek-widuri/widuri-api) Install them using the following commands on your `Debian` or `Ubuntu` system.
- Buka CMD (Command-Prompt) lalu install kebutuhan library dengan command berikut:
- Untuk Linux/MacOS: ```bash
```sh sudo apt update
cd directory/folder/widuri-api sudo apt install git python3 python3-venv python3-pip
python -m pip install --upgrade pip ```
python -m pip install bottle
python -m pip install beaker or you can use the following command to install similar packages using `brew`, the package manager for `macOS`:
python -m pip install mako
python -m pip install mysql-connector ```bash
python -m pip install bcrypt brew install git python3
python -m pip install pyjwt[crypto] ```
``` Installs Python 3 with `brew`, which includes `python3`, `pip3`, and the `venv` module. If you don't have Homebrew installed on your `macOS`, you can install it first.
- Untuk Windows:
```dos or go to the [git downloads page](https://git-scm.com/downloads) and a [Python downloads page](https://www.python.org/downloads/) and download the latest version of git Python for `Windows`.
cd C:\direktori\folder\widuri-api
py -m pip install --upgrade pip ## Installation
py -m pip install bottle
py -m pip install beaker Download from repository
py -m pip install mako ```bash
py -m pip install mysql-connector git clone https://gitea.ditaajipratama.net/aji/costapy.git
py -m pip install bcrypt ```
py -m pip install pyjwt[crypto]
``` Go to the directory and install with this command:
```bash
cd costapy
bash install.sh
```
Use `cat install.sh` if you want to see a completed command.
## Usage
Use this command below to start the web service and it will run on port `11000` by default
```bash
.venv/bin/python3 costa.py costapy-welcome
```
Here, `costapy-welcome` is the label of your service. You can replace it with any name you prefer.
## Trivia
- Why must `venv`?
`venv` is a module in Python that provides support for creating lightweight, isolated Python environments, known as virtual environments. Each virtual environment has its own installation directories and can have its own versions of Python packages, independent of the system-wide Python environment.
When deploying a Python application, using a virtual environment ensures that only the required packages (and their specific versions) are bundled. This reduces the risk of deploying unnecessary packages or incompatible versions that could lead to runtime errors.
Using `venv` is a widely accepted best practice in the Python community. It encourages good habits in dependency management, ensuring that projects are self-contained and reducing the potential for "dependency hell."
When a project is no longer needed, deleting its virtual environment is straightforward and does not affect other projects or the system's Python environment.
- Why I add `venv` on my `gitignore`?
Committing `venv` to Git is gross. Virtual environments can contain thousands of files and their size can be in gigabytes. Committing them to Git can overload and clutter your source code repo with unnecessary files and cause confusion for anyone trying to clone and run the source code on their machine.
## Pengunaan widuri-client
1. Buka Command-Prompt
2. Ke directory Widuri API (Contoh: `cd C:\direktori\widuri-api`)
3. Nyalain service Widuri API: `py costa.py`
4. Buka Command-Prompt baru
5. Ke directory Widuri Client (Contoh: `cd C:\direktori\widuri-client`)
6. Nyalain service Widuri Client: `py -m http.server 12000`
7. buka `localhost:12000` di Browser

View File

@ -1,84 +0,0 @@
# CostaPy
a Python WSGI Web Framework. Build with Bottle and Mako.
## License
CostaPy
Copyright (C) 2022 Dita Aji Pratama
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see https://www.gnu.org/licenses/.
# Getting Starter
## Requirement
You need a `git`, `python`, `pip`, and `venv` before using CostaPy.
Install them using the following commands on your `Debian` or `Ubuntu` system.
```bash
sudo apt update
sudo apt install git python3 python3-venv python3-pip
```
or you can use the following command to install similar packages using `brew`, the package manager for `macOS`:
```bash
brew install git python3
```
Installs Python 3 with `brew`, which includes `python3`, `pip3`, and the `venv` module. If you don't have Homebrew installed on your `macOS`, you can install it first.
or go to the [git downloads page](https://git-scm.com/downloads) and a [Python downloads page](https://www.python.org/downloads/) and download the latest version of git Python for `Windows`.
## Installation
Download from repository
```bash
git clone https://gitea.ditaajipratama.net/aji/costapy.git
```
Go to the directory and install with this command:
```bash
cd costapy
bash install.sh
```
Use `cat install.sh` if you want to see a completed command.
## Usage
Use this command below to start the web service and it will run on port `11000` by default
```bash
.venv/bin/python3 costa.py costapy-welcome
```
Here, `costapy-welcome` is the label of your service. You can replace it with any name you prefer.
## Trivia
- Why must `venv`?
`venv` is a module in Python that provides support for creating lightweight, isolated Python environments, known as virtual environments. Each virtual environment has its own installation directories and can have its own versions of Python packages, independent of the system-wide Python environment.
When deploying a Python application, using a virtual environment ensures that only the required packages (and their specific versions) are bundled. This reduces the risk of deploying unnecessary packages or incompatible versions that could lead to runtime errors.
Using `venv` is a widely accepted best practice in the Python community. It encourages good habits in dependency management, ensuring that projects are self-contained and reducing the potential for "dependency hell."
When a project is no longer needed, deleting its virtual environment is straightforward and does not affect other projects or the system's Python environment.
- Why I add `venv` on my `gitignore`?
Committing `venv` to Git is gross. Virtual environments can contain thousands of files and their size can be in gigabytes. Committing them to Git can overload and clutter your source code repo with unnecessary files and cause confusion for anyone trying to clone and run the source code on their machine.

6
api/bruno.json Normal file
View File

@ -0,0 +1,6 @@
{
"version": "1",
"name": "costapy",
"type": "collection",
"ignore": ["node_modules", ".git"]
}

18
api/bruno/Create API.bru Normal file
View File

@ -0,0 +1,18 @@
meta {
name: Create API
type: http
seq: 6
}
post {
url: http://{{BASE_URL}}/api/create
body: json
auth: inherit
}
body:json {
{
"name": "Test Lagi",
"phone": "080000000002"
}
}

View File

@ -1,26 +0,0 @@
meta {
name: Create
type: http
seq: 2
}
get {
url: http://localhost:11000/api/:crud
body: json
auth: none
}
params:path {
crud: create
}
body:json {
{
"name":"Gepeng",
"phone":"7777777"
}
}
docs {
crud = add | edit | remove | list | detail
}

17
api/bruno/Delete API.bru Normal file
View File

@ -0,0 +1,17 @@
meta {
name: Delete API
type: http
seq: 6
}
delete {
url: http://{{BASE_URL}}/api/delete
body: json
auth: inherit
}
body:json {
{
"id": 8
}
}

View File

@ -1,25 +0,0 @@
meta {
name: Delete
type: http
seq: 5
}
get {
url: http://localhost:11000/api/:crud
body: json
auth: none
}
params:path {
crud: delete
}
body:json {
{
"key":5
}
}
docs {
crud = add | edit | remove | list | detail
}

11
api/bruno/Read API.bru Normal file
View File

@ -0,0 +1,11 @@
meta {
name: Read API
type: http
seq: 5
}
get {
url: http://{{BASE_URL}}/api/read
body: none
auth: inherit
}

View File

@ -1,26 +0,0 @@
meta {
name: Read
type: http
seq: 3
}
get {
url: http://localhost:11000/api/:crud
body: none
auth: none
}
params:path {
crud: read
}
body:json {
{
"name":"Gepeng",
"phone":"7777777"
}
}
docs {
crud = add | edit | remove | list | detail
}

19
api/bruno/Update API.bru Normal file
View File

@ -0,0 +1,19 @@
meta {
name: Update API
type: http
seq: 6
}
put {
url: http://{{BASE_URL}}/api/update
body: json
auth: inherit
}
body:json {
{
"id": 4,
"name": "Syahdan",
"phone": "082112586824"
}
}

View File

@ -1,27 +0,0 @@
meta {
name: Update
type: http
seq: 4
}
get {
url: http://localhost:11000/api/:crud
body: json
auth: none
}
params:path {
crud: update
}
body:json {
{
"key":5,
"name":"Gemblong",
"phone":"5555"
}
}
docs {
crud = add | edit | remove | list | detail
}

View File

@ -1,9 +0,0 @@
{
"version": "1",
"name": "Pemrograman-Web-ISTEK-WIDURI",
"type": "collection",
"ignore": [
"node_modules",
".git"
]
}

View File

@ -4,7 +4,7 @@ host = "localhost"
port = 11000 port = 11000
reloader = False reloader = False
debug = False debug = False
server = 'wsgiref' # default = 'wsgiref' server = 'gunicorn' # default = 'wsgiref'
session_opts = { session_opts = {
'session.type': 'file', 'session.type': 'file',

View File

@ -0,0 +1,3 @@
vars {
BASE_URL: localhost:11000
}

View File

@ -5,17 +5,38 @@
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along with this program. If not, see https://www.gnu.org/licenses/. # You should have received a copy of the GNU General Public License along with this program. If not, see https://www.gnu.org/licenses/.
from bottle import Bottle, route, request, response import json
from bottle import Bottle, route, response, request
from config import directory, database from config import directory, database
import mysql.connector as mariadb import mysql.connector as mariadb
import json
import templates.plain.main as template_public import templates.plain.main as template_public
import modules.public.home as public_home import modules.public.home as public_home
app = Bottle() app = Bottle()
# Sample data to simulate a database
# also serves as a model reminder
data = {
"member": [
{
"id": 1,
"name": "Syahdan",
"phone": "081234567890"
},
{
"id": 2,
"name": "Dita",
"phone": "081234567891"
},
{
"id": 3,
"name": "Aji",
"phone": "081234567892"
}
]
}
@app.route('/') @app.route('/')
def index(): def index():
params = { params = {
@ -26,65 +47,89 @@ def index():
return public_home.main().html(params) return public_home.main().html(params)
@app.route('/api/<crud>', method=['OPTIONS', 'GET', 'POST', 'PUT', 'DELETE']) @app.route('/api/<crud>', method=['OPTIONS', 'GET', 'POST', 'PUT', 'DELETE'])
def list(crud): def index(crud):
# Untuk menentukan tipe konten pada respon, yaitu: JSON
response.content_type = 'application/json' response.content_type = 'application/json'
# Mengambil request pada body, yaitu berformat JSON result = {
params = request.json "status": "error",
# Keluaran default "message": f"API endpoint for /api/{crud} is not implemented yet."
keluaran = {
"status":"Gagal",
"message":"Anda tidak ada otoritas untuk menggunakan endpoint ini",
"endpoint":f"/api/{crud}",
"data":[]
} }
db_main = mariadb.connect(**database.db_main) db_main = mariadb.connect(**database.db_main)
cursor = db_main.cursor(dictionary=True) cursor = db_main.cursor(dictionary=True)
if request.method == 'OPTIONS': payload = request.json
return None if crud == "create":
elif crud == "create": name = payload["name"]
name = params["name" ] phone = payload["phone"]
phone = params["phone" ]
cursor.execute("INSERT INTO `member` VALUES (DEFAULT, %s, %s) ;" , (name, phone) ) if not name or not phone:
keluaran["status"] = "Berhasil" result["status"] = "error"
keluaran["message"] = "Selamat data anda telah ditambah" result["message"] = "Name and phone are required."
keluaran["data"] = { return json.dumps(result, indent = 2).encode()
"name":name,
"phone":phone data_id = cursor.execute("INSERT INTO `member` (name, phone) VALUES (%s, %s);", (name, phone))
result["status"] = "success"
result["message"] = f'{payload["name"]} is added to the list.'
result["data"] = {
"name": name,
"phone": phone
} }
elif crud == "read": elif crud == "read":
cursor.execute("SELECT * FROM `member`; ") cursor.execute("SELECT * FROM `member`;")
member_list = cursor.fetchall() members = cursor.fetchall()
keluaran["status"] = "Berhasil"
keluaran["message"] = "Data collected" if not members:
keluaran["data"] = member_list result["status"] = "error"
result["message"] = "No members found."
return json.dumps(result, indent = 2).encode()
result["status"] = "success"
result["message"] = "Members collected."
result["data"] = members
elif crud == "update": elif crud == "update":
key = params["key" ] member_id = payload["id"]
name = params["name" ] name = payload["name"]
phone = params["phone" ] phone = payload["phone"]
cursor.execute("UPDATE `member` SET `name` = %s, `phone` = %s WHERE `id` = %s ;" , (name, phone, key) )
keluaran["status"] = "Berhasil" cursor.execute("UPDATE `member` SET `name` = %s, `phone` = %s WHERE `id` = %s ;" , (name, phone, member_id) )
keluaran["message"] = "Belum dibikin" db_main.commit()
keluaran["data"] = { cursor.execute("SELECT * FROM `member` WHERE `id` = %s;", (member_id,))
"key":params["key"], member = cursor.fetchone()
"name":params["name"],
"phone":params["phone"] if not member:
result["status"] = "error"
result["message"] = f'Member with ID {member_id} not found.'
return json.dumps(result, indent = 2).encode()
result["status"] = "success"
result["message"] = f'Member with ID {member_id} is updated.'
result["data"] = {
"id" : member["id"],
"name" : member["name"],
"phone": member["phone"]
} }
elif crud == "delete": elif crud == "delete":
key = params["key" ] member_id = payload["id"]
cursor.execute("DELETE FROM `member` WHERE `id` = %s ;" , (key,) ) cursor.execute("SELECT * FROM `member` WHERE `id` = %s;", (member_id,))
keluaran["status"] = "Berhasil" member = cursor.fetchone()
keluaran["message"] = "Data sudah terhapus selamanya!" if not member:
result["status"] = "error"
else: result["message"] = f'Member with ID {member_id} not found.'
pass return json.dumps(result, indent = 2).encode()
cursor.execute("DELETE FROM `member` WHERE `id` = %s;", (member_id,))
cursor.close() result["status"] = "success"
db_main.close() result["message"] = f'Member with ID {member_id} is deleted.'
result["data"] = {
return json.dumps(keluaran, indent = 2).encode() "id" : member["id"],
"name" : member["name"],
"phone": member["phone"]
}
return json.dumps(result, indent = 2).encode()

11
api/sql/init.sql Normal file
View File

@ -0,0 +1,11 @@
CREATE TABLE member (
id int(11) not null auto_increment primary key,
name varchar(36) not null,
phone varchar(14) null
);
INSERT INTO member VALUES
(DEFAULT, 'Syahdan', '081111111111'),
(DEFAULT, 'Hafiz', '082222222222'),
(DEFAULT, 'Ashari', '083333333333');