A Web API is like a web service which works entirely with HTTP. A RESTful API must follow the REST (REpresentational State Transfer) practices, allowing to orientate the design to the resources, provide standard responses based on the different HTTP status codes.
Methods
HTTP methods are mapped to CRUD (create, read, update and delete) actions for a resource. Although you can make slight modifications such as making the PUT method to create or update, the basic patterns are listed as follows.
HTTP GET: Get/List/Retrieve an individual resource or a collection of resources.
HTTP POST: Create a new resource or resources.
HTTP PUT: Update an existing resource or collection of resources.
HTTP PATCH: Update an existing resource or collection of resources with specified parameters like in all users data if you wanted to update the email id only you can use PATCH.
HTTP DELETE: Delete a resource or collection of resources.
Laravel is a powerful PHP framework which follows MVC coding standard. It provides beautiful support for RESTful API development. We can manage our JSON request validations, returning JSON response etc.. Laravel also provides routing feature with REST standard methods like GET, POST, PUT and DELETE.
In this article I'm going to explain how we can develop RESTful API in Laravel in a simplest way.
Here is the below code explanation in Video:
First of all I'll create a middle ware which will validate every API request.
\App\Http\Middleware\ApiSecureKeyAuth.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
<?php
namespace App\Http\Middleware;
use Closure;
use App\Http\Controllers\BaseApiController;
use Symfony\Component\HttpFoundation\Response;
class ApiSecureKeyAuth
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if(empty($request->header('apiKey')) || $request->header('apiKey')!=env('API_KEY')){
return BaseApiController::errorResponse([],'Unauthorized',[],Response::HTTP_UNAUTHORIZED);
}
return $next($request);
}
}
|
In this middle ware I'm validating weather the API request is authorized or not. I have set some secure key in .env file with the name 'API_KEY'. A developer who will consume my API will pass that secure key in the request header with key name 'apiKey'. Then I'll match that API secure key sent in header should match to the secure API key which is declared in .env file. If key matched then will move to next request else will send 'unauthorized' message in response.
So write in your .env file like:
1
|
API_KEY=coding4developers
|
We also need to add this middle ware into $routeMiddleware array in kernel.php file like:
1
2
3
|
protected $routeMiddleware = [
'apiKeyAuth' => ApiSecureKeyAuth::class,
];
|
In kernel.php, Before class you also will require to use 'ApiSecureKeyAuth' Middle ware class like:
1
|
use App\Http\Middleware\ApiSecureKeyAuth;
|
In above middle ware code I have used BaseApiController to return the unauthorized response. In BaseApiController.php, I have written all the common functions like returning response functions. Here is BaseApiController.php.
\App\Http\Controllers\BaseApiController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
<?php
namespace App\Http\Controllers;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Response as ReturnResponse;
class BaseApiController extends Controller
{
public static function successResponse($data=[], $message = '', $errors = [], $statusCode = Response::HTTP_OK){
$result = ['status' => 1, 'message'=>$message, 'errors'=>$errors, 'data'=>$data];
return ReturnResponse::json($result, $statusCode)->header('Content-Type', "application/json");
}
public static function errorResponse($data=[], $message = '', $errors = [], $statusCode = Response::HTTP_INTERNAL_SERVER_ERROR){
$result = ['status' => 0, 'message'=>$message, 'errors'=>$errors, 'data'=>$data];
return ReturnResponse::json($result, $statusCode)->header('Content-Type', "application/json");
}
public function returnResponse($result){
if ($result['status']==1){
return BaseApiController::successResponse($result['data'],$result['message']);
}else{
return BaseApiController::errorResponse($result['data'],$result['message']);
}
}
}
|
Now I wanted to create an API to register the user. So here is the route code for the register request.
\routes\api.php
1
2
3
|
Route::group(['middleware' => 'apiKeyAuth'], function () {
Route::post('/user/create', 'UserController@create');
});
|
So here I have created a middle ware group named as 'apikeyAuth' which will be authenticating the API request. Now we will create UserController.php for user registration which will contain the create() function.
\App\Http\Controllers\UserController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<?php
namespace App\Http\Controllers;
use App\Http\Requests\RegisterUserRequest;
use App\Providers\UserServiceProvider;
class UserController extends BaseApiController
{
public $userServiceProvider;
public function __construct()
{
$this->userServiceProvider = new UserServiceProvider();
}
public function create(RegisterUserRequest $request) {
$result = $this->userServiceProvider->registerUser($request);
return $this->returnResponse($result);
}
}
|
In UserController, I have used ServiceProvider for business logics of application like UserServiceProvider has been used for defining business logics for user functionalities.
I also have used RegisterUserRequest to writing validation rules for validating the API request parameters. You need to create a directory named as 'Requests' in Http directory and inside this directory we'll be creating all validation classes.
\App\Http\Requests\RegisterUserRequest.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
<?php
namespace App\Http\Requests;
class RegisterUserRequest extends BaseApiRequest {
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules() {
return [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:8|max:25',
'role' => 'required|in:2,3',
'deviceId' => 'required',
'deviceType' => 'required|in:1,2',
'deviceToken' => 'sometimes'
];
}
/**
* Get the error messages for the defined validation rules.
*
* @return array
*/
public function messages()
{
return [
'name.required' => 'You first name and last name combination is required'
];
}
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize() {
return true;
}
}
|
Here we are extending the BaseApiRequest class so here is the BaseApiRequest.php.
\App\Http\Requests\BaseApiRequest.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
<?php
namespace App\Http\Requests;
use App\Http\Controllers\BaseApiController;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
/**
* This class is base class for all API request
* @author Saurabh
*/
class BaseApiRequest extends FormRequest {
protected function failedValidation(Validator $validator) {
$response = BaseApiController::errorResponse([],trans('messages.validation_errors'),$validator->errors(),422);
throw new HttpResponseException($response);
}
}
|
Now I'll write the UserServiceProvider.php inside the Providers directory to write the business logic for registering user.
\App\Providers\UserServiceProvider.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
<?php
namespace App\Providers;
use App\Helpers\AppUtility;
use App\Models\AccessToken;
use App\Models\User;
/**
* UserServiceProvider class contains methods for user management
*/
class UserServiceProvider extends BaseServiceProvider {
protected $userModelObj;
protected $accessTokenObj;
public function __construct()
{
$this->userModelObj = new User();
$this->accessTokenObj = new AccessToken();
}
/**
* Register a user
* @param type $request
* @return type
*/
public function registerUser($request) {
try {
$utilObj = new AppUtility();
$password = $utilObj->generatePassword($request['password']);
$userId = $this->userModelObj->create($request,$password);
$accessToken = md5(uniqid(mt_rand(), true));
$isAccessTokenCreated = $this->accessTokenObj->create($request, $accessToken, $userId);
if ($userId && $isAccessTokenCreated) {
UserServiceProvider::$data['status'] = 1;
UserServiceProvider::$data['data'] = array_merge($request->all(), ['accessToken' => $accessToken]);
UserServiceProvider::$data['message'] = trans('messages.user_registered');
}
} catch (\Exception $e) {
$this->logError(__CLASS__,__METHOD__,$e->getMessage());
}
return UserServiceProvider::$data;
}
}
|
Here UserServiceProvider class has extended the BaseServiceProvider class. BaseServiceProvider class contains some common functions and properties which will be used in service providers.
\App\Providers\BaseServiceProvider.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Log;
class BaseServiceProvider extends ServiceProvider
{
public static $data = [
'data' => [],
'message' => '',
'status' => 0
];
public function logError($class, $method, $errorMessage){
BaseServiceProvider::$data['message'] = trans('messages.server_error');
BaseServiceProvider::$data['status'] = 0;
Log::error( $class ."::" . $method . " " . $errorMessage);
}
/**
* Register any application services.
*
* @return void
*/
public function register() {
//
}
}
|
I also have used AppUtility class in UserServiceProvider for hashing the password. So basically I have created a helper class named as AppUtility which contains some common functions which can be used in the application.
\App\Helpers\AppUtility.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
<?php
/**
* This file contains all the common method that are being used multiple time throughout the app
*/
namespace App\Helpers;
class AppUtility {
public function __construct() {
}
/**
* This function is being used for generate password
* using hash (bcrypt method)
* @param type $password
* @return type encrypted password
*/
public function generatePassword($password = '') {
return \Hash::make($password);
}
/**
* This function is being used for matching password(change password)
* @param type $postPassword
* @param type $userPassword
* @return type
*/
public function matchPassword($postPassword, $userPassword) {
return \Hash::check($postPassword, $userPassword);
}
}
|
In UserServiceProvider I also have used some models like AccessToken and User model. But for using model I will require to create the tables. I'll be creating my tables through the migrations. You can take a look over Laravel migrations here.
Laravel already provides migration for user table. I have edited user table migration according to my need like:
\database\migrations\some_timestamp_create_users_table.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->tinyInteger('role')->default(2)->comment('1->Admin, 2->AppUser, 3->Vendor');
$table->boolean('status')->default(1)->comment('1->Active User, 0->Inactive User');
$table->rememberToken();
$table->timestamp('created_at')->default(\DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->default(\DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
$table->softDeletes();
});
}
|
You also can crate migration class for products by following command:
1
|
php artisan make:migration create_products_table --create=products
|
\database\migrations\some_timestamp_create_products_table.php
1
2
3
4
5
6
7
8
9
10
11
|
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->string('productName');
$table->string('brand');
$table->timestamp('created_at')->default(\DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->default(\DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
$table->softDeletes();
});
}
|
You also can crate migration class for access tokens by following command:
1
|
php artisan make:migration create_access_tokens --create=access_tokens
|
\database\migrations\some_timestamp_access_tokens_table.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public function up()
{
Schema::create('access_tokens', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->integer('userId')->unsigned();
$table->string('deviceToken')->nullable();
$table->string('deviceId')->nullable();
$table->tinyInteger('deviceType')->default(1)->comment('1->IOS,2->Android');
$table->string('accessToken')->nullable();
$table->timestamp('created_at')->default(\DB::raw('CURRENT_TIMESTAMP'));
$table->foreign('userId')->references('id')->on('users')->onDelete('cascade');;
});
}
|
After creating your migration classes you can run migrations with following command:
1
|
php artisan migrate
|
\App\Models\AccessToken.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class AccessToken extends Model
{
protected $table = 'access_tokens';
public function create($request, $accessToken, $userId){
return AccessToken::insert(['userId'=>$userId,'deviceToken'=>$request->deviceToken,'deviceId'=>$request->deviceId, 'deviceType'=>$request->deviceType,'accessToken'=>$accessToken]);
}
}
|
\App\Models\User.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = 'users';
const APP_USER = 2;
public function create($request,$password){
return User::insertGetId(['name'=>$request->name,'email'=>$request->email,'password'=>$password,'password'=>$password]);
}
}
|
Now you will be able to register the user through the RESTfull API in Laravel. After registration you'll get an access token in JSON response. That access token will be used for user authentication.
Now I'll explain how you can write the Login RESTfull API in Laravel.
You route for login will be like:
1
|
Route::post('/user/login', 'UserController@login');
|
Your login function in UserController will look like:
1
2
3
4
|
public function login(LoginUserRequest $request) {
$result = $this->userServiceProvider->login($request);
return $this->returnResponse($result);
}
|
\App\Http\Requests\LoginUserRequest.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
<?php
namespace App\Http\Requests;
class LoginUserRequest extends BaseApiRequest {
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules() {
return [
'email' => 'required',
'password' => 'required',
'deviceId' => 'required',
'deviceType' => 'required',
'deviceToken' => 'sometimes'
];
}
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize() {
return true;
}
}
|
Here will be your UserServiceProvider code for login function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
public function login($data) {
try {
UserServiceProvider::$data['message'] = trans('auth.failed');
$user = User::where('email', $data['email'])->first();
if(!empty($user)) {
$utilObj = new AppUtility();
$isPasswordMatched = $utilObj->matchPassword($data['password'], $user->password);
if ($isPasswordMatched) {
$accessToken = md5(uniqid(mt_rand(), true));
$accessTokenData = AccessToken::select('accessToken')->where('userId',$user->id)->where('deviceId',$data->deviceId)->where('deviceType',$data->deviceType)->first();
if(empty($accessTokenData)) {
$isAccessTokenCreated = $this->accessTokenObj->create($data, $accessToken, $user->id);
if ($user->id && $isAccessTokenCreated) {
UserServiceProvider::$data['status'] = 1;
UserServiceProvider::$data['data'] = ['accessToken' => $accessToken];
UserServiceProvider::$data['message'] = trans('messages.login_success');
}
}else {
UserServiceProvider::$data['status'] = 1;
UserServiceProvider::$data['data'] = ['accessToken' => $accessTokenData->accessToken];
UserServiceProvider::$data['message'] = trans('messages.already_login');
}
}
}
} catch (\Exception $e) {
$this->logError(__CLASS__,__METHOD__,$e->getMessage());
}
return UserServiceProvider::$data;
}
|
After Login/Registration you will get the access token. This token will be used for user authentication. For example if you have products in your database and you wanted to allow CRUD operation over products only for those who has got access token after login/registration.
API consumer will have to send the access token in the header of API request. Here will be the middle ware for authenticating the access token.
\App\Http\Middleware\UserAuth.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
<?php
namespace App\Http\Middleware;
use App\Models\AccessToken;
use Closure;
use App\Http\Controllers\BaseApiController;
use Symfony\Component\HttpFoundation\Response;
class UserAuth
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if(empty($request->header('accessToken'))){
return BaseApiController::errorResponse([],'Unauthorized',[],Response::HTTP_UNAUTHORIZED);
}
else if(!empty($request->header('accessToken'))){
$isAuthorized = AccessToken::select('id')->where('accessToken',$request->header('accessToken'))->first();
if(empty($isAuthorized)) {
return BaseApiController::errorResponse([],'Unauthorized',[],Response::HTTP_UNAUTHORIZED);
}
}
return $next($request);
}
}
|
Now you require to add this middle ware into kernel.php $routeMiddleware array like:
1
2
3
|
protected $routeMiddleware = [
'userAuth' => UserAuth::class,
];
|
In kernel.php, Before class you also will require to use 'UserAuth' Middle ware class like:
1
|
use App\Http\Middleware\UserAuth;
|
Here will be the final route for all APIs.
routes\api.php
1
2
3
4
5
6
7
8
9
10
11
12
|
<?php
Route::group(['middleware' => 'apiKeyAuth'], function () {
Route::post('/user/create', 'UserController@create');
Route::post('/user/login', 'UserController@login');
Route::group(['middleware' => 'userAuth'], function () {
Route::post('/user/logout', 'UserController@logout');
Route::get('/product/get', 'ProductController@get');
Route::put('/product/update', 'ProductController@update');
Route::delete('/product/delete', 'ProductController@delete');
});
});
|
A user who has valid access toke can access the following APIs:
- Logout User API
- Get Product listing API
- Update Product API
- Delete Product API
So final Files will look like:
\App\Http\Controllers\UserController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
<?php
namespace App\Http\Controllers;
use App\Http\Requests\LoginUserRequest;
use App\Http\Requests\RegisterUserRequest;
use App\Providers\UserServiceProvider;
use Illuminate\Http\Request;
class UserController extends BaseApiController
{
public $userServiceProvider;
public function __construct()
{
$this->userServiceProvider = new UserServiceProvider();
}
public function create(RegisterUserRequest $request) {
$result = $this->userServiceProvider->registerUser($request);
return $this->returnResponse($result);
}
public function login(LoginUserRequest $request) {
$result = $this->userServiceProvider->login($request);
return $this->returnResponse($result);
}
public function logout(Request $request){
$result = $this->userServiceProvider->logout($request);
return $this->returnResponse($result);
}
}
|
\App\Providers\UserServiceProvider.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
<?php
namespace App\Providers;
use App\Helpers\AppUtility;
use App\Models\AccessToken;
use App\Models\User;
/**
* UserServiceProvider class contains methods for user management
*/
class UserServiceProvider extends BaseServiceProvider {
protected $userModelObj;
protected $accessTokenObj;
public function __construct()
{
$this->userModelObj = new User();
$this->accessTokenObj = new AccessToken();
}
/**
* Register a user
* @param type $request
* @return type
*/
public function registerUser($request) {
try {
$utilObj = new AppUtility();
$password = $utilObj->generatePassword($request['password']);
$userId = $this->userModelObj->create($request,$password);
$accessToken = md5(uniqid(mt_rand(), true));
$isAccessTokenCreated = $this->accessTokenObj->create($request, $accessToken, $userId);
if ($userId && $isAccessTokenCreated) {
UserServiceProvider::$data['status'] = 1;
UserServiceProvider::$data['data'] = array_merge($request->all(), ['accessToken' => $accessToken]);
UserServiceProvider::$data['message'] = trans('messages.user_registered');
}
} catch (\Exception $e) {
$this->logError(__CLASS__,__METHOD__,$e->getMessage());
}
return UserServiceProvider::$data;
}
/**
* Login User
*
* @param type $data
* @return type
*/
public function login($data) {
try {
UserServiceProvider::$data['message'] = trans('auth.failed');
$user = User::where('email', $data['email'])->first();
if(!empty($user)) {
$utilObj = new AppUtility();
$isPasswordMatched = $utilObj->matchPassword($data['password'], $user->password);
if ($isPasswordMatched) {
$accessToken = md5(uniqid(mt_rand(), true));
$accessTokenData = AccessToken::select('accessToken')->where('userId',$user->id)->where('deviceId',$data->deviceId)->where('deviceType',$data->deviceType)->first();
if(empty($accessTokenData)) {
$isAccessTokenCreated = $this->accessTokenObj->create($data, $accessToken, $user->id);
if ($user->id && $isAccessTokenCreated) {
UserServiceProvider::$data['status'] = 1;
UserServiceProvider::$data['data'] = ['accessToken' => $accessToken];
UserServiceProvider::$data['message'] = trans('messages.login_success');
}
}else {
UserServiceProvider::$data['status'] = 1;
UserServiceProvider::$data['data'] = ['accessToken' => $accessTokenData->accessToken];
UserServiceProvider::$data['message'] = trans('messages.already_login');
}
}
}
} catch (\Exception $e) {
$this->logError(__CLASS__,__METHOD__,$e->getMessage());
}
return UserServiceProvider::$data;
}
public function logout($data){
try {
$isAccessTokenDeleted = AccessToken::where('accessToken',$data->header('accessToken'))->delete();
if($isAccessTokenDeleted) {
UserServiceProvider::$data['status'] = 1;
UserServiceProvider::$data['message'] = trans('messages.logout_success');
}
} catch (\Exception $e) {
$this->logError(__CLASS__,__METHOD__,$e->getMessage());
}
return UserServiceProvider::$data;
}
}
|
For products APIs:
\App\Http\Controllers\ProductController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
<?php
namespace App\Http\Controllers;
use App\Http\Requests\DeleteProductRequest;
use App\Http\Requests\UpdateProductRequest;
use App\Providers\ProductServiceProvider;
class ProductController extends BaseApiController
{
public $productServiceProvider;
public function __construct()
{
$this->productServiceProvider = new ProductServiceProvider();
}
public function get() {
$result = $this->productServiceProvider->getProducts();
return $this->returnResponse($result);
}
public function update(UpdateProductRequest $request){
$result = $this->productServiceProvider->updateProduct($request);
return $this->returnResponse($result);
}
public function delete(DeleteProductRequest $request){
$result = $this->productServiceProvider->deleteProduct($request);
return $this->returnResponse($result);
}
}
|
\App\Http\Requests\UpdateProductRequest.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
<?php
namespace App\Http\Requests;
class UpdateProductRequest extends BaseApiRequest {
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules() {
return [
'productId' => 'required|integer',
'productName' => 'required'
];
}
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize() {
return true;
}
}
|
\App\Http\Requests\DeleteProductRequest.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
<?php
namespace App\Http\Requests;
class DeleteProductRequest extends BaseApiRequest {
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules() {
return [
'productId' => 'required|integer',
];
}
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize() {
return true;
}
}
|
\App\Providers\ProductServiceProvider.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
<?php
namespace App\Providers;
use App\Models\Product;
/**
* ProductServiceProvider class contains methods for product management
*/
class ProductServiceProvider extends BaseServiceProvider {
public function __construct()
{
}
/**
* products list
* @return type
*/
public function getProducts() {
try {
$products = Product::select('id','productName','brand')->get();
UserServiceProvider::$data['status'] = 1;
UserServiceProvider::$data['data'] = ['products' => $products];
UserServiceProvider::$data['message'] = trans('messages.products_list');
} catch (\Exception $e) {
$this->logError(__CLASS__,__METHOD__,$e->getMessage());
}
return UserServiceProvider::$data;
}
/**
* update product
* @return type
*/
public function updateProduct($request) {
try {
$isProductUpdated = Product::where('id',$request->productId)->update(['productName'=>$request->productName]);
if($isProductUpdated){
UserServiceProvider::$data['status'] = 1;
UserServiceProvider::$data['message'] = trans('messages.product_updated');
}
} catch (\Exception $e) {
$this->logError(__CLASS__,__METHOD__,$e->getMessage());
}
return UserServiceProvider::$data;
}
/**
* delete product
* @return type
*/
public function deleteProduct($request){
try {
$isProductUpdated = Product::where('id',$request->productId)->delete();
if($isProductUpdated){
UserServiceProvider::$data['status'] = 1;
UserServiceProvider::$data['message'] = trans('messages.product_deleted');
}
} catch (\Exception $e) {
$this->logError(__CLASS__,__METHOD__,$e->getMessage());
}
return UserServiceProvider::$data;
}
}
|
\App\Models\Product.php
1
2
3
4
5
6
7
8
9
10
11
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $table = 'products';
}
|
Create a new file messages.php for writing all API messages.
\resources\lang\en\messages.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<?php
return [
'user_registered' => 'You have been registered successfully.',
'server_error' => 'Oops! Something went wrong, Please contact to Admin.',
'validation_errors' => 'Validation errors',
'login_success' => 'User logged in successfully',
'already_login' => 'You are already logged in!',
'products_list' => 'Products list',
'product_updated' => 'Product has been updated successfully',
'product_deleted' => 'Product has been deleted successfully',
'logout_success' => 'You have been logged out successfully'
];
|
Testing:
For user registration API:
URL: http://localhost/laravel/webservice/public/api/user/create
Headers : { "apiKey":"coding4developers", "Content-Type":"application/json" }
Method : POST
Body : {
"name" : "Coding 4 Developers",
"email" : "info@www.coding4developers.com",
"password" : "5454asfasfafa",
"role" : 2,
"deviceId" : "sdfjgsdjfgsdf",
"deviceType" : 1,
"deviceToken" : "ajhfgahfasfaf"
}
For user login API:
URL: http://localhost/laravel/webservice/public/api/user/login
Headers : { "apiKey":"coding4developers", "Content-Type":"application/json" }
Method : POST
Body : {
"email" : "info@www.coding4developers.com",
"password" : "5454asfasfafa",
"deviceId" : "sdfjgsdjfgsdf",
"deviceType" : 1,
"deviceToken" : "ajhfgahfasfaf"
}
For user logout API:
URL: http://localhost/laravel/webservice/public/api/user/logout
Headers : { "apiKey":"coding4developers", "Content-Type":"application/json", "accessToken":"f0df618a279944e59615ccd5ffce2875" }
Method : POST
For get products list API:
URL: http://localhost/laravel/webservice/public/api/product/get
Headers : { "apiKey":"coding4developers", "Content-Type":"application/json", "accessToken":"f0df618a279944e59615ccd5ffce2875" }
Method : GET