The world is completely turning towards the easiness of using mobile devices and looking for solutions online. Web design and web development are progressing at a massive extent in today's world.
Most of the demand have been turned to smartphones as website development encompasses mobile app development as well. That being said, for mobile apps, backend require 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 restful API 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 application programing interface, which help 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 device so this can donhe with API only.
Sometimes, there is a need for network communicatREST API or Representational State Transfer API.
How does it work?
At the very first we have to install laravel app in our system so we can follow laravel official documentation which will help us to moving further. Here is the link of document which can be follow to install the laravel application:
To install app please use this command but please make sure you should have composer in your system , as composer is dependency tool which help to install all dependencies in application, you can follow the this link :
https://getcomposer.org/download/
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 App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
// sanctum
use Laravel\Sanctum\HasApiTokens;
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 App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller as Controller;
class BaseController extends Controller
{
/**
* success response method.
*
* @return \Illuminate\Http\Response
*/
public function sendResponse($result, $message)
{
$response = [
'success' => true,
'data' => $result,
'message' => $message,
];
return response()->json($response, 200);
}
/**
* return error response.
*
* @return \Illuminate\Http\Response
*/
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 App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\API\BaseController as BaseController;
use Illuminate\Support\Facades\Auth;
use Validator;
use App\Models\User;
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 to 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.