Laravel Api RESTful 统一封装 返回信息

Published on 04 July 2020 By. ghost

RESTful

对应的中文是rest式的;Restful web service是一种常见的rest的应用,是遵守了rest风格的web服务;rest式的web服务是一种 ROA(The Resource-Oriented Architecture)(面向资源的架构). 符合REST约束风格和原则的应用程序或设计就是RESTful.

/article/1  HTTP GET           # 查询id=1的 article
/article/1  HTTP DELETE     #删除id=1的 article 
/article/1  HTTP PUT            # 更新 id=1 的 article
/article/add  HTTP POST     #新增 article

Api封装类

Api 统一处理返回 http状态

<?php
namespace App\Api\Helpers\Api;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Response;
use Symfony\Component\HttpFoundation\Response as FoundationResponse;
trait ResponseServe
{
    /**
     * @var int
     */
    protected $statusCode = FoundationResponse::HTTP_OK;
    /**
     * @return mixed
     */
    public function getStatusCode()
    {
        return $this->statusCode;
    }
    /**
     * @param $statusCode
     * @return $this
     */
    public function setStatusCode($statusCode)
    {
        $this->statusCode = $statusCode;
        return $this;
    }
    /**
     * @param $data
     * @param array $header
     * @return mixed
     */
    public function respond($data, $header = [])
    {
        return Response::json($data,$this->getStatusCode(),$header);
    }
    /**
     * @param $status
     * @param array $data
     * @param null $code
     * @return mixed
     */
    public function status($status, array $data, $code = null){
        if ($code){
            $this->setStatusCode($code);
        }
        $status = [
            'status' => $status,
            'code' => $this->statusCode
        ];
        $data = array_merge($status,$data);
        return $this->respond($data);
    }

    /**
     * @param $message
     * @param int $code
     * @param string $status
     * @return mixed
     */
    public function failed($message, $code = FoundationResponse::HTTP_BAD_REQUEST, $status = 'error'){
        return $this->setStatusCode($code)->message($message,$status);
    }
    /**
     * @param $message
     * @param string $status
     * @return mixed
     */
    public function message($message, $status = "error"){
        return $this->status($status,[
            'message' => $message
        ]);
    }
    /**
     * @param string $message
     * @return mixed
     */
    public function internalError($message = "Internal Server Error!"){
        return $this->failed($message,FoundationResponse::HTTP_INTERNAL_SERVER_ERROR);
    }
    /**
     * @param string $message
     * @return mixed
     */
    public function created($message = "created")
    {
        return $this->setStatusCode(FoundationResponse::HTTP_CREATED)
            ->message($message);
    }
    /**
     * 请求方法不存在
     * @param string $message
     * @return JsonResponse
     */
    public function methodNotAllow($message = 'Method Not Allowed!')
    {
        return $this->setStatusCode(FoundationResponse::HTTP_METHOD_NOT_ALLOWED)
            ->message($message);
    }
    /**
     * 身份验证失败响应。
     * @param string $message
     * @return \Illuminate\Http\JsonResponse
     */
    public function unAuthorized($message = 'Unauthorized.')
    {
        return $this->setStatusCode(FoundationResponse::HTTP_UNAUTHORIZED)
            ->message($message);
    }
    /**
     * 服务器位置错误响应。
     * @param string $message
     * @return \Illuminate\Http\JsonResponse
     */
    public function serviceUnavailable($message = 'Service Unavailable!')
    {
        return $this->setStatusCode(FoundationResponse::HTTP_SERVICE_UNAVAILABLE)
            ->message($message);
    }
    /**
     * 权限不足响应。
     * @param string $message
     * @return \Illuminate\Http\JsonResponse
     */
    public function forbidden($message = 'Forbidden.')
    {
        return $this->setStatusCode(FoundationResponse::HTTP_FORBIDDEN)
            ->message($message);
    }
    /**
     * 表单验证错误响应。
     * @param string $message
     * @return \Illuminate\Http\JsonResponse
     */
    public function badRequest($message = 'Bad Request!')
    {
        return $this->setStatusCode(FoundationResponse::HTTP_BAD_REQUEST)
            ->message($message);
    }
    /**
     * @param $data
     * @param string $status
     * @return mixed
     */
    public function success($data, $status = "success"){
        return $this->status($status,compact('data'));
    }   
    /**
     * @param string $message
     * @return mixed
     */
    public function notFond($message = 'Not Fond!')
    {
        return $this->failed($message,Foundationresponse::HTTP_NOT_FOUND);
    }
}

