title | author | format | ||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Creating RESTful API with Laravel |
Vladimir Lelicanin - SAE Institute |
|
- REST stands for Representational State Transfer
- A RESTful API is an interface that is useful for communicating between different systems, including web and mobile applications
- APIs use HTTP requests to POST (create), PUT (update), GET (read), and DELETE data
- Laravel is a PHP framework that makes it easy to build web applications and RESTful APIs
- It provides a beautiful syntax and features like routing, ORM, migrations, and many others
- Step 1: Install Laravel using composer
composer create-project --prefer-dist laravel/laravel myapi
- Step 2: Run the project on local server
php artisan serve
- Step 3: Create a new controller
php artisan make:controller ApiController
- Endpoints are routes that enable you to interact with database resources through HTTP methods
- Example:
Route::get('/users', 'ApiController@index');
Route::get('/users/{id}', 'ApiController@show');
Route::post('/users', 'ApiController@store');
Route::put('/users/{id}', 'ApiController@update');
Route::delete('/users/{id}', 'ApiController@destroy');
$request
parameter in controllers is used to get request data- Laravel
response()
function is used to return data in JSON format - Example:
public function index()
{
$users = User::all();
return response()->json($users);
}
- Laravel Eloquent ORM makes it easy to interact with database records
- Example:
public function show($id)
{
$user = User::find($id);
return response()->json($user);
}
- Laravel request validation is a middleware that validates user input before processing it
- Example:
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required',
]);
$user = User::create($request->all());
return response()->json($user);
}
- Laravel Passport package allows for easy integration of OAuth2 API authentication
- Example:
public function login(Request $request)
{
$credentials = request(['email', 'password']);
if (!Auth::attempt($credentials)) {
return response()->json([
'message' => 'Unauthorized'
], 401);
}
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
$token->save();
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer'
]);
}
- Rate limiting protects an API by restricting user access to a certain number of requests per minute
- Laravel built-in rate limiter middleware can be used to achieve this functionality
Route::middleware('throttle:60,1')->group(function () {
Route::get('/users', 'ApiController@index');
});
- Laravel query scopes can be used to implement search queries
public function scopeSearch($query, $search)
{
return $query->where('name', 'like', "%$search%")
->orWhere('email', 'like', "%$search%");
}
public function index(Request $request)
{
$search = $request->query('search');
$users = User::search($search)->get();
return response()->json($users);
}
- Laravel API Resource feature allows you to transform a model into a JSON representation
- Example:
use Illuminate\Http\Resources\Json\JsonResource;
class UserResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
];
}
}
public function index()
{
$users = User::all();
return UserResource::collection($users);
}
- Customization of API Resource enables you to add additional properties to the JSON representation of a resource
- Example:
class UserResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'created_at' => $this->created_at,
];
}
}
- Laravel built-in
paginate()
method is used to paginate database results - Example:
public function index()
{
$users = User::paginate(10);
return UserResource::collection($users);
}
- Laravel exception handler enables us to properly format and display response to API exceptions
- Example:
public function show($id)
{
$user = User::find($id);
if (! $user) {
throw new ModelNotFoundException('The user you are looking for doesn't exist.');
}
return new UserResource($user);
}
- Versioning API helps keep backward compatibility and track changes
- Example:
Route::middleware(['api', 'v1'])->group(function () {
Route::get('/users', 'Api\v1\ApiController@index');
});
Route::middleware(['api', 'v2'])->group(function () {
Route::get('/users', 'Api\v2\ApiController@index');
});
- RESTful API with Laravel makes it easy to build, test, and deploy APIs
- The Laravel framework allows you to focus on the business logic of your application and not re-inventing the wheel
- Laravel also has a great documentation to help you through every step