iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 29
2
Modern Web

使用 Laravel 打造 RESTful API系列 第 29

Laravel 自動產生API文件

使用Laravel 8 PHP主流框架打造RESTful API(iT邦幫忙鐵人賽系列書)ISBN:9789864345304

本系列文章已集結成冊與鐵人賽文章差異內容,有以下幾點:

更新至Laravel 8、基礎的PHP重點筆記、加強製作API流程細節、加入程式設計模式,優化、重構程式碼的部分,並且於書籍前面的章節介紹Git。

讓您從製作第一個簡單的API到優化自己的程式碼,分享我的經驗給您,打造自己的最強大腦API,若有興趣的朋友可以參考看看

天瓏網路書局:
https://www.tenlong.com.tw/products/9789864345304


此篇文章同步發於個人部落格

簡介&安裝

我們打造好的API,沒有使用手冊,對於要介接的開發者,根本無法使用,所以必須提供文件給他們!

所以今天就來介紹 mpociot/laravel-apidoc-generator 這是搭配apidoc + Laravel路徑配置 另外寫好的套件,能夠基於 Laravel 路由自動生成專案 API 文件,可以省掉很多麻煩!

也可以使用 apidoc 官方的套件但就是需要多設定一些路徑!

GitHub連結

使用Composer安裝這個套件

composer require --dev mpociot/laravel-apidoc-generator

安裝情形

使用指令發布配置檔案! (配置檔案可以設定很多東西,例如產生API文件的Logo...)

php artisan vendor:publish --provider="Mpociot\ApiDoc\ApiDocGeneratorServiceProvider" --tag=apidoc-config

如下圖產生一個 apidoc.php 檔案在 config 資料夾中!

安裝情形

安裝套件及配置檔案都完成後!開始嘗試產生api文件。

如何使用

先下指令看看

執行下方指令,依照我們撰寫的路由產生API文件!會在public目錄下多一個docs目錄以及相關的檔案!

還記得定義API URI 的 api.php 檔案嗎?我們寫的那些程式,對應到的Controller ,在依照每個 Controller 中的方法上方的註解,產生的API檔案。

php artisan apidoc:generate

結果發生錯誤了~~(是因為升級Laravel 6 不相容嗎?讓我們繼續看下去)

發生錯誤

來去發生錯誤的檔案看看,按住 command (ctrl)+點擊上方紅框 發現錯誤地點如下圖! (我使用VScode編輯器,好像現在的編輯器都有這樣的功能,那個路徑應該會出現底線)

發生錯誤2

推測 config 快取未更新 下指令讓他清除 config 快取吧!

php artisan config:clear

在下產生API文件的指令

php artisan apidoc:generate

成功產生檔案

打開 http://127.0.0.1:8000/docs/index.html

API文件畫面

看到左邊的general 分類已經有一排東西!這就是目前專案內的所有API。

開始寫文件

可以注意到文件畫面的又半部深色區域,還會幫我們請求 API 並顯示出 Response 結果,如果需要權限的內容皆顯示

{
    "message": "Unauthenticated."
}

介紹註解關鍵字

@group 幫API分組

@bodyParam 請求時須提供的資料,名稱、生日(選填)、顏色...
@queryParam 請求時可附加的參數 排序、篩選...(/api/animals?sort=name:asc) 問候後面的那些參數

@bodyParam @queryParam 可以而外附上 Example: 關鍵字範例

@authenticated 該是否需要身份驗證

@response 返回響應相關。

@responseFile 如果響應資料太多可以用此關鍵字載入 json 檔案

直接附上寫好註解的 AnimalConteoller

<?php

namespace App\Http\Controllers\Api;

use App\Animal;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Http\Resources\AnimalResource;
use Auth;
use App\Http\Requests\StoreAnimalRequest;
use App\Services\AnimalService;
use App\Http\Controllers\Controller;

/**
 * @group 動物資源
 * 
 * 動物的所有操作
 */
class AnimalController extends Controller
{
    private $animalService;

