Struktur API Modern

Dipublikasikan: 12 Januari 2025 • Kategori: Tools • Penulis: Jumanto

API modern tidak lagi dibuat dalam satu file besar seperti api.php. Struktur harus dipisah menjadi folder endpoint, controller, middleware, dan service agar mudah dikembangkan, scalable, dan aman.

1. Struktur Folder API Modern


api/
  index.php
  routes/
    auth.php
    user.php
  controllers/
    AuthController.php
    UserController.php
  middleware/
    AuthMiddleware.php
    ApiKeyMiddleware.php
  helpers/
    Response.php
  config/
    database.php
    env.php

2. Routing Terpisah


// routes/user.php
$router->get("/user/profile", "UserController@profile");
$router->post("/user/update", "UserController@update");

3. Controller untuk Logika Bisnis


// controllers/UserController.php
class UserController {
  public function profile() {
    return Response::json(["name" => "Jumanto"]);
  }
}

4. Middleware untuk Keamanan

Middleware adalah filter sebelum request masuk ke controller.


// middleware/AuthMiddleware.php
class AuthMiddleware {
  public static function handle() {
    $token = $_SERVER["HTTP_AUTH"];
    if (!$token) {
      Response::unauthorized("Token diperlukan");
      exit;
    }
  }
}

5. Respon Standar JSON


// helpers/Response.php
class Response {
  public static function json($data) {
    echo json_encode(["success" => true, "data" => $data]);
  }
}

6. Keuntungan Struktur API Modern

Dengan struktur modern ini, API Anda menjadi lebih profesional, mudah diperluas, dan aman untuk kebutuhan aplikasi mobile, web, atau sistem bisnis UMKM.

← Kembali ke Blog