Я разрабатываю Saas SPA приложение на Laravel 9 и vue2.
Разработай API для моего приложения что бы другие приложения могли получать информацию из базы данных о моряках.
На данный момент я использую файл web.php для route.
На сколько я понимаю должен быть какой-то уникальный token
-- Дамп структуры для таблица adminlte.applications
CREATE TABLE IF NOT EXISTS applications (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
remarks int(11) DEFAULT NULL,
status tinyint(4) DEFAULT '1',
current_vessel int(9) DEFAULT NULL,
prev_vessel int(9) DEFAULT NULL,
pd_eyes varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
pd_weight int(11) DEFAULT NULL,
pd_hair varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
pd_height int(11) DEFAULT NULL,
pd_shoes int(11) DEFAULT NULL,
pd_boilersuit int(11) DEFAULT NULL,
marlins_test varchar(191) DEFAULT NULL,
tose_test int(11) DEFAULT NULL,
airport varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
rank_id int(11) DEFAULT NULL,
other_rank_id int(11) DEFAULT NULL,
avatar varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
salary varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
name varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
gender tinyint(2) DEFAULT NULL,
surname varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
middlename varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
address varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
postcode varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
dob date NOT NULL,
pob varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
city varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
phone varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
mobile varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
alt_phone varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
skype varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
nok_name varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
tinyint(4) DEFAULT NULL,
tinyint(4) DEFAULT NULL,
int(11) DEFAULT NULL,
int(11) DEFAULT NULL,
text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
int(9) DEFAULT NULL,
text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
date DEFAULT NULL,
int(11) DEFAULT NULL,
tinyint(1) NOT NULL DEFAULT '1',
date DEFAULT NULL,
text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
timestamp NULL DEFAULT NULL,
timestamp NULL DEFAULT NULL,
text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
text,
varchar(150) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
varchar(150) DEFAULT NULL,
tinyint(1) DEFAULT NULL,
tinyint(1) DEFAULT '2',
tinyint(1) DEFAULT '1',
varchar(191) DEFAULT NULL,
date DEFAULT NULL,
PRIMARY KEY (),
UNIQUE KEY (),
KEY (),
KEY (),
KEY (),
KEY (),
KEY (),
KEY (,),
KEY ()
) ENGINE=InnoDB AUTO_INCREMENT=50280 DEFAULT CHARSET=utf8mb4;
Assistant
nok_relationship
nok_mobile
nok_address
marital_status
number_children
country
citizenship
school
school_status
description
data_protection_consent_date
data_protection_consent_version
data_protection_consent_status
available_from
flight_details
agent_details
created_at
updated_at
additional_information
seafarer_notes
email
login_hash
editable_status
activated
visibility
joining_port
joining_date
id
login_hash
login_hash
status
status
rank_id
rank_id
other_rank_id
other_rank_id
name
name
surname
surname
idx_applications_activated_id
activated
id
idx_applications_current_vessel
current_vessel
-- Дамп структуры для таблица adminlte.documents
CREATE TABLE IF NOT EXISTS documents (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
application_id int(11) NOT NULL,
certificate_id int(11) DEFAULT NULL,
number varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
country_id int(11) DEFAULT NULL,
primary_ tinyint(1) DEFAULT NULL,
from date DEFAULT NULL,
till date DEFAULT NULL,
PRIMARY KEY (id),
KEY application_id (application_id),
KEY certificate_id (certificate_id)
) ENGINE=InnoDB AUTO_INCREMENT=3977 DEFAULT CHARSET=utf8mb4;
-- Дамп структуры для таблица adminlte.experiences
CREATE TABLE IF NOT EXISTS experiences (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
application_id int(11) NOT NULL,
vessel_list_id int(11) DEFAULT NULL,
vessel varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
flag int(11) DEFAULT NULL,
company varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
dwt int(11) DEFAULT NULL,
kwt int(11) DEFAULT NULL,
vessel_engine_id int(11) DEFAULT NULL,
crewing varchar(190) DEFAULT NULL,
vessel_type_id int(11) DEFAULT NULL,
rank_id int(11) DEFAULT NULL,
teu varchar(100) DEFAULT NULL,
engine_model varchar(100) DEFAULT NULL,
yob varchar(10) DEFAULT NULL,
reason varchar(191) DEFAULT NULL,
from date DEFAULT NULL,
till date DEFAULT NULL,
PRIMARY KEY (id),
KEY application_id (application_id),
KEY vessel_type_id (vessel_type_id),
KEY vessel_engine_id (vessel_engine_id),
KEY idx_experiences_application_id_vessel_type_id (application_id,vessel_type_id),
KEY idx_experiences_application_id_vessel_engine_id (application_id,vessel_engine_id),
KEY idx_experiences_application_id_vessel (application_id,vessel)
) ENGINE=InnoDB AUTO_INCREMENT=199122 DEFAULT CHARSET=utf8mb4;
To develop an API for your Laravel 9 application that allows other applications to access information about sailors from your database, you'll need to set up API routes, implement authentication using unique tokens, and expose the necessary data through API endpoints. Here's a step-by-step guide to help you achieve this:
1. Set Up API Routes
Laravel provides a separate file for defining API routes: routes/api.php. Unlike routes defined in web.php, routes in api.php are stateless and are intended for API use.
Create API Routes:
Open routes/api.php and define your API routes. For example:
php
use App\Http\Controllers\Api\SailorController;
use Illuminate\Support\Facades\Route;
Route::middleware('auth:sanctum')->group(function () {
Route::get('/sailors', [SailorController::class, 'index']);
Route::get('/sailors/{id}', [SailorController::class, 'show']);
// Add more routes as needed
});
2. Install and Configure Laravel Sanctum for API Authentication
Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs. It allows you to issue API tokens to your users and authenticate API requests via tokens.
Install Sanctum:
bash
composer require laravel/sanctum
Publish Sanctum Configuration and Migration Files:
In most cases, the default configuration is sufficient. However, if you need to customize token expiration or other settings, you can adjust them in config/sanctum.php.
Update Kernel.php:
Ensure that the auth:sanctum middleware is included in your API middleware group. In app/Http/Kernel.php, it should look like this:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Application extends Model
{
protected $table = 'applications';
protected $fillable = [
// List all the fields you want to be mass assignable
];
public function documents()
{
return $this->hasMany(Document::class, 'application_id');
}
public function experiences()
{
return $this->hasMany(Experience::class, 'application_id');
}
}
Document Model (app/Models/Document.php):
php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Document extends Model
{
protected $table = 'documents';
protected $fillable = [
// List all the fields
];
public function application()
{
return $this->belongsTo(Application::class, 'application_id');
}
}
Experience Model (app/Models/Experience.php):
php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Experience extends Model
{
protected $table = 'experiences';
protected $fillable = [
// List all the fields
];
public function application()
{
return $this->belongsTo(Application::class, 'application_id');
}
}
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Http\Resources\SailorResource;
use App\Models\Application;
use Illuminate\Http\Request;
class SailorController extends Controller
{
// GET /api/sailors
public function index()
{
$sailors = Application::all();
return SailorResource::collection($sailors);
}
// GET /api/sailors/{id}
public function show($id)
{
$sailor = Application::with(['documents', 'experiences'])->findOrFail($id);
return new SailorResource($sailor);
}
}
5. Create API Resources for Data Transformation
Use Laravel's API Resources to transform your models into JSON, ensuring clients receive the data in the desired format.
Note: For security reasons, you should specify the allowed origins in production.
9. Implement Rate Limiting
Protect your API from abuse by implementing rate limiting.
Configure Rate Limiting in RouteServiceProvider:
php
// app/Providers/RouteServiceProvider.php
protected function configureRateLimiting()
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
});
}
Apply Rate Limiting to Routes:
The throttle:api middleware is already applied by default to API routes. You can adjust the rate limit as needed.
10. Test Your API
Use tools like Postman or cURL to test your API endpoints.
Testing the Sailors Endpoint with Postman:
Set the request method to GET.
Enter the endpoint URL, e.g., https://yourdomain.com/api/sailors.
In the Headers tab, add an Authorization header with the value Bearer {token}.
Send the request and verify the response.
Example: Full Implementation
routes/api.php
php
use App\Http\Controllers\Api\SailorController;
use Illuminate\Support\Facades\Route;
Route::middleware('auth:sanctum')->group(function () {
Route::get('/sailors', [SailorController::class, 'index']);
Route::get('/sailors/{id}', [SailorController::class, 'show']);
});
app/Http/Controllers/Api/SailorController.php
php
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Http\Resources\SailorResource;
use App\Models\Application;
class SailorController extends Controller
{
public function index()
{
$sailors = Application::paginate(10);
return SailorResource::collection($sailors);
}
public function show($id)
{
$sailor = Application::with(['documents', 'experiences'])->findOrFail($id);
return new SailorResource($sailor);
}
}
app/Http/Resources/SailorResource.php
php
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class SailorResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'surname' => $this->surname,
'middlename' => $this->middlename,
'email' => $this->email,
'dob' => $this->dob,
// Additional fields as needed
'documents' => DocumentResource::collection($this->documents),
'experiences' => ExperienceResource::collection($this->experiences),
];
}
}
Validation: If you're accepting data via POST or PUT requests, ensure you validate the data using Laravel's validation features.
Error Handling: Implement proper error handling and return meaningful HTTP status codes.
Logging: Log API requests and errors to monitor usage and diagnose issues.
Security: Always protect sensitive data and enforce HTTPS for secure communication.
Conclusion
By following these steps, you can develop a secure API for your Laravel application, allowing other applications to access sailor information from your database. Ensure you keep security best practices in mind, manage your API tokens carefully, and provide clear documentation to your API consumers.
If you have any questions or need further assistance, feel free to ask!