Laravel api tool kit is a set of tools that will help you to build a fast and well-organized API using laravel best practices.

Overview

Laravel API tool kit and best API practices

Laravel api tool kit is a set of tools that will help you to build a fast and well-organized API using laravel best practices.

Contents

Installation

Api response

Dynamic Pagination

Filters

Api Generator

Actions

Media Helper

Enum

General tips

Installation

composer require essa/api-tool-kit

to publish config

php artisan vendor:publish --provider="essa\APIToolKit\APIToolKitServiceProvider" --tag="config"

use exception handler to standardize the error response Error Response

namespace App\Exceptions;

use essa\APIToolKit\Exceptions\Handler;
use essa\APIToolKit\Exceptions\Handler as APIHandler;

class Handler extends ExceptionHandler
{
}

use API Response Trait in Controller

App\Http\Controllers\Controller.php:

use essa\APIToolKit\Http\ApiResponse;

class Controller extends BaseController
{
    use ApiResponse;
}

check : API response

🔝 Back to contents

API Response

it is used to format your response to standard format and status codes for success responses, it will be

Success Response

{
  "message": "your message",
  "data": "your date"
}

Error Response

{
  "errors": [
    {
      "status": 403,
      "title": "unauthenticated!",
      "detail": "Unauthenticated."
    }
  ]
}

usage: you can use the trait inside the class you want to return the response form

and use it like this

$this->responseSuccess('car created successfully' , $car);

Available Methods

responseSuccess($message , $data)  // returns a 200 HTTP status code
responseCreated($message,$data)  // returns a 201 HTTP status code 
responseDeleted()  // returns empty response with a 204 HTTP status code
responseNotFound($error_details,$error_title)  // returns a 404 HTTP status code
responseBadRequest($error_details,$error_title)  // returns a 400 HTTP status code
responseUnAuthorized($error_details,$error_title)  // returns a 403 HTTP status code
responseConflictError($error_details,$error_title)  // returns a 409 HTTP status code
responseUnprocessable($error_details,$error_title)  // returns a 422 HTTP status code
responseUnAuthenticated ($error_details,$error_title) // returns a 401 HTTP status code
responseWithCustomError($error_title, $error_details, $status_code) //send custom error 

🔝 Back to contents

Dynamic Pagination

use pagination dynamically

usage

to use dynamic pagination to get all users :

$users = User::dynamicPaginate();

to get all users without pagination :

\users?pagination='none'

to get all users paginated 10 users per page:

\users?per_page=10

by default pagination is 20 element per page you can change the default value from config/api-tool-kit

Filters

usage:

to create a filter class:

php artisan make:action CarFilters

to set default filters to the Car model , in Car model you will add

protected $default_filters = CarFilters::class;

to use it

Car::useFilters()->get();

if you want to override the default filters

Car::useFilters(SpecialCaseCarFilters::class)->get();

options in Filter class

//to add the attributes to filter by =>> /cars?color=red&model_id=1
protected array $allowedFilters  = ['color' , 'model_id']; 
//to add the attributes to filter by :
// desc : ?sorts=created_at
// asc  : ?sorts=-created_at
protected array $allowedSorts= ['created_at'];
//allowed relationships to be loaded 
protected array $allowedIncludes = ['model'];
//column that will be included in search =>> ?search=tesla
protected array $columnSearch= ['name','descriptions']; 
//relation that will be included in search =>> ?search=ahmed
protected array $relationSearch = [
    'user' => ['first_name', 'last_name']
]; 

to create a custom query you will just create a new function in the class and add your query example filter by year:

public function year($term)
{
    $this->builder->whereYear('created_At', $term);
}

//usage : /cars?year=2020

filter by relationship :

public function option($term)
{
    $this->builder->whereHas('options', fn($query) => $query->where('option_id', $term));
}
//usage : /cars?option=1

🔝 Back to contents

API Generator

Usage :

php artisan api:generate Car

when you type the command it will ask you whether you want default options :

  • (N) it will ask you which files you want to generate .
  • (Y) it will generate files for all options that exists in config/api-tool-kit
options :
 ** by default it will create a model :
-app/Models/Car.php
 ** controller :
-app/Http/Controllers/API/CarController.php
 ** resource :
-app/Http/Resources/CarResource.php
 ** request :
-app/Http/Requests/Car/CreateCarRequest.php
-app/Http/Requests/Car/UpdateCarRequest.php
 ** filter :
-app/Filters/CarFilters.php
 ** seeder :
-database/seeders/CarSeeder.php
 ** factory :
-database/factories/CarFactory.php
 ** test :
-Tests/Feature/CarTest.php
 ** migration :
-database/migrations/x_x_x_x_create_cars_table.php

in addition, the routes will be created and added in routes/api.php files

🔝 Back to contents

Actions

action is a laravel implementation of command design pattern which create a class where you can add your business logic in https://en.wikipedia.org/wiki/Command_pattern

usage:

php artisan make:action CreateCar
<?php
namespace App\Actions;

class CreateCar
{
    public function execute($data)
    {
      //add business logic to create a car
    }
}

The best practice to use the action class is to use dependency injection

you have many options 1-use laravel application container

app(CreateCar::class)->execute($data);

2-inject it in the class in constructor

private $create_car_action ;

public function __construct(CreateCar $create_car_action)
{
    $this->create_car_action=$create_car_action;
}

public function doSomething()
{
    $this->create_car_action->execute($data);
}

3-inject the class in laravel controller function

public function doSomething(CreateCar $create_car_action)
{
    $create_car_action->execute($data);
}

🔝 Back to contents

Media Helper

it is used to upload and delete an image in storage

