The world is completely turning towards the easiness of using mobile devices and looking for solutions online. Web design and web development are progressing to a massive extent in today's world.
Most of the demand has been turned to smartphones as website development encompasses mobile app development as well. That being said, for mobile apps, the backend requires restful API.
If you don’t know what REST API is, that’s ok! We’ve got you covered.
In this blog, I will explain what is the REST API in Laravel is and how it works. I will also explain how to develop a restful API in Laravel.
Let’s get started!
What is the REST API?
API is an application programing interface, which helps us to connect one device to another device; for example, spouse we have one website live, and now we want to build one mobile app so we will create API to connect data to device, we have to use JSON data to pass in the device so this can be done with API only.
Sometimes, there is a need for network communicatREST API or Representational State Transfer API.
How does the REST API work?
At the very first, we have to install the Laravel app in our system so we can follow Laravel's official documentation, which will help us to move further. Here is the link to the document which can be followed to install the Laravel application: http://laravel.com/
To install the app, please use this command, but please make sure you should have a composer in your system, as a composer is a dependency tool which helps to install all dependencies in the application; you can follow this link :
Once you install composer you can download Laravel, please use this command :
composer create-project –prefer-dist laravel/laravel laravel-sanctum-auth
Once project is install then need to set database detail in .ENV file so just fill your database nane in ENV file.
The next step is to to install API package. There are many packages available but your can install as per your choice.
So to install the package, you have to follow the command as per given in laravel documentation . As I am going to use Sanctum, I will use this command :
composer require laravel/sanctum
After I run this command, my package will be installed and it will be ready to use. Just follow the screenshot below :
Once we are done with package setup, the next step is to create model for database. We will create one mode and migration which will connect to direct database ,
app/Models/User.php file.
<?php
namespace AppModels;
use IlluminateContractsAuthMustVerifyEmail;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
// sanctum
use LaravelSanctumHasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
‘name',
'email',
‘password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
‘password',
‘remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => ‘datetime',
];
}
Now we have to create one controller so please use this command to create controller
Php artisan make::controller CONTROLLER NAME
app/Http/Controllers/API/BaseController.php file:
<?php
namespace AppHttpControllersAPI;
use IlluminateHttpRequest;
use AppHttpControllersController as Controller;
class BaseController extends Controller
{
/**
* success response method.
*
* @return IlluminateHttpResponse
*/
public function sendResponse($result, $message)
{
$response = [
‘success' => true,
‘data' => $result,
‘message' => $message,
];
return response()->json($response, 200);
}
/**
* return error response.
*
* @return IlluminateHttpResponse
*/
public function sendError($error, $errorMessages = [], $code = 404)
{
$response = [
‘success' => false,
‘message' => $error,
];
if(!empty($errorMessages)){
$response[‘data'] = $errorMessages;
}
return response()->json($response, $code);
}
}
Please note : Whenever we create API, we always send response in JSON with status code.
For API we always create auth token. It means if token will be created and verified, then we can authenticate users.
<?php
namespace AppHttpControllersAPI;
use IlluminateHttpRequest;
use AppHttpControllersAPIBaseController as BaseController;
use IlluminateSupportFacadesAuth;
use Validator;
use AppModelsUser;
class AuthController extends BaseController
{
public function signin(Request $request)
{
if(Auth::attempt(['email' => $request->email, ‘password' => $request->password])){
$authUser = Auth::user();
$success[‘token'] = $authUser->createToken(‘MyAuthApp')->plainTextToken;
$success[‘name'] = $authUser->name;
return $this->sendResponse($success, ‘User signed in');
}
else{
return $this->sendError(‘Unauthorised.', [‘error'=>'Unauthorised']);
}
}
public function signup(Request $request)
{
$validator = Validator::make($request->all(), [
‘name' => ‘required',
'email' => ‘required|email',
‘password' => ‘required',
‘confirm_password' => ‘required|same:password',
]);
if($validator->fails()){
return $this->sendError(‘Error validation', $validator->errors());
}
$input = $request->all();
$input[‘password'] = bcrypt($input[‘password']);
$user = User::create($input);
$success[‘token'] = $user->createToken(‘MyAuthApp')->plainTextToken;
$success[‘name'] = $user->name;
return $this->sendResponse($success, ‘User created successfully.');
}
}
This route file :
Finally, to run the project, we need to run this command:
php artisan serve
Wrapping up!
APIs power many of today's most popular websites and services, from social networks to financial apps. In this blog, you were introduced to REST API in Laravel. We hope this laid a foundation for your understanding of what is REST API and how it works.
If you are looking for web development services, you need not look further. At webdew, you will be able to find a proactive team of skilled web designers and developers to design and build your business website. Contact us to know more.