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)的服務,通常包括三個部分:

例如

 [{"id":1,"name" :"Ben", "age":50}, {"id":2, "name":"Mary", "age":40}, {"id":3, "name", "Tom", "age":20}]

 {"id":1,"name" :"Ben", "age":50}

{"id":4,"name" :"Tony", "age":12}

{"name" :"Steve"}

{"id":1,"name" :"Steve", "age":40}

不使用框架的範例

    // show products data in json format

    echo json_encode($products_arr);

    // get posted data

    $data = json_decode(file_get_contents("php://input"));

    header("Access-Control-Allow-Origin: *");

    http://localhost/api/product/read.php

    http://localhost/api/product/create.php

    http://localhost/api/product/read_one.php?id=60

<?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();

RewriteEngine On

RewriteBase /api

RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.+)$ index.php [QSA,L]

使用框架的介紹