REST
REST (REpresentational State Transfer)
2020/04/20
2021/04/15 (增加連結)
2024/04/13 (增加範例)
基本概念
REST (REpresentational State Transfer)是提供web services的一種方法,REST利用HTTP的POST,GET , PUT / PATCH, DELETE以及JSON來進行CRUD (詳參: Representational state transfer)。一個Restful(符合REST)的服務,通常包括三個部分:
一個URI,例如 http://api.example.com/items
標準的HTTP方法(如:GET, POST, PUT, PATCH 及 DELETE)
定義資料傳輸的格式,通常使用JSON
例如
獲取商品資料 http://api.example.com/items (method:GET) 回傳:
[{"id":1,"name" :"Ben", "age":50}, {"id":2, "name":"Mary", "age":40}, {"id":3, "name", "Tom", "age":20}]
獲取編號1的商品資料 http://api.example.com/items/1 (method:GET) 回傳:
{"id":1,"name" :"Ben", "age":50}
新增商品資料 http://api.example.com/items/ (method:POST),並送出
{"id":4,"name" :"Tony", "age":12}
更新商品資料特定欄位內容 http://api.example.com/items/1 (method:PATCH) ,並送出
{"name" :"Steve"}
更新商品資料內容 http://api.example.com/items/1 (method:PUT),並送出
{"id":1,"name" :"Steve", "age":40}
刪除商品資料 http://api.example.com/items/1 (method:DELETE)
不使用框架的範例
How To Create A Simple REST API in PHP? Step By Step Guide!
這是個相當完整的範例,但這個範例只符合部分的REST規範:
以JSON格式回傳資料給前端
// show products data in json format
echo json_encode($products_arr);
以JSON格式取得資料
// get posted data
$data = json_decode(file_get_contents("php://input"));
加了必要的header來避免CORS
header("Access-Control-Allow-Origin: *");
讀取與新增分別使用了GET與POST,但卻對應不同的URI
讀取
http://localhost/api/product/read.php
新增
http://localhost/api/product/create.php
讀取特定一筆資料雖然是採用GET,但是,產品編號是以parameter的方式傳遞,並非獨立URI
http://localhost/api/product/read_one.php?id=60
更新並不是利用PATCH或PUT,而是使用POST,也對應不同的URI
更新並不是利用DELETE,而是使用POST,也對應不同的URI
原因是PHP本身除了JSON之外,並不直接支援REST的其他規範
Build a Simple REST API in PHP
為了符合規範,這個範例利用index.php,透過parse_url以及explode來處理URI
<?php
require "../bootstrap.php";
use Src\Controller\PersonController;
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: OPTIONS,GET,POST,PUT,DELETE");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri = explode( '/', $uri );
// all of our endpoints start with /person
// everything else results in a 404 Not Found
if ($uri[1] !== 'person') {
header("HTTP/1.1 404 Not Found");
exit();
}
// the user id is, of course, optional and must be a number:
$userId = null;
if (isset($uri[2])) {
$userId = (int) $uri[2];
}
$requestMethod = $_SERVER["REQUEST_METHOD"];
// pass the request method and user ID to the PersonController and process the HTTP request:
$controller = new PersonController($dbConnection, $requestMethod, $userId);
$controller->processRequest();
當我們的API很簡單的時候,這樣寫當然沒問題,但是,當API很多的時候,index.php就變得很複雜了,所以,通常我們會借用PHP的框架來簡化我們的程式,要記得,其實背後運作原理是一樣的。
這個範例不一樣的地方在於利用.htaccess進行url的rewrite
RewriteEngine On
RewriteBase /api
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php [QSA,L]
使用框架的介紹
5 Popular PHP REST API Frameworks
這篇文章介紹五個框架,基本上大部分的框架都支援REST
Laravel (a full-stack framework)
Symfony (a full-stack framework)
Slim (a lightweight micro-framework)
Lumen (a micro-framework based on Laravel that is designed specifically for building APIs and microservices)
Phalcon 用C開發,所以,速度最快
Laravel 5
Guzzle
Leaf PHP
Slim
Lumen