2025-10-08
admin
Diperbarui 2025-10-11

NEO Storage API: Panduan Testing, Penggunaan, & Contoh Kode Lengkap

Ingin menguji dan menggunakan NEO Storage API? Panduan ini mencakup instalasi, testing Web UI & endpoint, contoh kode, dan troubleshooting. Optimalkan penyimpanan data Anda sekarang!
NEO Storage API: Panduan Testing, Penggunaan, & Contoh Kode Lengkap

🧪 Testing & Usage Guide - NEO Storage API

📋 Table of Contents

  1. Quick Start
  2. Testing Web UI
  3. Testing API Endpoints
  4. Python Examples
  5. cURL Examples
  6. Troubleshooting

🚀 Quick Start

1. Instalasi

# Clone dan install dependencies
git clone <repo-url>
cd neo-storage-api
pip install -r requirements.txt

# Setup environment
cp .env.example .env
# Edit .env dengan kredensial Anda

# Run aplikasi
python app.py

2. Access Web UI

http://localhost:7600

🌐 Testing Web UI

Login Flow

Step 1: Login Page

  1. Buka browser → http://localhost:7600
  2. Masukkan nomor WhatsApp (contoh: 081234567890)
  3. Klik "Kirim Kode OTP"
  4. Pastikan WhatsApp Gateway berjalan di http://10.122.25.172:5000

Step 2: Verify OTP

  1. Cek WhatsApp untuk kode OTP 6 digit
  2. Masukkan kode OTP
  3. Otomatis login jika kode valid

Dashboard Features

User Dashboard

  • Overview Stats: Total API keys, requests, storage status
  • Quick Actions: Create API key, view logs
  • API Documentation: Endpoint reference

Admin Dashboard (Only for role=admin)

  • Semua fitur user +
  • User Management
  • Global monitoring semua user
  • System statistics

API Key Management

Membuat API Key

  1. Login → Menu "API Keys"
  2. Isi form:
  • Nama: Foto Presensi
  • Deskripsi: Upload foto untuk sistem presensi karyawan
  1. Klik "Generate API Key"
  2. Copy API key yang muncul
  3. Simpan API key dengan aman!

Contoh Use Cases API Key:

  • Foto Presensi - Upload foto karyawan
  • Gambar Website - Upload gambar untuk CMS
  • Dokumen PDF - Upload dokumen
  • Video Training - Upload video pembelajaran

Access Logs

User View

  • Hanya melihat log aktivitas sendiri
  • Filter by endpoint, method, status

Admin View

  • Melihat semua log dari semua user
  • Statistics: success rate, avg response time
  • Filter by user, API key, date range

User Management (Admin Only)

Menambah User

  1. Login sebagai admin
  2. Menu "Users" → "Tambah Pengguna Baru"
  3. Isi data:
  • Nomor WhatsApp: 081234567890
  • Nama: John Doe
  • Role: user atau admin
  1. User bisa langsung login dengan OTP

Manage Users

  • Toggle Status: Aktifkan/nonaktifkan user
  • Delete User: Hapus user (semua API key & log akan terhapus)
  • View Stats: Lihat jumlah API keys & requests per user

🔌 Testing API Endpoints

Setup

# Set environment variables
export BASE_URL="http://localhost:7600"
export API_KEY="your-api-key-here"

1. API Info

curl -X GET $BASE_URL/api/info

Response:

{
  "service": "NEO Storage API - IndoWeb ID",
  "version": "1.0.0",
  "endpoints": [...]
}

2. Upload File

curl -X POST $BASE_URL/api/upload \
  -H "X-API-Key: $API_KEY" \
  -F "file=@/path/to/image.jpg" \
  -F "folder=uploads"

Response:

{
  "success": true,
  "url": "http://storage-url/uploads/20251005_123456_abc123_image.jpg",
  "filename": "20251005_123456_abc123_image.jpg",
  "object_key": "uploads/20251005_123456_abc123_image.jpg"
}

3. List Files

curl -X GET "$BASE_URL/api/files?folder=uploads" \
  -H "X-API-Key: $API_KEY"

Response:

{
  "success": true,
  "files": [
    {
      "key": "uploads/file.jpg",
      "filename": "file.jpg",
      "size": 12345,
      "modified": "2025-10-05 10:30:00",
      "url": "http://storage-url/uploads/file.jpg"
    }
  ]
}

4. Delete File

curl -X POST $BASE_URL/api/delete \
  -H "X-API-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"object_key": "uploads/file.jpg"}'

Response:

{
  "success": true
}

🐍 Python Examples

Basic Upload

import requests

# Configuration
base_url = "http://localhost:7600"
api_key = "your-api-key-here"
headers = {"X-API-Key": api_key}

# Upload file
with open("image.jpg", "rb") as f:
    files = {"file": f}
    data = {"folder": "uploads"}
    
    response = requests.post(
        f"{base_url}/api/upload",
        headers=headers,
        files=files,
        data=data
    )
    
    result = response.json()
    print(f"Upload success: {result['success']}")
    print(f"File URL: {result['url']}")

Upload Multiple Files

import requests
import os

base_url = "http://localhost:7600"
api_key = "your-api-key-here"
headers = {"X-API-Key": api_key}

# Upload semua file dalam folder
folder_path = "/path/to/images"
uploaded_urls = []

for filename in os.listdir(folder_path):
    if filename.endswith(('.jpg', '.png', '.jpeg')):
        file_path = os.path.join(folder_path, filename)
        
        with open(file_path, "rb") as f:
            files = {"file": f}
            data = {"folder": "batch_upload"}
            
            response = requests.post(
                f"{base_url}/api/upload",
                headers=headers,
                files=files,
                data=data
            )
            
            if response.status_code == 200:
                result = response.json()
                uploaded_urls.append(result['url'])
                print(f"✅ Uploaded: {filename}")
            else:
                print(f"❌ Failed: {filename}")

