Bài 01: Tìm hiều API - Laravel

Bài 01: Tìm hiều API - Laravel

 

Hiện nay API nói chung và Web API nói riêng đang được ứng dụng ngày càng nhiều. Kiến trúc ứng dụng hiện đại ngày nay ngày càng phân tán, không phụ thuộc ngôn ngữ đã thúc đẩy việc ứng dụng API. Vậy API là gì? Nguồn gốc và ưu điểm của nó là như thế nào? 

1/ API là gì?

-     API là các phương thức, giao thức kết nối với các thư viện và ứng dụng khác. Nó là viết tắt của Application Programming Interface – giao diện lập trình ứng dụng. API cung cấp khả năng cung cấp khả năng truy xuất đến một tập các hàm hay dùng. Và từ đó có thể trao đổi dữ liệu giữa các ứng dụng. 

2/API thường ứng dụng vào đâu? 

-    Web API: là hệ thống API được sử dụng trong các hệ thống website. Hầu hết các website đều ứng dụng đến Web API cho phép bạn kết nối, lấy dữ liệu hoặc cập nhật cơ sở dữ liệu. Ví dụ: Bạn thiết kế chức nằng login thông Google, Facebook, Twitter, Github… Điều này có nghĩa là bạn đang gọi đến API của. Hoặc như các ứng dụng di động đều lấy dữ liệu thông qua API. API trên hệ điều hành: Windows hay Linux có rất nhiều API, họ cung cấp các tài liệu API là đặc tả các hàm, phương thức cũng như các giao thức kết nối. Nó giúp lập trình viên có thể tạo ra các phần mềm ứng dụng có thể tương tác trực tiếp với hệ điều hành. 

3/ API của thư viện phần mềm hay framework:

 - API mô tả và quy định các hành động mong muốn mà các thư viện cung cấp. Một API có thể có nhiều cách triển khai khác nhau và nó cũng giúp cho một chương trình viết bằng ngôn ngữ này có thể sử dụng thư viện được viết bằng ngôn ngữ khác. 

Ví dụ bạn có thể dùng Php để yêu cầu một thư viện tạo file PDF được viết bằng C++. Web API là gì? -   -    Web API là một phương thức dùng để cho phép các ứng dụng khác nhau có thể giao tiếp, trao đổi dữ liệu qua lại. Dữ liệu được Web API trả lại thường ở dạng JSON hoặc XML thông qua giao thức HTTP hoặc HTTPS. 

- Những điểm nổi bật của Web API Web API hỗ trợ restful đầy đủ các phương thức: Get/Post/put/delete dữ liệu. Nó giúp bạn xây dựng các HTTP service một cách rất đơn giản và nhanh chóng. Nó cũng có khả năng hỗ trợ đầy đủ các thành phần HTTP: URI, request/response headers, caching, versioning, content forma. 

- Hỗ trợ đầy đủ các thành phần MVC như: routing, controller, action result, filter, model binder, IoC container, dependency injection, unit test. 

4/ Web API hoạt động như thế nào? 

Đầu tiên là xây dựng URL API để bên thứ ba có thể gửi request dữ liệu đến máy chủ cung cấp nội dung, dịch vụ thông qua giao thức HTTP hoặc HTTPS. Tại web server cung cấp nội dung, các ứng dụng nguồn sẽ thực hiện kiểm tra xác thực nếu có và tìm đến tài nguyên thích hợp để tạo nội dung trả về kết quả. Server trả về kết quả theo định dạng JSON hoặc XML thông qua giao thức HTTP/HTTPS. Tại nơi yêu cầu ban đầu là ứng dụng web hoặc ứng dụng di động , dữ liệu JSON/XML sẽ được parse để lấy data. Sau khi có được data thì thực hiện tiếp các hoạt động như lưu dữ liệu xuống Cơ sở dữ liệu, hiển thị dữ liệu…

5/ Kiến thức thực tế:

Xây dựng API-App_PhuHuynh:

Tạo token khi login thành công

-    Vào thư mục htdoc mở cmd Tạo một dự án mới tên api_token :

Vào phpStorm mở dự án api_token lên vào terminal chạy lệnh :

php artisan make:model SessionUser -m
Xem cấu trúc thư mục:

- Vào file 2021_11_13_072554_create_session_users_table.php   Nhập :
   
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateSessionUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('session_users', function (Blueprint $table) {
$table->id();
$table->string('token');
$table->string('refresh_token');
$table->dateTime('token_expried');
$table->dateTime('refresh_token_expried');
$table->bigInteger('user_id');
$table->timestamps()
;
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('session_users');
}
}
-    Vào file .env Nhập:
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:VD+RI38y0QbJoRVI9HI14MhE4uSZAEzG7lv37k4YVDg=
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=api_token_base
DB_USERNAME=root
DB_PASSWORD=

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
-    Vào navicat tạo database:

