小白的邊學邊寫,一個基於laravel的APP接口【API】(一)

前期準備

原文地址
前言,爲何作以及要作個啥
本人姓小名白,徹徹底底編程屆小白一名,可是自從大一那會兒接觸到編程這件奇妙的事情,就完徹底全的陷入的程序的世界。
這不,最近又開始折騰APP了,話說如今開發一款APP真是容易,只用JavaScript和一點點HTML+css技術就能夠完成。可是作APP的後臺就不同了。開發了APP,想讓讀點數據進去,那咱們就要去開發個後臺了。
laravel框架,是我最喜歡的PHP框架了,沒有之一。去年就曾經用laravel寫了個人我的網站但粗糙程度讓我十分臉紅,好了不扯了,讓咱們直接進入主題——先安裝laravel吧!php

基礎環境配置

具體的步驟直接看文檔吧laravel5.2安裝
我本身的環境是win10上面安裝了wampsrver2.5,可是這裏值得好好注意一下,用wampsrver2.5了話,這幾個地方要改動一下。關於這個請看個人筆記
工具:sublime
瀏覽器:chrome(要用到的插件postmancss

關於API

API(Application Programming Interface,應用程序編程接口)是一些預先定義的函數,目的是提供應用程序與開發人員基於某軟件或硬件得以訪問一組例程的能力,而又無需訪問源碼,或理解內部工做機制的細節。
須要注意的是:API有它的具體用途,咱們應該清楚它是幹啥的。訪問API的時候應該輸入什麼。訪問過API事後應該獲得什麼。html

在開始設計API時,咱們應該注意這8點

這裏的內容摘抄自大神的博客
後續的開發計劃就圍繞着這個進行了。(真心好棒的總結)laravel

1.Restful設計原則
2.API的命名
3.API的安全性
4.API返回數據
5.圖片的處理
6.返回的提示信息
7.在線API測試文檔
8.在app啓動時,調用一個初始化API獲取必要的信息

用laravel開發API

就在我上愁着要不要從零開始學習的時候,找到了這個插件dingo/api那麼如今就來安裝吧!
首先必定是下載的沒錯
在新安裝好的laravel的composer.json加入以下內容git

"require": {
    "php": ">=5.5.9",
    "laravel/framework": "5.2.*",
    "dingo/api": "1.0.*dev",
    "lucadegasperi/oauth2-server-laravel": "5.1.*"
},

而後打開cmd執行github

composer update

config/app.php中的providers裏添加web

App\Providers\OAuthServiceProvider::class,
Dingo\Api\Provider\LaravelServiceProvider::class,
LucaDegasperi\OAuth2Server\Storage\FluentStorageServiceProvider::class,
LucaDegasperi\OAuth2Server\OAuth2ServerServiceProvider::class,

aliases裏添加chrome

'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

修改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="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())];
    });
});

分別建立BaseController.phpUsersController.php內容以下

//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);
        // 數組形式
        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,
          ];

          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

clipboard.png


clipboard.png


clipboard.png


clipboard.png


以上的全部內容不少是來自於其餘大牛的博客,很是的感謝dingo/apiLaravel 5 token based Authentication (OAuth 2.0)phphub的文章

相關文章
相關標籤/搜索