print(f"\nTotal uploaded: {len(uploaded_urls)}")

Complete Example with Error Handling

import requests
from typing import Optional, Dict

class NEOStorageClient:
    def __init__(self, base_url: str, api_key: str):
        self.base_url = base_url
        self.headers = {"X-API-Key": api_key}
    
    def upload_file(self, file_path: str, folder: str = "uploads") -> Optional[Dict]:
        """Upload file ke NEO Storage"""
        try:
            with open(file_path, "rb") as f:
                files = {"file": f}
                data = {"folder": folder}
                
                response = requests.post(
                    f"{self.base_url}/api/upload",
                    headers=self.headers,
                    files=files,
                    data=data,
                    timeout=30
                )
                
                response.raise_for_status()
                return response.json()
                
        except requests.exceptions.RequestException as e:
            print(f"Upload error: {e}")
            return None
    
    def list_files(self, folder: str = "uploads") -> Optional[Dict]:
        """List semua file"""
        try:
            response = requests.get(
                f"{self.base_url}/api/files",
                headers=self.headers,
                params={"folder": folder},
                timeout=10
            )
            
            response.raise_for_status()
            return response.json()
            
        except requests.exceptions.RequestException as e:
            print(f"List error: {e}")
            return None
    
    def delete_file(self, object_key: str) -> bool:
        """Delete file"""
        try:
            response = requests.post(
                f"{self.base_url}/api/delete",
                headers=self.headers,
                json={"object_key": object_key},
                timeout=10
            )
            
            response.raise_for_status()
            result = response.json()
            return result.get("success", False)
            
        except requests.exceptions.RequestException as e:
            print(f"Delete error: {e}")
            return False

# Usage
if __name__ == "__main__":
    client = NEOStorageClient(
        base_url="http://localhost:7600",
        api_key="your-api-key-here"
    )
    
    # Upload
    result = client.upload_file("photo.jpg", "presensi")
    if result and result['success']:
        print(f"Uploaded: {result['url']}")
        
        # Delete
        if client.delete_file(result['object_key']):
            print("File deleted successfully")

📝 cURL Examples

Upload dengan Custom Folder

curl -X POST http://localhost:7600/api/upload \
  -H "X-API-Key: your-api-key" \
  -F "[email protected]" \
  -F "folder=presensi/2025/januari"

Upload PDF Document

curl -X POST http://localhost:7600/api/upload \
  -H "X-API-Key: your-api-key" \
  -F "[email protected]" \
  -F "folder=documents"

List Files dari Folder Spesifik

curl -X GET "http://localhost:7600/api/files?folder=presensi/2025/januari" \
  -H "X-API-Key: your-api-key"

Pretty Print JSON Response

curl -X GET http://localhost:7600/api/files \
  -H "X-API-Key: your-api-key" | python -m json.tool

🔧 Troubleshooting

Problem: OTP Tidak Terkirim

Solusi:

  1. Pastikan WhatsApp Gateway running:
curl http://10.122.25.172:5000/api/status
  1. Check .env file:
WA_API_URL=http://10.122.25.172:5000/api/send-messageWA_ADMIN_NUMBER=6281241314446
  1. Test manual send message:
curl -X POST http://10.122.25.172:5000/api/send-message \  -H "Content-Type: application/json" \  -d '{"phone":"081234567890","message":"Test"}'

Problem: Upload Failed - Invalid API Key

Solusi:

  1. Pastikan API key benar:
# Check di web UI: Menu API Keys
  1. Pastikan header format benar:
-H "X-API-Key: your-api-key"# atau-H "Authorization: Bearer your-api-key"

Problem: Storage Connection Failed

Solusi:

  1. Verify NEO credentials di .env:
NEO_ACCESS_KEY=your-keyNEO_SECRET_KEY=your-secretNEO_ENDPOINT=http://your-endpointNEO_BUCKET=your-bucketNEO_USE_SSL=false
  1. Test bucket access:
curl http://localhost:7600/test-connection

Problem: Permission Denied

Solusi:

  1. Check user status (harus active):
SELECT * FROM user WHERE phone='081234567890';
  1. Check API key status:
SELECT * FROM api_key WHERE user_id=1;

Problem: Database Locked

Solusi:

# Stop service
sudo systemctl stop neo-storage-api

# Remove lock
rm -f neo_storage.db-journal

# Restart
sudo systemctl start neo-storage-api

📊 Monitoring & Logs

View Real-time Logs

# Systemd logs
journalctl -u neo-storage-api -f

# Application logs
tail -f /var/log/neo-storage-api.log

Check Service Status

sudo systemctl status neo-storage-api

Database Queries

# Login to database
sqlite3 neo_storage.db

# Useful queries:
SELECT COUNT(*) FROM user;
SELECT COUNT(*) FROM api_key WHERE is_active=1;
SELECT COUNT(*) FROM access_log;
SELECT endpoint, COUNT(*) as hits FROM access_log GROUP BY endpoint;

🎯 Best Practices

  1. API Key Management
  • Gunakan API key berbeda untuk setiap aplikasi
  • Nama API key yang descriptive
  • Rotate API key secara berkala
  1. File Organization
  • Gunakan folder struktur yang jelas
  • Contoh: presensi/2025/januari/foto.jpg
  1. Error Handling
  • Selalu check response status
  • Implement retry logic untuk network errors
  • Log semua errors
  1. Security
  • Jangan hardcode API key di source code
  • Gunakan environment variables
  • Implement rate limiting di client side

Built with ❤️ by IndoWeb ID

blog teknologi programming admin

Artikel Terkait