错误统一处理

Api 错误统一处理


<?php
namespace App\Exceptions;
use App\Http\Controllers\Api\ApiController;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];
    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];
    /**
     * Report or log an exception.
     *
     * @param  \Throwable  $exception
     * @return void
     *
     * @throws \Exception
     */
    public function report(Throwable $exception)
    {
        parent::report($exception);
    }
    /**
     * Render an exception into an HTTP response.
     *
     * @param  Request  $request
     * @param  \Throwable  $exception
     * @return Response
     *
     * @throws \Throwable
     */
    public function render($request, Throwable $exception)
    {
        if (Str::contains($request->server('REQUEST_URI'),'/api/'))
        {
            $api = new ApiController();

            if ($exception instanceof AuthenticationException)
            {
                $response = $api->unAuthorized();
            }else if ($exception instanceof ValidationException){
                $response = $api->badRequest($exception->validator->errors()->first());
            } else if($exception instanceof ModelNotFoundException){
                $response = $api->notFond();
            }else if($exception instanceof NotFoundHttpException){
                $response = $api->notFond();
            }else if($exception instanceof MethodNotAllowedHttpException){
                $response = $api->methodNotAllow();
            }
            else{
                $response = $api->serviceUnavailable($exception->getMessage());
            }
            return $response;
        }else{
            return parent::render($request, $exception);
        }       
    }
}

调用

新建ApiController 控制器 use ResponseServe;


<?php
namespace App\Http\Controllers\Api;

use App\Api\Helpers\Api\ResponseServe;
use App\Http\Controllers\Controller;

class ApiController extends Controller
{
    use ResponseServe;
}

返回值

正常返回

{
        "status": "success",
        "code": 200,
        "data": {
                "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiI5MGM5NmI2Ny0zZDc3LTQzNWEtYjRhOS01NGJkNDFmNWU4YmQiLCJqdGkiOiJiODUyZWRjYjA4YjgzZGNiMWE5NjAwZTMxMmJjODEwM2I5ZmUwNzQ2NWQzZDI2M2VhMGI4Y2ZjYTM0Zjg0YTg2ZDAwODRjMGI0ZmQ1MjdiNiIsImlhdCI6MTU5MTk0ODQ1NywibmJmIjoxNTkxOTQ4NDU3LCJleHAiOjE2MjM0ODQ0NTcsInN1YiI6IjEiLCJzY29wZXMiOltdfQ.CxwJkmE2EtbL4-ShcIaq7DTXh9uRhJ2LI_E9HHvEsvlw2FM4c-OgQA00jpJei7SJdIw-DH9kaeXhIoGA3f2aofe5fUK2C10PxsvnSROo2qaNN7nQpGw19vNEuKz7cTE64BkS-iLFrNUwQWC1pQAP-n4rwDR-G-xqkxiL6bQxvvjk0p89CvbvGX6MJfAUEPomP0dWH5B6ANt3IotKJbKyy1AFjHWaBcH48yYrzjuf-t7gaNK--6IX08oeXYIS9ZGLiwmFYpfHrSEGmnYRJt760VNfKJkXiLI87BNfnjd8P3CS7rx9bzKsjG0FjcJiHKazK4vSV7qvavgXwn1e8VMXVCjrEWQ7Dskkv-jFnsL9XFEJqklh3I6QsL-uYZEjKXbW9hbF8-rU8hUWyZBCptHMiQxqXH6bMn39s3KCOzA_LT8enKfmC5bCBaOXR3d1mGvj5BRFxNyFzpSipp3-xt0TUkWCLftdoNvp4ZtROe5M6v_oqgRIFApq7Kf6Jj5fqvHYFGAeKwIRwZwptg5nGL8bmRXvSDfj8VhImYMsZ4Ycl5robqaxBzpskp1bwKdHIbMSG-1CqQ3nVXyNN1vWR8uqRFEHU0C_5L84rXu6JuPt7I4pkw8-pyGrKWiDL2y-n-HgEfJ6Kgn53hiodLjk68cagC9n6zckmheLGNeCXNtGPeU"
    }
}

