這篇文章主要為大家展示了基于laravel如何制作API接口,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶大家一起來(lái)研究并學(xué)習(xí)一下“基于laravel如何制作API接口”這篇文章吧。
目前成都創(chuàng)新互聯(lián)公司已為上千多家的企業(yè)提供了網(wǎng)站建設(shè)、域名、網(wǎng)站空間、成都網(wǎng)站托管、企業(yè)網(wǎng)站設(shè)計(jì)、蘄春網(wǎng)站維護(hù)等服務(wù),公司將堅(jiān)持客戶(hù)導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶(hù)和合作伙伴齊心協(xié)力一起成長(zhǎng),共同發(fā)展。
Laravel 是一套簡(jiǎn)潔、優(yōu)雅的PHP Web開(kāi)發(fā)框架。它可以讓你從面條一樣雜亂的代碼中解脫出來(lái);它可以幫你構(gòu)建一個(gè)完美的網(wǎng)絡(luò)APP,而且每行代碼都可以簡(jiǎn)潔、富于表達(dá)力。
關(guān)于API
API(Application Programming Interface,應(yīng)用程序編程接口)是一些預(yù)先定義的函數(shù),目的是提供應(yīng)用程序與開(kāi)發(fā)人員基于某軟件或硬件得以訪(fǎng)問(wèn)一組例程的能力,而又無(wú)需訪(fǎng)問(wèn)源碼,或理解內(nèi)部工作機(jī)制的細(xì)節(jié)。
需要注意的是:API有它的具體用途,我們應(yīng)該清楚它是干啥的。訪(fǎng)問(wèn)API的時(shí)候應(yīng)該輸入什么。訪(fǎng)問(wèn)過(guò)API過(guò)后應(yīng)該得到什么。
在開(kāi)始設(shè)計(jì)API時(shí),我們應(yīng)該注意這8點(diǎn)
后續(xù)的開(kāi)發(fā)計(jì)劃就圍繞著這個(gè)進(jìn)行了。
1.Restful設(shè)計(jì)原則
2.API的命名
3.API的安全性
4.API返回?cái)?shù)據(jù)
5.圖片的處理
6.返回的提示信息
7.在線(xiàn)API測(cè)試文檔
8.在app啟動(dòng)時(shí),調(diào)用一個(gè)初始化API獲取必要的信息
用laravel開(kāi)發(fā)API
就在我上愁著要不要從零開(kāi)始學(xué)習(xí)的時(shí)候,找到了這個(gè)插件dingo/api那么現(xiàn)在就來(lái)安裝吧!
首先一定是下載的沒(méi)錯(cuò)
在新安裝好的laravel的composer.json加入如下內(nèi)容
然后打開(kāi)cmd執(zhí)行
composer update
在config/app.php中的providers里添加
App\Providers\OAuthServiceProvider::class, Dingo\Api\Provider\LaravelServiceProvider::class, LucaDegasperi\OAuth3Server\Storage\FluentStorageServiceProvider::class, LucaDegasperi\OAuth3Server\OAuth3ServerServiceProvider::class,
在aliases里添加
'Authorizer' => LucaDegasperi\OAuth3Server\Facades\Authorizer::class,
修改app/Http/Kernel.php文件里的內(nèi)容
protected $middleware = [\LucaDegasperi\OAuth3Server\Middleware\OAuthExceptionHandlerMiddleware::class, ]; protected $routeMiddleware = [ 'oauth' => \LucaDegasperi\OAuth3Server\Middleware\OAuthMiddleware::class, 'oauth-user' => \LucaDegasperi\OAuth3Server\Middleware\OAuthUserOwnerMiddleware::class, 'oauth-client' => \LucaDegasperi\OAuth3Server\Middleware\OAuthClientOwnerMiddleware::class, 'check-authorization-params' => \LucaDegasperi\OAuth3Server\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\oauth3.php文件
'grant_types' => [ 'password' => [ 'class' => 'League\OAuth3\Server\Grant\PasswordGrant', 'access_token_ttl' => 604800, 'callback' => '\App\Http\Controllers\Auth\PasswordGrantVerifier@verify', ], ],
新建一個(gè)服務(wù)提供者,在app/Providers下新建OAuthServiceProvider.php文件內(nèi)容如下
namespace App\Providers; use Dingo\Api\Auth\Auth; use Dingo\Api\Auth\Provider\OAuth3; use Illuminate\Support\ServiceProvider; class OAuthServiceProvider extends ServiceProvider { public function boot() { $this->app[Auth::class]->extend('oauth', function ($app) { $provider = new OAuth3($app['oauth3-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() { // } }
然后打開(kāi)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; } }
打開(kāi)數(shù)據(jù)庫(kù)的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');
隨后的就是去愉快的測(cè)試了,這里要測(cè)試的API有
新增一個(gè)用戶(hù)
http://localhost/register
讀取所有用戶(hù)信息
http://localhost/api/users
只返回用戶(hù)id為4的信息
http://localhost/api/users/4
獲取access_token
http://localhost/oauth/access_token
利用token值獲得時(shí)間,token值正確才能返回正確值
http://localhost/api/time
打開(kāi)PostMan
以上就是關(guān)于“基于laravel如何制作API接口”的內(nèi)容,如果改文章對(duì)你有所幫助并覺(jué)得寫(xiě)得不錯(cuò),勞請(qǐng)分享給你的好友一起學(xué)習(xí)新知識(shí),若想了解更多相關(guān)知識(shí)內(nèi)容,請(qǐng)多多關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。