详解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="test@test";
$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())];
});
php实例代码详解});
分别创建BaseController.php和UsersController.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有
新增⼀个⽤户
读取所有⽤户信息
只返回⽤户id为4的信息
获取access_token
利⽤token值获得时间,token值正确才能返回正确值
打开PostMan
以上就是详解Laravel制作API接⼝的详细内容,更多关于Laravel制作API接⼝的资料请关注其它相关⽂章!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论