Vào thư mục: 

Trong AppServiceProvider.php nhập như sau:
<?php

namespace App\Providers;

use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}

/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Schema::defaultStringLength(191);
}
}

-    Vào termianl chạy lệnh sau : php artisan migrate

Vào navicat kiểm tra databasse :

-    Vào termianl chạy lệnh sau :  php artisan serve
-    Bây giờ chúng ta bắt đầu viết api cho dự án:
-    Vào routes vào api nhập mã nguồn sau :
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::get('register','Api\RegisterController@register');

-    Vào termianl chạy lệnh sau :  php artisan make:controller Api\RegisterController

  -    Vào file sau :

-    Vào RegisterController.php

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class RegisterController extends Controller
{
public function register(Request $request)
{
dd('register');
}
}

Vào phần mền postman:(chú ý phải chạy server trước)


- Bây giờ chúng ta đã request thành công.

Vào api.php:

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
//api-register
Route::post('register','Api\RegisterController@register');
//login-create_token

Vào RegisterController.php : 

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;

class RegisterController extends Controller
{
public function register(Request $request)
{
$userCreate = User::create([
'name' => $request->name,
'email' => $request->email,
'password'=> bcrypt($request->password)
]);
return response()->json([
'code' => 201,
'data' => $userCreate
], 201);
}
}

-    Vào postMan:    Kết quả trả về:

Vào navicat check databasse:

-    Bây h giữ liệu đã tạo thành công

-    Vào api.php:

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
//api-register
Route::post('register','Api\RegisterController@register');
//login-create_token
Route::post('login','Api\LoginController@login');

-    Vào terminal tạo controller: php artisan make:controller Api\LoginController
-    Vào  LoginController.php :
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\SessionUser;
use Illuminate\Http\Request;
use Illuminate\Support\Str;


class LoginController extends Controller
{
public function login(Request $request)
{
$dataCheckLogin = [
'email' => $request->email,
'password' => $request->password
];
//B1 xác thc user có tài khon
if (auth()->attempt($dataCheckLogin) ){
$checkTokenExit = SessionUser::where('user_id',auth()->id())->first();
if (empty($checkTokenExit)){
$userSession = SessionUser::create([
'token'=> Str::random(40),
'refresh_token'=>Str::random(40),
'token_expried'=>date('Y-m-d H:i:s', strtotime('+30 day')),
'refresh_token_expried'=>date('Y-m-d H:i:s', strtotime('+360 day')),
'user_id'=>auth()->id()
]);
}else{
$userSession = $checkTokenExit;
}
return response()->json([
'code'=> 200,
'data'=> $userSession,
],200);
}else{
return response()->json([
'code'=> 401,
'message'=> 'userName or Password false?',
],401);
}
}
}
-    Vào SessionUser.php :
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class SessionUser extends Model
{
protected $guarded = [];
}
  - Vào api.php:
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
//api-register
Route::post('register','Api\RegisterController@register');
//login-create_token
Route::post('login','Api\LoginController@login');
-    Vào postman check:

Sử dụng token lấy dữ liệu

-    Vào terminal chạy lệnh: php artisan make:model Product -m
-    Vào  2021_11_14_015632_create_products_table.php :
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}

  -    Vào terminal chạy lệnh: php artisan migrate

-    Vào navicat tạo dữ liệu như sau:

-    Vào api.php:

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
//api-register
Route::post('register','Api\RegisterController@register');
//login-create_token
Route::post('login','Api\LoginController@login');
//danh sach san pham
Route::get('product','Api\ProductController@index');
-    Vào termianl chạy lệnh : php artisan make:controller Api\ProductController
-    Vào  ProductController.php :  
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Product;
use App\SessionUser;
use Illuminate\Http\Request;

class ProductController extends Controller
{
public function index(Request $request)
{
$token = $request->header('token');
$checkTokenIsValid = SessionUser::where('token',$token)->first();
if (empty($token)){
return response()->json([
'code'=> 401,
'message'=> 'token khong duoc gui thong qua header',
], 401);
}elseif(empty($checkTokenIsValid)){
return response()->json([
'code'=> 401,
'message'=> 'token khong hop le',
], 401);
}else{
$Product = Product::all();
return response()->json([
'code'=> 200,
'data'=> $Product
], 200);
}
}
}
Vào navicat lấy token:
Vào postman:dán token vào kiểm tra


Refresh token

-    khi token hết hạn chúng ta sẽ refresh token
-    Vào api.php:
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
//api-register
Route::post('register','Api\RegisterController@register');
//login-create_token
Route::post('login','Api\LoginController@login');
//danh sach san pham
Route::get('product','Api\ProductController@index');
//refresh_token
Route::post('refresh-token','Api\LoginController@refreshtoken');
-    Vào LoginController.php:
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\SessionUser;
use Illuminate\Http\Request;
use Illuminate\Support\Str;


