Laravel Api RESTful 统一封装 返回信息
Published on 04 July 2020 By. ghost
- 本文地址:https://ghost-ai.com/article/4
- 转载请注明出处
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."
}
0条评论
发表评论
您的电子邮件地址不会被公布。必填字段被标记为*