# laravel API ## 注意事項 你body 那邊可以選json 然後header會自動加上 但返回的並不是json 所以要加上header裡面 加上 Accept json ![](https://i.imgur.com/eIEc1RA.png) ## api request form 设置所有请求和响应都是 json 格式 请注意不要使用 `php artisan make:request BaseRequest`,这会使得你的 BaseRequest 继承 FormRequest,而我们要覆盖的是 `Illuminate\Http\Request`,所以我们应当继承的是 Request。 ## 可以自訂token https://stackoverflow.com/questions/61688072/laravel-what-is-storage-key-in-auth-php ![](https://i.imgur.com/rLotAEX.png) 第一個是input queryString改名稱的作法 第二個是migrate欄位名稱 這是裡面的方法Illuminate/Auth/AuthManager ``` /** * Create a token based authentication guard. * * @param string $name * @param array $config * @return \Illuminate\Auth\TokenGuard */ public function createTokenDriver($name, $config) { // The token guard implements a basic API token based guard implementation // that takes an API token field from the request and matches it to the // user in the database or another persistence layer where users are. $guard = new TokenGuard( $this->createUserProvider($config['provider'] ?? null), $this->app['request'], $config['input_key'] ?? 'api_token', $config['storage_key'] ?? 'api_token' ); $this->app->refresh('request', $guard, 'setRequest'); return $guard; } ``` 它與 處於同一級別provider,從班級中也可以看出它與 處於同一級別driver。您需要將用於身份驗證的選定(例如)之一放入storage_key其中。默認情況下,它們都設置為.input_keyguardsapiapi_token ``` 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'token', 'provider' => 'users', ], ], ``` ## http方法 https://www.youtube.com/watch?v=oEDDZsmMLc0 7之前適用guzzle 7之後guzzle在安裝時就會裝在composer裡面 新版使用 ![](https://i.imgur.com/Yzx1oKR.png) 只要用facads引入http就能用了 ## 查詢參數 上面是linux 下面windos ![](https://i.imgur.com/TTcEeS1.png) ## paginate appends 讓api返回的paginate裡面多一個參數(query string) 因為原本只會說上一頁面下一個面 ?page=1這樣 如果要加上總頁數可以這樣做 ## fluent api https://www.amitmerchant.com/fluent-string-operations-laravel7/ https://www.youtube.com/watch?v=w7QzoOZN2tk 就是一種寫法 ->function -> -> 可以把很多需要參數的改成傳進去 每個都return this返回 原本 ![](https://i.imgur.com/QtX6LSf.png) 外面 ![](https://i.imgur.com/pq2VYkT.png) 裡面 ![](https://i.imgur.com/mDIfZEN.png) ## api 多少都要用Cache ``` use Illuminate\Support\Facades\Http; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Cache; class WeatherController extends Controller { public function __invoke($city) { $coordinates = config('app.cities.'.$city); return Cache::remember('city' . $city, 60 * 5, function() use ($coordinates) { $response = Http::get('https://api.open-meteo.com/vsdfsd1/forecast?latitude='.$coordinates['lat'].'&longitude='.$coordinates['lng'].'&daily=temperature_2m_max,temperature_2m_min&timezone=UTC'); if ($response->successful()) { return $response->json('daily'); } return response()->json([]); }); } } ``` 防止重複送 很常看到可能有原因 ## api版本控制 https://codimth.com/blog/web/laravel/versioning-your-rest-api-laravel 其實就是設立middware 然後加上v1 prefix 在routeService那邊的map api的地方在加上一個middware而已 ## 攜帶token ::withToken ![](https://i.imgur.com/JpX0poi.png) ![](https://i.imgur.com/XRaRVfu.png) ## API文件 https://ithelp.ithome.com.tw/articles/10226634 https://pandalab.org/articles/150 使用 **mpociot/laravel-apidoc-generator** (不支援 laravel8,解決方法在第二個連結) 這是搭配apidoc + Laravel路徑配置 另外寫好的套件,能夠基於 Laravel 路由自動生成專案 API 文件,可以省掉很多麻煩! 也可以使用** apidoc** 官方的套件但就是需要多設定一些路徑! **生成文件** ``` 想對已存在的路由重新再編譯一次的話,可加上 —-force 選項 php artisan apidoc:generate php artisan apidoc:generate --force ``` 打開 http://127.0.0.1:8000/docs/index.html 可看到目前專案內的所有API **開始寫文件** @group 幫API分組 * @bodyParam 請求時須提供的資料,名稱、生日(選填)、顏色... * @queryParam 請求時可附加的參數 排序、篩選...(/api/animals?sort=name:asc) 問候後面的那些參數 * @bodyParam @queryParam 可以而外附上 Example: 關鍵字範例 * @authenticated 該是否需要身份驗證 * @response 返回響應相關。 * @responseFile 如果響應資料太多可以用此關鍵字載入 json 檔案 **手動修改文件內容** 如果在生成文件之後,在沒有更動路由的情況下,你可以手動去修改生成文件的內容,透過編輯 [index.md](http://index.md) 檔案 這個檔案位於你輸出資料夾內的 source 資料夾內,比如 type 設為 laravel 的話就是在 resources/docs/source/index.md 一旦當你編輯完 Markdown 檔案之後,可使用以下命令來重新打造 API 技術文件 `php artisan apidoc:rebuild` ### Swagger 還未開始 ## api 404 後備路線 使用該Route::fallback方法,您可以定義一個路由,當沒有其他路由與傳入請求匹配時將執行該路由。通常,未處理的請求將通過應用程序的異常處理程序自動呈現“404”頁面。但是,由於您通常會fallback在routes/web.php文件中定義路由,因此web中間件組中的所有中間件都將應用於該路由。你可以根據需要自由地向這個路由添加額外的中間件: ``` Route::fallback(function () { // }); ``` 但這樣其實不好的作法 應該用丟錯誤的方法 正確做法 第一 ![](https://i.imgur.com/FegCTur.png) 去異常錯誤那邊寫返回 注意路由那邊也要寫route route那邊要寫respond ## bearerToken 這是5.8 migrate的 https://panjeh.medium.com/laravel-get-bearer-token-from-a-request-b1b242277e22 paasPort的 https://www.youtube.com/watch?v=H3zybw5joyQ ###### tags: `Laravel`