class LoginController extends Controller
{
public function login(Request $request)
{
$dataCheckLogin = [
'email' => $request->email,
'password' => $request->password
];
//B1 xác thc user có tài khon
if (auth()->attempt($dataCheckLogin) ){
$checkTokenExit = SessionUser::where('user_id',auth()->id())->first();
if (empty($checkTokenExit)){
$userSession = SessionUser::create([
'token'=> Str::random(40),
'refresh_token'=>Str::random(40),
'token_expried'=>date('Y-m-d H:i:s', strtotime('+30 day')),
'refresh_token_expried'=>date('Y-m-d H:i:s', strtotime('+360 day')),
'user_id'=>auth()->id()
]);
}else{
$userSession = $checkTokenExit;
}
return response()->json([
'code'=> 200,
'data'=> $userSession,
],200);
}else{
return response()->json([
'code'=> 401,
'message'=> 'userName or Password false?',
],401);
}
}
public function refreshToken(Request $request){
$token = $request->header('token');
$checkTokenIsValid = SessionUser::where('token',$token)->first();
if (!empty($checkTokenIsValid)){
if ($checkTokenIsValid->token_exptied < time() ){
$checkTokenIsValid->update([
'token'=> Str::random(40),
'refresh_token'=>Str::random(40),
'token_expried'=>date('Y-m-d H:i:s', strtotime('+30 day')),
'refresh_token_expried'=>date('Y-m-d H:i:s', strtotime('+360 day'))
]);
}
}
$dataSession = SessionUser::find($checkTokenIsValid->id);
return response()->json([
'code'=> 200,
'data'=> $dataSession,
'message'=> 'refresh token sucess?',
],200);
}
}
Vào navicat:
-    Bây giờ chúng ta chỉnh ngày hết hạn của token:

Vào postman:


Vào navicat check lại token:


Xóa token

-    khi chúng ta logout chúng ta sẻ xóa token
-    Vào api.php:
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
//api-register
Route::post('register','Api\RegisterController@register');
//login-create_token
Route::post('login','Api\LoginController@login');
//danh sach san pham
Route::get('product','Api\ProductController@index');
//refresh_token
Route::post('refresh-token','Api\LoginController@refreshtoken');
//delete_token
Route::delete('delete-token','Api\LoginController@deletetoken')
;
-    Vào LoginController.php:
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\SessionUser;
use Illuminate\Http\Request;
use Illuminate\Support\Str;


class LoginController extends Controller
{
public function login(Request $request)
{
$dataCheckLogin = [
'email' => $request->email,
'password' => $request->password
];
//B1 xác thc user có tài khon
if (auth()->attempt($dataCheckLogin) ){
$checkTokenExit = SessionUser::where('user_id',auth()->id())->first();
if (empty($checkTokenExit)){
$userSession = SessionUser::create([
'token'=> Str::random(40),
'refresh_token'=>Str::random(40),
'token_expried'=>date('Y-m-d H:i:s', strtotime('+30 day')),
'refresh_token_expried'=>date('Y-m-d H:i:s', strtotime('+360 day')),
'user_id'=>auth()->id()
]);
}else{
$userSession = $checkTokenExit;
}
return response()->json([
'code'=> 200,
'data'=> $userSession,
],200);
}else{
return response()->json([
'code'=> 401,
'message'=> 'userName or Password false?',
],401);
}
}
public function refreshToken(Request $request){
$token = $request->header('token');
$checkTokenIsValid = SessionUser::where('token',$token)->first();
if (!empty($checkTokenIsValid)){
if ($checkTokenIsValid->token_exptied < time() ){
$checkTokenIsValid->update([
'token'=> Str::random(40),
'refresh_token'=>Str::random(40),
'token_expried'=>date('Y-m-d H:i:s', strtotime('+30 day')),
'refresh_token_expried'=>date('Y-m-d H:i:s', strtotime('+360 day'))
]);
}
}
$dataSession = SessionUser::find($checkTokenIsValid->id);
return response()->json([
'code'=> 200,
'data'=> $dataSession,
'message'=> 'refresh token sucess?',
],200);
}
public function deleteToken(Request $request){
$token = $request->header('token');
$checkTokenIsValid = SessionUser::where('token',$token)->first();
if (!empty($checkTokenIsValid)){
$checkTokenIsValid->delete();
}
return response()->json([
'code'=> 200,
'message'=> 'delete token sucess?',
],200);
}
}
Vào postman check:

check database:

Kiểm tra khi login lại có tạo lại token mới không:

Check database:

Kho Lưu Trữ:    Liên kết mã nguồn và database


Đăng nhận xét

0 Nhận xét

myadcash