5182015, ‘Tuterial Phalcon 3: Membuat REST AP Sederhana- @itedy_ns
@fredy_ns
Tutorial Phalcon 3 : Membuat RESTful API
Sederhana
Dalam tutorial Phalcon ini, kami akan menjelaskan cara membuat aplikasi sederhana
yang menyediakan RESTful API menggunakan metode HTTP yang berbeda:
# GET untuk mengambil dan mencari data
# POST untuk menambahkan data
# PUT untuk memperbarui data
# DELETE untuk menghapus data
Mendefinisikan API 9
API terdiri dari metode berikut ini:
METODE URL TINDAKAN
GET _Apitrobot Mengambil semua data dari tabel robot
GET —_Apiitobot/searchiAstro Pencarian untuk robot dengan nama ‘Astro!
GET —_Apitrobots/2 Mengambil robot berdasarkan primary key
POST —/Apitrobot Menambahkan sebuah robot baru
PUT —_IApilrobots/2 Update robot berdasarkan primary key
DELETE /Apitrobots/2 Menghapus robot berdasarkan primary key
Membuat Aplikasi 4
Karena aplikasi ini begitu sederhana, kita tidak perlu mengimplementasikan MVC
sepenuhnya dalam pengembangan. Dalam hal ini, kita akan menggunakan aplikasi
mikro untuk mencapai tujuan kita.
ipstredyns.netblog2014/057utrial-phalcon-3:membuat estl-oi-sederhanal am5182015
‘Struktur
e1
2
3
4
es
‘Tuttial Phalcon3: Memtuat RESTIU API Sadertana- @itedy_ ns
Berkas berikut ini lebih dari cukup:
my-rest-api/
models/
Robots. php
index.php
. htaccess
Pertama, kita perlu file .htaccess yang berisi semua aturan untuk rewrite URI ke file
index.php, yaitu aplikasi kita:
e1
e2
3
4
es
Kemudiat
e1
e2
3
04
es
e6
e7
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule *(.*)$ index.php?_url=/$"#5., 1]
in, dalam file index.php kita membuat hal-hal berikut:
handle() ;
Sekarang kita akan membuat rute seperti yang telah didefinisikan di atas:
e1
e2
3
4
es
6
e7
es
e9
10
11
12
13
14
15
16
get('/api/robots', function() {
ys
//Searches for robots with $name in their name
$app->get('/api/robots/search/{name}', function($name) {
Ys
//Retrieves robots based on primary key
$app->get(‘/api/robots/{id:[0-9]+}", function($id) {
7
hnipsredyns.neflog'201406tutril-phalcon-3-memiuat-restu-ap-sederhanal amtsns2016 “Tutorial Pracon 3: Membuat RESTI API Sedethana- @tedy_ ns
18] 3)5
19
20] //Adds a new robot
21] $app->post('/api/robots', function() {
22
23) })5
24
25 | //Updates robots based on primary key
26 | $app->put('/api/robots/{id:[@-9]+}', function() {
27
28) 3)5
29
3@| //Deletes robots based on primary key
31] $app->delete('/api/robots/{id:[@-9]+}', function() {
32
33) 3)5
34
35 | $app->handle();
Setiap route didefinisikan dengan metode bernama yang sama dgn metode HTTP,
parameter pertama kita isikan pola route, dilkuti oleh handler. Dalam kasus ini, handler
adalah fungsi anonim. Route sebagai berikut: ‘/api/robot/{id:[0-9}+), sebagai contoh,
secara eksplisit menetapkan bahwa format parameter “id” harus numerik.
Ketika route yang ditetapkan sesuai dengan URI yang diminta maka aplikasi
mengeksekusi handler yang sesuai
Membuat Model 9
API menyediakan informasi tentang ‘robot’, data ini disimpan dalam database. Model
berikut ini memungkinkan kita untuk mengakses tabel yang dalam cara berorientasi
objek. Kita telah menerapkan beberapa bussiness rule dengan menggunakan built-in
validator dan aturan validasi sederhana. Melakukan hal ini akan member kita ketenangan
pikiran dimana data yg disimpan telah memenuhi persyaratan aplikasi kita
e1| validate(new InclusionIn(
array(
"field" => "type",
"domain" => array("droid", "mechanical", "virtual":
)
3
//Robot name must be unique
$this->validate(new Uniqueness(
array(
“field” "name" ,
“message” => "The robot name must be unique"
)
3
//Near cannot be less than zero
if ($this->year < 8) {
$this->appendMessage(new Message("The year cannot be lc
}
//Check if any messages have been produced
if ($this->validationHasFailed() == true) {
return false;
}
ii ]
Sekarang, kita harus mengatur koneksi yang akan digunakan oleh model ini dan
memuatnya dalam aplikasi kami:
e1
e2
3
e4
es
6
e7
es
e9
10
11
12
13
14
15
16
17
18
19
28
21
22
registerDirs (array(
_DIR__ . '/models/*
))->register();
$di = new \Phalcon\DI\FactoryDefault() ;
//Set up the database service
$di->set('db', function(){
return new \Phalcon\Db\Adapter\Pdo\Mysql (array(
"host" => “localhost”
“username” => “asimov”,
“password” => "zeroth",
"dbname" ‘obotics”
5
v5
//Create and bind the DI to the application
hnipsredyns.neflog'201406tutril-phalcon-3-memiuat-restu-ap-sederhanal ansns2016 “Tutorial Pracon 3: Membuat RESTI API Sedethana- @tedy_ ns
23 | $app = new \Phalcon\Mvc\Micro($di) ;
Mengambil data 4
Yang pertama “handler” yang kita akan terapkan yaitu metode GET
untuk memberikan semua data robot yang tersedia. Mari kita gunakan PHQL untuk
melakukan query sederhana ini mengembalikan hasil sebagai JSON
e1| get('/api/robots', function() use ($app) {
es
@6 $phql ELECT * FROM Robots ORDER BY name"
e7 $robots = $app->modelsManager->executeQuery($phq1) ;
@8
@9 $data = array();
10 foreach ($robots as $robot) {
11 $data[] = array(
12 ‘id" $robot->id,
13 ‘name’ => $robot->name,
14 )s
15 }
16
17 echo json_encode($data);
18] })5
PHQL , memungkinkan kita untuk menulis query menggunakan tingkat-tinggi, dialek SQL
object-oriented yang diterjemahkan secara internal ke pernyataan SQL yang tepat
tergantung pada sistem database yang digunakan. Klausul “use” dalam fungsi anonim
akan memberikan akses variabel globel selayaknya variabel local.
Handler pencarian berdasarkan nama akan terlihat seperti berikut:
e1| get('/api/robots/search/{name}", function($name) use ($app) +
es
06 $phql = "SELECT * FROM Robots WHERE name LIKE :name: ORDER BY 1
@7 $robots = $app->modelsManager->executeQuery($phql, array(
08 ‘name ‘% . $name.
eo d)3
10
11 $data = array();
12 foreach ($robots as $robot) {
13 $data[] = array(
hnipsredyns.neflog'201406tutril-phalcon-3-memiuat-restu-ap-sederhanal sit5182015
14
15
16
17
18
19
20
21
“Tutatial Phalcon 3: Membuat RESTI AP Sedertana- @tedy_rs
‘id’ => $robot->id,
‘name’ => $robot->name,
3
+
echo json_encode($data) ;
v5
i J
Mencari berdasarkan kolom “id” caranya mirip, dalam hal ini, kita juga memberitahukan
jika robot itu ditemukan atau tidak:
e1
3
4
e6
e7
es
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
get('/api/robots/{id:[9-9]+}', function($id) use ($app) {
$phql ELECT * FROM Robots WHERE id = :id:"5
$robot = $app->modelsManager->executeQuery($phql, array(
‘id’ => $id
))->getFirst();
//Create a response
$response = new Phalcon\Http\Response();
if ($robot == false) {
$response->setJsonContent(array('status' => 'NOT-FOUND'))5
} else {
$response->setJsonContent (array(
‘status’ => 'FOUND',
‘data’ => array(
‘id’ => $robot->id,
‘name’ => $robot->name
)
5
}
return $response;
Ys
Menambah Data 97
Mengambil data sebagai string JSON yg disertakan pada request, kita juga menggunakan
PHAL untuk insert data:
e1
e2
3
post('/api/robots', function() use ($app) {
$robot = $app->request->getJsonRawBody();
$phql = "INSERT INTO Robots (name, type, year) VALUES (:name:,
$status = $app->modelsManager->executeQuery($phql, array(
‘name’ => $robot->name,
$robot ->type,
$robot ->year
//Create a response
$response = new Phalcon\Http\Response() ;
//Check if the insertion was successful
if ($status->success() == true) {
//Change the HTTP status
$response->setStatusCode(2@1, "Created");
$robot->id = $status->getModel()->id;
$response->setJsonContent(array('status' => 'OK', ‘data’ =:
} else {
//Change the HTTP status
$response->setStatusCode(409, "Conflict");
//Send errors to the client
$errors = array();
foreach ($status->getMessages() as $message) {
$errors[] = $message->getMessage();
}
$response->setJsonContent(array('status’ => ‘ERROR’, ‘mess:
}
return $response;
Ys
i
Memperbarui Data 4
Update data mirip dengan penyisipan.'id” dikirimkan sebagai parameter yg menunjukan
data robot mana yg diperbaharui:
e1
e2
3
e4
@5
put('/api/robots/{id:[0-9]+}", function($id) use($app) {
hnipsredyns.neflog'201406tutril-phalcon-3-memiuat-restu-ap-sederhanal ™5182015 ‘Tuttial Phalcon3: Memtuat RESTIU API Sadertana- @itedy_ ns
6 $robot = $app->request->getJsonRawBody();
@7
@8 $phql = "UPDATE Robots SET name = :name:, type = :type:, year =
29 $status = $app->modelsManager->executeQuery($phql, array(
10 ‘id’ => $id,
11 "name" $robot->name,
12 ‘type’ => $robot->type,
13 ‘year’ => $robot->year
14 d)3
15
16 //Create a response
17 $response = new Phalcon\Http\Response() ;
18
19 //Check if the insertion was successful
20 if ($status->success() == true) {
21 $response->setJsonContent(array('status’ => 'OK'));
22 } else {
23
24 //Change the HTTP status
25 $response->setStatusCode(489, "Conflict");
26
27 $errors = array();
28 foreach ($status->getMessages() as $message) {
29 $errors[] = $message->getMessage();
30 }
31
32 $response->setJsonContent(array('status' => 'ERROR', ‘mess:
33 }
34
35 return $response;
36] })5
|
Menghapus Data 4
Menghapus data caranya jg sama. “id” dikirimkan untuk mengetahui data robot mana yg
dihapus:
e1| delete('/api/robots/{id:[0-9]+}', function($id) use ($app) {
5
@6 $phql = "DELETE FROM Robots WHERE id = :id
e7 $status = $app->modelsManager->executeQuery($phql, array(
e8 ‘id’ => $id
eo d)3
10
11 //Create a response
12 $response = new Phalcon\Http\Response();
23
14 if ($status->success() == true) {
15 $response->setJsonContent(array('status’ => 'OK'));
hnipsredyns.neflog'201406tutril-phalcon-3-memiuat-restu-ap-sederhanal ant5182015 ‘Tuttial Phalcon3: Memtuat RESTIU API Sadertana- @itedy_ ns
16 } else {
17
18 //Change the HTTP status
19 $response->setStatusCode(489, "Conflict");
20
21 $errors = array();
22 foreach ($status->getMessages() as $message) {
23 $errors[] = $message->getMessage();
24 }
25
26 $response->setJsonContent(array('status' => 'ERROR', ‘mess:
27
28 }
29
30 return $response;
31] })5
a i
Menguji Aplikasi 4
Menggunakan curl, kita akan menguji setiap route dalam aplikasi kita, memverifikasi
apakah operasi sudah tepat:
Mendapatkan semua robot:
1] curl -i -x GET http://localhost/my-rest-api/api/robots
@3 | HTTP/1.1 200 OK
@4] Date: Wed, 12 Sep 2012 07:05:13 GMT
@5| Server: Apache/2.2.22 (Unix) DAV/2
@6 | Content-Length: 117
@7| Content-Type: text/html; charset=UTF-8
Robotina"}, {"id
e9| [{"id
SSS
Cari robot berdasarkan nama:
‘Astro Boy"},{"id":'
1] curl -i -x GET http://localhost/my-rest-api/api/robots/search/Astr«
@2
3 HTTP/1.1 208 OK
04 Date: Wed, 12 Sep 2012 07:09:23 GMT
@5 | Server: Apache/2.2.22 (Unix) DAV/2
@6 | Content-Length: 31
@7| Content-Type: text/html; charset-UTF-8
08
eo] [¢"id
»"name":"Astro Boy"}]
a i ]
hnipsredyns.neflog'201406tutril-phalcon-3-memiuat-restu-ap-sederhanal ont5182015 ‘Tuttial Phalcon3: Memtuat RESTIU API Sadertana- @itedy_ ns
Mendapatkan robot berdasarkan |D-nya:
@1| curl -i -x GET http://localhost/my-rest-api/api/robots/3
@2
@3 | HTTP/1.1 200 OK
@4| Date: Wed, 12 Sep 2012 07:12:18 GMT
@5| Server: Apache/2.2.22 (Unix) DAV/2
@6 | Content-Length: 56
@7| Content-Type: text/html; charset=UTF-8
08
e9| {"status":"FOUND", "data": {"id":"3", "name":"Terminator"}}
Masukkan robot baru:
@1| curl -i -x POST -d '{"name":"C-3P0","type": "droid", "year":1977}"
@2
@3 | http://localhost/my-rest-api/api/robots
04
@5 | HTTP/1.1 21 Created
@6 | Date: Wed, 12 Sep 2012 07:15:09 GMT
@7| Server: Apache/2.2.22 (Unix) DAV/2
@8 | Content-Length: 75
@9| Content-Type: text/html; charset-UTF-8
10
11] {"status":"0K", "data"
C-3P0","type":"droid", "year":1977,":
a i ]
Cobalah untuk memasukkan robot baru dengan nama robot yang sudah ada:
@1| curl -i -x POST -d '{"name":"C-3P0","type": "droid", "year":1977}"
@2
@3 | http://localhost/my-rest-api/api/robots
04
@5 | HTTP/1.1 409 Conflict
@6| Date: Wed, 12 Sep 2012 07:18:28 GMT
@7| Server: Apache/2.2.22 (Unix) DAV/2
@8 | Content-Length: 63
@9 | Content-Type: text/html; charset=UTF-8
10
11] {"statu
ERROR"
“The robot name must be uniqu
Atau memperbarui robot dengan jenis yang tidak diketahui:
@1| curl -i -x PUT -d '{"name":
@2
@3 | http://localhost/my-rest-api/api/robots/4
‘ASIMO", “type”: "humanoid", "year" :2000}"
hnipsredyns.neflog'201406tutril-phalcon-3-memiuat-restu-ap-sederhanal son5192015, ‘Tuttal Phalcon3: Memtuat RESTIU API Saderhana- @itedy_ ns
ea
@5 | HTTP/1.1 409 Conflict
@6 | Date: Wed, 12 Sep 2012 08:48:01 GMT
@7| Server: Apache/2.2.22 (Unix) DAV/2
@8 | Content-Length: 104
@9 | Content-Type: text/html; charset=UTF-8
10
11] {"status":"ERROR", "messages": ["Value of field ‘type’ must be part «
12 list: droid, mechanical, virtual"]}
cat m,
Akhimya, menghapus robot:
@1| curl -i -X DELETE http://localhost/my-rest-api/api/robots/4
2
@3 | HTTP/1.1 200 OK
@4| Date: Wed, 12 Sep 2012 08:49:29 GMT
@5| Server: Apache/2.2.22 (Unix) DAV/2
@6 | Content-Length: 15
@7| Content-Type: text/html; charset=UTF-8
8
@9} {"status":"0K"}
Kesimpulan 4
Sebagaimana telah kita lihat, mengembangkan RESTful API dengan Phalcon sangatlah
mudah. Kemudian dalam dokumentasi kami akan menjelaskan secara rinci bagaimana
menggunakan aplikasi mikro dan bahasa PHQL .
Terjemahan dari Tutorial Phalcon 3 : Membuat RESTful API Sederhana
http://docs,phalconphp.com/en/latest/reference/tutorial-rest.htm|
Share this:
Twoot (0
Share 1 fo Email Print
This entry was posted in PhalconPHP and tagged Bahasa Indonesia, Phalcon, PhalconPHP, Tutorial on
26 May 2014 [http://fredyns.net/blog/2014/05/tutorial-phalcon-3-membuat-restful-api-sederhana/] .
hnipsredyns.neflog7201406tutril-phalcon-3-memiuat-restu-ap-sederhnal wm