詳解Laravel制作API接口
需要注意的是:API有它的具體用途,我們應(yīng)該清楚它是干啥的。訪問API的時候應(yīng)該輸入什么。訪問過API過后應(yīng)該得到什么。
在開始設(shè)計API時,我們應(yīng)該注意這8點。后續(xù)的開發(fā)計劃就圍繞著這個進(jìn)行了。
1.Restful設(shè)計原則
2.API的命名
3.API的安全性
4.API返回數(shù)據(jù)
5.圖片的處理
6.返回的提示信息
7.在線API測試文檔
8.在app啟動時,調(diào)用一個初始化API獲取必要的信息
用laravel開發(fā)API
就在我上愁著要不要從零開始學(xué)習(xí)的時候,找到了這個插件dingo/api那么現(xiàn)在就來安裝吧!
首先一定是下載的沒錯
在新安裝好的laravel的composer.json加入如下內(nèi)容
然后打開cmd執(zhí)行
composer update
在config/app.php中的providers里添加
App\Providers\OAuthServiceProvider::class,
Dingo\Api\Provider\LaravelServiceProvider::class,
LucaDegasperi\OAuth2Server\Storage\FluentStorageServiceProvider::class,
LucaDegasperi\OAuth2Server\OAuth2ServerServiceProvider::class,
在aliases里添加
'Authorizer' => LucaDegasperi\OAuth2Server\Facades\Authorizer::class,
修改app/Http/Kernel.php文件里的內(nèi)容
protected $middleware = [\LucaDegasperi\OAuth2Server\Middleware\OAuthExceptionHandlerMiddleware::class, ]; protected $routeMiddleware = [ 'oauth' => \LucaDegasperi\OAuth2Server\Middleware\OAuthMiddleware::class, 'oauth-user' => \LucaDegasperi\OAuth2Server\Middleware\OAuthUserOwnerMiddleware::class, 'oauth-client' => \LucaDegasperi\OAuth2Server\Middleware\OAuthClientOwnerMiddleware::class, 'check-authorization-params' => \LucaDegasperi\OAuth2Server\Middleware\CheckAuthCodeRequestMiddleware::class, 'csrf' => \App\Http\Middleware\VerifyCsrfToken::class, ];
然后執(zhí)行
php artisan vendor:publish
php artisan migrate
在.env文件里添加這些配置
API_STANDARDS_TREE=x
API_SUBTYPE=rest
API_NAME=REST
API_PREFIX=api
API_VERSION=v1
API_CONDITIONAL_REQUEST=true
API_STRICT=false
API_DEBUG=true
API_DEFAULT_FORMAT=json
修改app\config\oauth2.php文件
'grant_types' => [ 'password' => [ 'class' => 'League\OAuth2\Server\Grant\PasswordGrant', 'access_token_ttl' => 604800, 'callback' => '\App\Http\Controllers\Auth\PasswordGrantVerifier@verify', ], ],
新建一個服務(wù)提供者,在app/Providers下新建OAuthServiceProvider.php文件內(nèi)容如下
namespace App\Providers; use Dingo\Api\Auth\Auth; use Dingo\Api\Auth\Provider\OAuth2; use Illuminate\Support\ServiceProvider; class OAuthServiceProvider extends ServiceProvider { public function boot() { $this->app[Auth::class]->extend('oauth', function ($app) { $provider = new OAuth2($app['oauth2-server.authorizer']->getChecker()); $provider->setUserResolver(function ($id) { // Logic to return a user by their ID. }); $provider->setClientResolver(function ($id) { // Logic to return a client by their ID. }); return $provider; }); } public function register() { // } }
然后打開routes.php添加相關(guān)路由
//Get access_token Route::post('oauth/access_token', function() { return Response::json(Authorizer::issueAccessToken()); }); //Create a test user, you don't need this if you already have. Route::get('/register',function(){ $user = new App\User(); $user->name="tester"; $user->email="test@test.com"; $user->password = \Illuminate\Support\Facades\Hash::make("password"); $user->save(); }); $api = app('Dingo\Api\Routing\Router'); //Show user info via restful service. $api->version('v1', ['namespace' => 'App\Http\Controllers'], function ($api) { $api->get('users', 'UsersController@index'); $api->get('users/{id}', 'UsersController@show'); }); //Just a test with auth check. $api->version('v1', ['middleware' => 'api.auth'] , function ($api) { $api->get('time', function () { return ['now' => microtime(), 'date' => date('Y-M-D',time())]; }); });
分別創(chuàng)建BaseController.php和UsersController.php內(nèi)容如下
//BaseController namespace App\Http\Controllers; use Dingo\Api\Routing\Helpers; use Illuminate\Routing\Controller; class BaseController extends Controller { use Helpers; } //UsersController namespace App\Http\Controllers; use App\User; use App\Http\Controllers\Controller; class UsersController extends BaseController { public function index() { return User::all(); } public function show($id) { $user = User::findOrFail($id); // 數(shù)組形式 return $this->response->array($user->toArray()); } }
隨后在app/Http/Controllers/Auth/下創(chuàng)建PasswordGrantVerifier.php內(nèi)容如下
namespace App\Http\Controllers\Auth; use Illuminate\Support\Facades\Auth; class PasswordGrantVerifier { public function verify($username, $password) { $credentials = [ 'email' => $username, 'password' => $password, ]; if (Auth::once($credentials)) { return Auth::user()->id; } return false; } }
打開數(shù)據(jù)庫的oauth_client表新增一條client數(shù)據(jù)
INSERT INTO 'oauth_clients' ('id', 'secret', 'name', 'created_at', 'updated_at') VALUES ('1', '2', 'Main website', '2016–03–13 23:00:00', '0000–00–00 00:00:00');
隨后的就是去愉快的測試了,這里要測試的API有
新增一個用戶
http://localhost/register
讀取所有用戶信息
http://localhost/api/users
只返回用戶id為4的信息
http://localhost/api/users/4
獲取access_token
http://localhost/oauth/access_token
利用token值獲得時間,token值正確才能返回正確值
http://localhost/api/time
打開PostMan
以上就是詳解Laravel制作API接口的詳細(xì)內(nèi)容,更多關(guān)于Laravel制作API接口的資料請關(guān)注腳本之家其它相關(guān)文章!
- Laravel如何實現(xiàn)適合Api的異常處理響應(yīng)格式
- 在 Laravel 中動態(tài)隱藏 API 字段的方法
- Laravel實現(xiàn)ApiToken認(rèn)證請求
- laravel框架 api自定義全局異常處理方法
- laravel dingo API返回自定義錯誤信息的實例
- Laravel框架實現(xiàn)調(diào)用百度翻譯API功能示例
- PHP使Laravel為JSON REST API返回自定義錯誤的問題
- 讓Laravel API永遠(yuǎn)返回JSON格式響應(yīng)的方法示例
- Larave框架通過sanctum進(jìn)行API鑒權(quán)詳解
相關(guān)文章
PHP的Laravel框架中使用AdminLTE模板來編寫網(wǎng)站后臺界面
這篇文章主要介紹了PHP的Laravel框架中使用AdminLTE模板來編寫網(wǎng)站后臺的方法,AdminLTE基于BootStrap,能幫助快速創(chuàng)建網(wǎng)站后臺管理面板界面,需要的朋友可以參考下2016-03-03Laravel框架使用技巧之使用url()全局函數(shù)返回前一個頁面的地址方法詳解
這篇文章主要介紹了Laravel框架使用技巧之使用url()全局函數(shù)返回前一個頁面的地址,需要的朋友可以參考下2020-04-04PHP面向?qū)ο蟪绦蛟O(shè)計OOP繼承用法入門示例
這篇文章主要介紹了PHP面向?qū)ο蟪绦蛟O(shè)計OOP繼承用法,結(jié)合簡單實例形式分析了php類的定義與繼承使用方法,需要的朋友可以參考下2016-12-12php數(shù)組實現(xiàn)根據(jù)某個鍵值將相同鍵值合并生成新二維數(shù)組的方法
這篇文章主要介紹了php數(shù)組實現(xiàn)根據(jù)某個鍵值將相同鍵值合并生成新二維數(shù)組的方法,涉及php數(shù)組的遍歷、賦值相關(guān)運(yùn)算技巧,需要的朋友可以參考下2017-04-04PHP file_get_contents 函數(shù)超時的幾種解決方法
在使用file_get_contents函數(shù)的時候,經(jīng)常會出現(xiàn)超時的情況,在這里要通過查看一下錯誤提示,看看是哪種錯誤,比較常見的是讀取超時,這種情況大家可以通過一些方法來盡量的避免或者解決。2009-07-07