错误信息

{
      "status": "error",
      "code": 401,
      "message": "Unauthorized."
}
21条评论
BobbieSnpl
Thu, Aug 4, 2022 2:30 AM
online casino signup bonus no deposit [url="https://firstonlinecasino.org"]real online gambling[/url] no deposit online casino bonus
LeslieSnpl
Fri, Aug 5, 2022 12:31 AM
best mobile casinos [url="https://free-online-casinos.net"]best welcome bonus online casino[/url] internet casino bonus
HonorSnpl
Sun, Aug 7, 2022 7:27 PM
why buy a vpn [url="https://freehostingvpn.com"]best gaming vpn[/url] best free windows vpn
TrudieSnpl
Mon, Aug 8, 2022 1:00 AM
casinos online real money no deposit [url="https://internet-casinos-online.net"]play blackjack online money[/url] casino welcome bonuses
TeddieSnpl
Mon, Aug 8, 2022 3:40 PM
best vpn for chrome free [url="https://freevpnconnection.com"]best vpn for warzone[/url] dot vpn
JaynellSnpl
Tue, Aug 9, 2022 1:08 AM
bonus no deposit [url="https://newlasvegascasinos.com"]online casino usa real money no deposit bonus[/url] real casino online
JenneeSnpl
Wed, Aug 10, 2022 12:08 AM
buy nord vpn [url="https://imfreevpn.net"]avast secure line vpn[/url] vpn for windows free download
DulceaSnpl
Wed, Aug 10, 2022 8:45 AM
casino no deposit welcome bonus [url="https://onlinecasinofortunes.com"]no deposit casino online[/url] real money casino games
JenneeSnpl
Wed, Aug 10, 2022 8:24 PM
business vpn small [url="https://imfreevpn.net"]free vpn download for mac[/url] vpn vanish
CarolanSnpl
Thu, Aug 11, 2022 8:00 AM
casino real money [url="https://onlinecasinosdirectory.org"]bonus casino online[/url] blackjack payout
AshleighSnpl
Thu, Aug 11, 2022 4:39 PM
international vpn service [url="https://ippowervpn.net"]reddit best vpn[/url] avast secureline vpn buy
FanyaSnpl
Fri, Aug 12, 2022 7:56 AM
welcome bonus no deposit [url="https://onlineplayerscasino.com"]free cash bonus no deposit casino[/url] best online casino bonus
KelseySnpl
Fri, Aug 12, 2022 1:29 PM
vpn vanish [url="https://rsvpnorthvalley.com"]download vpn for pc[/url] kim komando best vpn
CarolinSnpl
Sat, Aug 13, 2022 8:51 AM
no deposit casino [url="https://ownonlinecasino.com"]casinos online usa[/url] online casinos free money
LaurellaSnpl
Sat, Aug 13, 2022 11:46 AM
free safe vpn [url="https://shiva-vpn.com"]reddit best vpn[/url] buy hma vpn
SheelaghSnpl
Sun, Aug 14, 2022 7:47 PM
free vpn canada [url="https://superfreevpn.net"]vpn reviews cnet[/url] best vpn in the world
SheelaghSnpl
Mon, Aug 15, 2022 1:54 PM
free youtube vpn [url="https://superfreevpn.net"]best windows vpn app[/url] best vpn extension for chrome
FifineSnpl
Mon, Aug 15, 2022 10:44 PM
best online casinos for usa players [url="https://trust-online-casino.com"]no deposit online casino bonus[/url] top us online casino
Raldiobia
Tue, Aug 16, 2022 8:51 PM
Viagra A Los 20 Anos <a href=https://iverstromectol.com/>ivermectin rosacea</a>
Raldiobia
Tue, Aug 16, 2022 8:59 PM
Cialis 10 O 20 Mg Precios <a href=https://iverstromectol.com/>injectable ivermectin</a>
GwenoreSnpl
Tue, Aug 16, 2022 9:04 PM
mobile online casinos [url="https://vrgamescasino.com"]online gambling sites no deposit[/url] online gambling reviews

发表评论

您的电子邮件地址不会被公布。必填字段被标记为*