    public function __construct(AnimalService $animalService)
    {
        $this->animalService = $animalService;
        $this->middleware('auth:api', ['except' => ['index','show']]);
    }

    /**
     * Show Animal List
     * 
     * @queryParam marker 標記由哪個資源開始查詢(預設ID:1) Example: 1
     * @queryParam limit  設定回傳資料筆數(預設10筆資料) Example: 10
     * @queryParam sort   設定排序方式 Example: name:asc
     * 
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        // 設定預設值

        $marker = isset($request->marker) ? $request->marker : 1;
        $limit = isset($request->limit) ? $request->limit : 10;

        $query = Animal::query();

        $query = $this->animalService->filterAnimals($request->filters, $query);
        
        $query = $this->animalService->sortAnimals($request->sort, $query);

        $animals = $query->where('id', '>=', $marker)->paginate($limit);

        return response($animals, Response::HTTP_OK);
    }

    /**
     * Store Animal
     * 
     * @authenticated
     * 
     * @bodyParam type_id Int required 動物的分類ID(需參照types資料表) Example: 1
     * @bodyParam name String required 動物名稱 Example: 黑熊
     * @bodyParam birthday date required 生日 Example: 2019-10-10
     * @bodyParam area String required 所在區域 Example: 台北市
     * @bodyParam fix boolean required 是否結紮 Example: true
     * @bodyParam description text 簡易描述 Example: 黑狗,胸前有白毛!宛如台灣黑熊
     * @bodyParam personality text 其他介紹 Example: 非常親人!很可愛~
     * 
     * 
     * @param  App\Http\Requests\StoreAnimalRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreAnimalRequest $request)
    {
        $animal = Animal::create($request->all());
        return response($animal, Response::HTTP_CREATED);
    }

    /**
     * Show Animal
     *
     * @param  \App\Animal  $animal
     * @return \Illuminate\Http\Response
     */
    public function show(Animal $animal)
    {
        return response(new AnimalResource($animal), Response::HTTP_OK);
    }

    /**
     * Update Animal
     * 
     * @bodyParam type_id Int required 動物的分類ID(需參照types資料表) Example: 1
     * @bodyParam name String required 動物名稱 Example: 黑熊
     * @bodyParam birthday date required 生日 Example: 2019-10-10
     * @bodyParam area String required 所在區域 Example: 台北市
     * @bodyParam fix boolean required 是否結紮 Example: true
     * @bodyParam description text 簡易描述 Example: 黑狗,胸前有白毛!宛如台灣黑熊
     * @bodyParam personality text 其他介紹 Example: 非常親人!很可愛~
     * 
     * @authenticated
     * 
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Animal  $animal
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Animal $animal)
    {
        $animal->update($request->all());
        return response($animal, Response::HTTP_OK);
    }

    /**
     * Delete Animal
     *`
     * @authenticated
     * 
     * @param  \App\Animal  $animal
     * @return \Illuminate\Http\Response
     */
    public function destroy(Animal $animal)
    {
        $animal->delete();
        return response(null, Response::HTTP_NO_CONTENT);
    }

    /**
     * Like/Unlike Animal
     *
     * @authenticated
     * 
     * @param  \App\Animal  $animal
     * @return \Illuminate\Http\Response
     */
    public function like(Animal $animal)
    {
        $animal->like()->toggle(Auth::user()->id);

        return response(null, Response::HTTP_NO_CONTENT);
    }

}

功能很簡單,給上對應的關鍵字就可以囉!但好像沒有比 apidoc 設定來的自由,想要查詢其他關鍵字請參考 laravel-apidoc-generator 官方文件 https://laravel-apidoc-generator.readthedocs.io/en/latest/index.html

記得有修改註解都要下指令產生文件喔!


上一篇
更好的自己更好的 API - 如何安心升級 Laravel6
下一篇
Laravel RESTful API 送養系統 完賽結語
系列文
使用 Laravel 打造 RESTful API30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言