Best practices of designing APIs in Laravel

Alex Renoki
Jan 27 · 7 min read
Stolen from here.

Security

Headers

var data = JSON.parse(response.data);
function index(Request $request)
{
$var = $request->variable;
}
function index(Request $request)
{
$data = $request->all(); // this is empty array, even we have data.
}
function getUsers(Request $request)
{
return responder()->success(User::all())->respond();
}
function getUsers(Request $request)
{
$users = User::all();

if ($users->count() === 0) {
return responder()->error('no_users', 'There are no users.')->respond();
}
return responder()->success($users)->respond();
}

Coding standards

Use routes/api.php file for API routes

Make use of the route names

Route::get('/users', 'API\UserController@getUsers')->name('get.users');
Route::group(['as' => 'api.'], function () {
Route::get('/users', 'API\UserController@getUsers')->name('get.users');
});

Descriptive, yet simple routes

Route::group(['as' => 'api.'], function () {
Route::group(['as' => 'account.', 'prefix' => '/account'], function () {
Route::get('/users', 'API\UserController@getUsers')->name('get.users');
Route::get('/user/{id}', 'API\UserController@getUser')->name('get.user');
Route::post('/user', 'API\UserController@createUser')->name('create.user');
// etc.
});
});
function getUsers(Request $request)
{
$users = User::all();
return responder()->success($users)->respond();
}
function getUser($id, Request $request)
{
$user = User::findOrFail($id);
return responder()->success($user)->respond();
}
function createUser(CreateUserRequest $request)
{
$user = User::create($request->all());
return responder()->success($user)->respond();
}
// etc.

Too hard to understand? Reach me!

If this post was helpful, please click the clap 👏 button below a few times to show your support for the author! ⬇

Faun

The Must-Read Publication for Aspiring Developers & DevOps Enthusiasts

Alex Renoki

Written by

Certified Laravel Developer. Working with full-stack web applications, AWS, Kubernetes and buzzwords like cloud computing.

Faun

Faun

The Must-Read Publication for Aspiring Developers & DevOps Enthusiasts