留言板、API篇


Posted by s103071049 on 2021-06-30

什麼是 API

資料 + 顯示畫面(html/css) = 頁面

API 提供的只有資料,所以我拿到資料後再看要如何顯示,再將它顯示出來。

API = 純資料。它是一個資料的溝通。有提供 API 就不需要透過爬蟲去爬它

API 的資料是格式化的資料,JSON 格式,基本上長相和 JS 物件差不多,所以可以方便我們進行 JS 撰寫。

實作無會員機制的留言板 API:列出所有文章

php 裡如何輸出 JSON 格式的資料

comments 是陣列,它有兩個元素,第一個元素是物件,它是 [id] => 1 [content] => apple [username] => 123;第二個元素也是物件,它是 [id] => 2 [content] => boy [username] => 456

<?php
  $comments = array();
  array_push($comments, array(
    "id" => 1,
    "content" => "apple",
    "username" => "123"
  ));
  array_push($comments, array(
    "id" => 2,
    "content" => "boy",
    "username" => "456"
  ));
  print_r($comments);
?>

加上這幾行,它的結構會變得比較難懂,因為 array 裡面又有 array 又有 array。

Array ( [comments] => Array ( [0] => Array ( [id] => 1 [content] => apple [username] => 123 ) [1] => Array ( [id] => 2 [content] => boy [username] => 456 ) ) )

  $json = array(
    "comments" => $comments
  );
  print_r($json)

將內容轉為 json 格式:{"comments":[{"id":1,"content":"apple","username":"123"},{"id":2,"content":"boy","username":"456"}]}

  $response = json_encode($json);
  print_r($response);

加上 header,讓瀏覽器知道我們要印出 json 格式與它的編碼

header('Content-type:application/json;charset=utf-8');

dev-tool => network => 點下檔案 => preview 進行資料結構的檢視

所以,這就是我們要的資料格式。現在,我們可以這樣調整 php 檔案。

有了 $row 就按照上面這樣做。另外可以在網址帶參數 api_comments.php?page=4

抓資料部分,原本在 main.php 抓完資料是直接顯示,這邊我們先將資料放到 comments 的陣列中,在 comments 裡在建立一個陣列。有點像是物件的概念。舉例來說:key id 對應到的是 row id。

<?php
  require_once('conn.php');
  $page = 1;
  if (!empty($_GET['page'])) {
    $page = $_GET['page'];
  }
  $limit = 10;
  $offset = ($page - 1) * $limit;

  $stmt = $conn->prepare(
    'select ' .
      'C.id as id, C.content as content, C.create_at as create_at, ' .
      'U.nickname as nickname, U.username as username ' .
    'from comments as C ' . 
    'left join users as U on C.username = U.username ' .
    'where C.is_deleted is Null ' .
    'order by C.id desc ' .
    'limit ? offset ? '
  );
  $stmt->bind_param('ii', $limit, $offset);
  $result = $stmt->execute();
  if (!$result) {
    die('錯誤訊息 : ' . $conn ->error);
  }
  $result = $stmt->get_result();    

  $comments = array();
  while ($row = $result->fetch_assoc()) {
    array_push($comments, array(
      "id" => $row['id'],
      "username" => $row['username'],
      "nickname" => $row['nickname'],
      "content" => $row['content'],
      "create_at" => $row['create_at']
    ));
  }

  $json = array(
    "comments" => $comments
  );
  $response = json_encode($json);
  header('Content-type:application/json;charset=utf-8');
  print_r($response);
?>
  1. 將 query 貼過來
  2. 將資料放入 comments 中
  3. 產生 json 物件
  4. 設置 header (加上 header 是為了讓瀏覽器知道我們要輸出的是 json 格式,他的編碼是 utf8)

有了這樣的結果,就可以透過前端進行串接。只輸出資料的 api 就長這樣。

實作 API:新增文章

新增留言的 api 一樣回從 post 拿進來,當然也可以實作 SESSION 機制,但會比較麻煩。所以等下示範,會寫死 username。

首先,加上這行

header('Content-type:application/json;charset=utf-8');

原本沒帶 content ,會導回去首頁。現在要回傳一個 json 格式的 response。

做 api 要將結果直接以 json 格式傳回去。

<?php
  require_once('conn.php');
  header('Content-type:application/json;charset=utf-8');

  if (empty($_POST['content'])) {
    $json = array(
      "ok" => false, 
      "message" => "資料不得為空"
    );
    $response = json_encode($json);
    echo $response;
    die();
  }
  $username = $_POST['username'];
  $content = $_POST['content'];
  $sql = 'insert into comments(username, content) values(?, ?)';
  $stmt = $conn->prepare($sql);
  $stmt = bind_param('ss', $username, $content);
  $result->$stmt->execute();

  if (!$result) {
    $json = array(
      "ok"=>false,
      "message"=>$conn->error
    );
    $response = json_encode($json);
    echo $response;
    die();
  }
  $json = array(
    "ok"=>true,
    "message"=>'成功'
  );
  $response = json_encode($json);
  echo $response;
?>

RESTful API 簡介

RESTful 是一種風格,我們設計的 API 網址都不固定。RESTful 制定規則,如果有按照規則走就是 RESTful API。就算不遵守這個規則,也可以做得出 api。

php 要做 RESTful,要調 server 的設定。

Get /comments => 所有留言
POST /comments => 新增留言

Get /comments/:id => 單一留言
Delete /comments/:id => 刪除留言
Patch/Put /comments/:id => 修改留言

comments 在裡面會被當作一個資源。


#API







Related Posts

剛進 Lab 的碩 0

剛進 Lab 的碩 0

[FE302] React 基礎 - hooks 版本:state

[FE302] React 基礎 - hooks 版本:state

Shingling, MinHashing and Common distance measure I

Shingling, MinHashing and Common distance measure I


Comments