// to upload image
$image_path = MediaHelper::uploadImage($file ,$path); 
//to delete an image
MediaHelper::deleteImage($path); //to delete image

🔝 Back to contents

**Enum

bad practice : if I have two types of users (admin ,student) instead of hard coding the name of user type every time using it you can simply use the enum class

usage :

php artisan make:enum UserTypes

it will generate classes like this

namespace App\Enums;

class UserTypes extends Enum
{
    public const ADMIN = 'admin';
    public const STUDENT = 'student';
}

methods:

UserTypes::getAll() //get all types 
UserTypes::isValid($value) //to check if this value exist in the enum
UserTypes::toArray() //to get all enums as key and value

🔝 Back to contents

General Tips

throw error instead of return json response

Bad:

public function index()
{
    if (auth()->user()->not_active ) {
        $this->responseUnAuthorized('you can not preform this action');
    } 
}

good

public function index()
{
    if (auth()->user()->not_active ) {
        throw new AuthorizationException('you can not preform this action');
    } 
}

🔝 Back to contents

You might also like...
Content Negotiation tools for PHP.

Negotiation Negotiation is a standalone library without any dependencies that allows you to implement content negotiation in your application, whateve

Provides tools for building modules that integrate Nosto into your e-commerce platform

php-sdk Provides tools for building modules that integrate Nosto into your e-commerce platform. Requirements The Nosto PHP SDK requires at least PHP v

Disable Google's FLoC with help of PSR-15 middleware

Disable Google's FLoC with PSR-15 middleware This package will help you disable Google's FLoC. Installation You can install the package via composer:

GraPHPinator ⚡ 🌐 ⚡ Easy-to-use & Fast GraphQL server implementation for PHP

Easy-to-use & Fast GraphQL server implementation for modern PHP. Includes features from latest draft, middleware directives and modules with extra functionality.

This plugin lets you to get spawners that when you break them they regenerates themselves!

ItemSpawners This plugin lets you to get spawners that when you break them they regenerates themselves! How to use? For any information: https://githu

A Laravel Fractal package for building API responses, giving you the power of Fractal with Laravel's elegancy.
A Laravel Fractal package for building API responses, giving you the power of Fractal with Laravel's elegancy.

Laravel Responder is a package for building API responses, integrating Fractal into Laravel and Lumen. It can transform your data using transformers,

Simple and effective multi-format Web API Server to host your PHP API as Pragmatic REST and / or RESTful API

Luracast Restler ![Gitter](https://badges.gitter.im/Join Chat.svg) Version 3.0 Release Candidate 5 Restler is a simple and effective multi-format Web

A simple way of authenticating your RESTful APIs with API keys using Laravel

ApiGuard This package is no longer maintained This package is no longer maintained as Laravel already has a similar feature built-in since Laravel 5.8

API for Symbiota using the Lumen PHP PHP Micro-Framework By Laravel

symbiota-api API for Symbiota using the Lumen PHP PHP Micro-Framework By Laravel Laravel Lumen Official Documentation Documentation for the Lumen fram

Releases(1.1.7)
Owner
Ahmed Esa
Software developer
Ahmed Esa
This bundle provides tools to build a complete GraphQL server in your Symfony App.

OverblogGraphQLBundle This Symfony bundle provides integration of GraphQL using webonyx/graphql-php and GraphQL Relay. It also supports: batching with

Webedia - Overblog 720 Dec 25, 2022
a tool to get Facebook data, and some Facebook bots, and extra tools found on Facebook Toolkit ++.

FACEBOOK TOOLKIT a tool to get Facebook data, and some Facebook bots, and extra tools found on Facebook Toolkit ++. Graph API Facebook. Made with ❤️ b

Wahyu Arif Purnomo 569 Dec 27, 2022
Best resources restful api for developers (with JSON:API standar specification design)

List API Best resources restful api for developers (with JSON:API standar specification design). API Resource Endpoint Name Resource Description Al Qu

Noval 2 Jan 18, 2022
Best resources restful api for developers

Best resources restful api for developers (with JSON:API standar specification design).

Noval 2 Jan 18, 2022
Laravel A2Reviews Client API lets you build apps, extensions, or plugins to get reviews from the A2reviews APP.

Overview Laravel A2Reviews Client API lets you build apps, extensions or plugins to get reviews from the A2reviews APP. Including adding reviews to a

Be Duc Tai 2 Sep 26, 2021
Zoho CRM API SDK is a wrapper to Zoho CRM APIs. By using this sdk, user can build the application with ease

Archival Notice: This SDK is archived. You can continue to use it, but no new features or support requests will be accepted. For the new version, refe

null 81 Nov 4, 2022
This project lists all the mandatory steps I recommend to build a Website using Symfony, Twig, Doctrine.

{% raw %} <-- keep this for Jekyll to fully bypass this documents, because of the Twig tags. Symfony Website Checklist ?? Summary~~~~ Elevator pitch P

William Pinaud 6 Aug 31, 2022
Jane is a set of libraries to generate Models & API Clients based on JsonSchema / OpenAPI specs

Jane is a set of libraries to generate Models & API Clients based on JsonSchema / OpenAPI specs Documentation Documentation is available at http://jan

Jane 438 Dec 18, 2022
It helps to provide API support to projects. It is Simple, Safe and Fast.

apiservice It helps to provide API support to projects. It is Simple, Safe and Fast. Setup composer create-project mind/apiservice or After downloadin

Ali Yılmaz 5 Nov 3, 2022
Awesome Set of Packages for Laravel

Awesome Set of Packages for Laravel The set provides best practices to make development more fun and classes/services that I found very useful while w

Aleksei Lebedev 8 Nov 24, 2022