1. 程式人生 > 程式設計 >詳解Laravel製作API介面

詳解Laravel製作API介面

需要注意的是:API有它的具體用途,我們應該清楚它是幹啥的。訪問API的時候應該輸入什麼。訪問過API過後應該得到什麼。

在開始設計API時,我們應該注意這8點。後續的開發計劃就圍繞著這個進行了。

1.Restful設計原則

2.API的命名

3.API的安全性

4.API返回資料

5.圖片的處理

6.返回的提示資訊

7.線上API測試文件

8.在app啟動時,呼叫一個初始化API獲取必要的資訊

用laravel開發API

就在我上愁著要不要從零開始學習的時候,找到了這個外掛dingo/api那麼現在就來安裝吧!

首先一定是下載的沒錯

在新安裝好的laravel的composer.json加入如下內容

然後開啟cmd執行

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檔案裡的內容

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,];

然後執行

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',],

新建一個服務提供者,在app/Providers下新建OAuthServiceProvider.php檔案內容如下

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新增相關路由

//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="[email protected]";
 $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())];
 });
});

分別建立BaseController.php和UsersController.php內容如下

//BaseController
namespace App\Http\Controllers;
   
use Dingo\Api\Routing\Helpers;
use Illuminate\Routing\Controller;
   
class BaseControl程式設計客棧ler extends Controller
{
 use Helpers;
}
   
//UsersController
namespace App\Http\Controllers;
   
use App\User;
use App\Http\Controllers\Controller;
   
class UsersController extends BasEJzFDkeController
{
   
 public function index()
 {
 return User::all();
 }
   
 public function show($id)
 {
 $user = User::findOrFail($id);
 // 陣列形式
 return $this->response->array($user->toArray());
 }
}

隨後在app/Http/Controllers/Auth/下建立PasswordGrantVerifier.php內容如下

namespace App\Http\Controllers\Auth;
use Illuminate\Support\Facades\Auth;
   
class PasswordGrantVerifier
{
 public function verify($username,$password)
 {
 $credentials = [
 'email' => $username,'password' => $password,]http://www.cppcns.com;
   
 if (Auth::once($credentials)) {
 return Auth::user()->id;
 }
   
 return false;
 }
}

開啟資料庫的oauth_client表新增一條client資料

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介面的詳細內容,更多關於Laravel製作API介面的資料請關注我們其它相關文章!