RESTful API Slim Framework

Selamat Pagi kawan-kawan, kali ini mau share nih tentang RESTful API menggunakan Slim Framework, kenapa pakai slim framework? sebenernya mau coba-coba aja, oiya disini yang dibahas metode request umum, seperti GET, POST, DELETE dan PUT, yuk ikuti langkah-langkah nya.

Langkah Pertama
Instal slim framework.

Langkah Kedua
Tambahkan Eloquent pada aplikasi dengan composer

composer require illuminate/database "~5.1"

Langkah Ketiga
Siapkan tabel Mahasiswa.

create sruktur tabel sebagai berikut:

CREATE TABLE `mahasiswa` (
`nim` varchar(10) NOT NULL,
`nama_lengkap` varchar(50) NOT NULL,
`tanggal_lahir` date NOT NULL,
`no_hp` varchar(13) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Langkah Keempat
Koneksi kedatabase

'db' => [
            'driver' => 'mysql',
            'host' => 'localhost',
            'database' => 'database',
            'username' => 'user',
            'password' => 'password',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ]

Langkah Kelima
Jangan lupa pada file dependencis

// Service factory for the ORM
$container['db'] = function ($container) {
    $capsule = new \Illuminate\Database\Capsule\Manager;
    $capsule->addConnection($container['settings']['db']);

    $capsule->setAsGlobal();
    $capsule->bootEloquent();

    return $capsule;
};

Langkah Keenam
Buat metode request RESTful API

1. Method GET (menampilkan semua data)

//Method GET
$app->get("/allmahasiswa/", function (Request $request, Response $response){
$sql = "SELECT * FROM mahasiswa";
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
return $response->withJson(["status" => "success", "data" => $result], 200);
});

cek pada RESTClient

Preview

2. Method POST (menambah data)

//Method POST
$app->post("/mahasiswa/", function (Request $request, Response $response){ 
$emp = json_decode($request->getBody()); 
$sql = "INSERT INTO mahasiswa (nim, nama_lengkap) VALUE (:nim, :nama_lengkap)";
$stmt = $this->db->prepare($sql);
$data = [
":nim" => $emp->nim,
":nama_lengkap" => $emp->nama_lengkap 
];
if($stmt->execute($data))
return $response->withJson(["status" => "success", "data" => "1"], 200);

return $response->withJson(["status" => "failed", "data" => "0"], 200);
});

Cek pada RESTClient

Preview

3. Method PUT dan DELETE

//Method PUT
$app->put("/mahasiswa/{id}", function (Request $request, Response $response, $args){
$id = $args["id"];
$emp = json_decode($request->getBody()); 
$sql = "UPDATE mahasiswa SET nama_lengkap=:nama_lengkap WHERE nim=:id";
$stmt = $this->db->prepare($sql);
$data = [
":id" => $id,
":nama_lengkap" => $emp->nama_lengkap
];

if($stmt->execute($data))
return $response->withJson(["status" => "success", "data" => "1"], 200);

return $response->withJson(["status" => "failed", "data" => "0"], 200);
});

//Method DELETE
$app->delete("/mahasiswa/{id}", function (Request $request, Response $response, $args){
$id = $args["id"];
$sql = "DELETE FROM mahasiswa WHERE nim=:id";
$stmt = $this->db->prepare($sql);
$data = [
":id" => $id
];
if($stmt->execute($data))
return $response->withJson(["status" => "success", "data" => "1"], 200);

return $response->withJson(["status" => "failed", "data" => "0"], 200);
});

Cek pada RESTClient dan Preview (PUT & Delete)

Done.

Salam
Okto

References:
https://www.petanikode.com/slim-api/
https://www.phpflow.com/php/create-simple-rest-api-using-slim-framework/

Advertisements

Creating a Restful Web Service in PHP (Method GET)

Kali ini kita akan membuat sebuah webservis dengan bahasa pemograman PHP tanpa Framework, biasanya orang bilang PHP Native. Perlu diketahui perbedaan website dan webservis adalah jika website diakses oleh user/orang via web browser dan respon berupa HTML, maka webservice yaitu dapat diakses oleh program, respon berupa XML atau JSON, dan digunakan untuk berkomunikasi antar system dan platform yang berbeda.

Nah… Webservis yang akan dibuat kali ini yaitu webservis yang dasar-dasarnya saja dengan metode GET. Bagaimana caranya?.. yuk ikuti langkah berikut:

1. Buatlah table contacts sebagai berikut:

CREATE TABLE IF NOT EXISTS `contacts` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `telpnumber_person` varchar(15) NOT NULL,
  `email` varchar(50) NOT NULL,
  `address_person` varchar(50) NOT NULL,
  `motor` int(11) NOT NULL,
  `mobil` int(11) NOT NULL,
  `rumah` int(11) NOT NULL,
  `fact` varchar(200) NOT NULL,
  `message` varchar(50) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL
  ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;
INSERT INTO `contacts` (`id`, `name`, `telpnumber_person`, `email`, `address_person`, `motor`, `mobil`, `rumah`, `fact`, `message`, `created_at`, `updated_at`) VALUES
  (6, 'Gon Freecss', '08777', 'gonfreecss@gmail.com', 'Whale Island', 3, 2, 1, '', '', '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
  (7, 'Killua Zoldyck', '813', 'killuazoldyck@gmail.com', 'Gunung Kukuru', 4, 4, 1, '', '', '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
  (8, 'Leorio Paradinight', '812', 'leorioparadinight@gmail.com', 'Yasmin-Bogor', 1, 2, 2, '', '', '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
  (9, 'Kill Tutut Sawah', '8777', 'killtututsawah@gmail.com', 'Bubulak', 2, 3, 3, '', '', '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
  (10, 'Kentut Ayam', '08777', 'kentutayam@gmail.com', 'Bogor', 3, 3, 4, '', '', '0000-00-00 00:00:00', '0000-00-00 00:00:00');

2. Buatlah file koneksi.php

Script sebagai berikut:

<?php
 $mysqli = new mysqli("localhost", "root", "", "");
  if ($mysqli->connect_errno)
   {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
   }
?>

3. Buatlah file index.php

Script sebagai berikut:

<?php

//koneksi ke database
  include "koneksi.php";

//proses client request(VIA URL)
  header("Content-Type:application/json");

if(!empty($_GET['name'])){
  //Ambil data name dari URL
  $name=$_GET['name'];

//cek ke database
  $res = $mysqli->query("SELECT * FROM contacts WHERE name = '".$name."'");

//cek jika data di temukan di database
  if($res->num_rows>0){

$row= $res->fetch_array();

//tampilkan dalam bentuk array
  $data=array('name contact'=>$row['name'],
  'telp contact'=>$row['telpnumber_person'],
  'email contact'=>$row['email']
  );

//panggil fungsi respon
  deliver_response(200,"Contact Found", $data);
  }

else {
  //panggil fungsi respon
  deliver_response(200,"Contact Not Found", NULL);
  }

}

else{
  //panggil fungsi respon
  deliver_response(400,"Invalid Request", NULL);
  }

//fungsi respon
  function deliver_response($status, $status_message, $data){
  header("HTTP/1.1 $status $status_message");

//array
  $response['status']=$status;
  $response['status_message']=$status_message;
  $response['data']=$data;

$json_response=json_encode($response);
  echo $json_response;
  }

?>

4. Hit URL pada RESTClient
restclient

5. Result JSON

{
  "status": 200,
  "status_message": "Contact Found",
  "data":
  {
   "name contact": "Gon Freecss",
   "telp contact": "08777",
   "email contact": "gonfreecss@gmail.com"
   }
}

6. Done 😀

Terimakasih
Sumber:https://www.youtube.com/watch?v=5eWC-lf1FxM
Regards,

Okto Alhamda Putra