2017-06-19 46 views
0

我正在按照Google(https://google.github.io/styleguide/jsoncstyleguide.xml)關於json格式響應的指導,努力創建一個良好的RESTful API服務。設置默認的JSON格式響應Laravel

有什麼辦法來設置每個響應的缺省JSON格式,因爲在指南中說

爲了保持整個API的一個一致的界面,JSON對象應 按照下面列出的結構。

object { 
    string apiVersion?; 
    string context?; 
    string id?; 
    string method?; 
    object { 
    string id? 
    }* params?; 
    object { 
    string kind?; 
    string fields?; 
    string etag?; 
    string id?; 
    string lang?; 
    string updated?; # date formatted RFC 3339 
    boolean deleted?; 
    integer currentItemCount?; 
    integer itemsPerPage?; 
    integer startIndex?; 
    integer totalItems?; 
    integer pageIndex?; 
    integer totalPages?; 
    string pageLinkTemplate /^https?:/ ?; 
    object {}* next?; 
    string nextLink?; 
    object {}* previous?; 
    string previousLink?; 
    object {}* self?; 
    string selfLink?; 
    object {}* edit?; 
    string editLink?; 
    array [ 
     object {}*; 
    ] items?; 
    }* data?; 
    object { 
    integer code?; 
    string message?; 
    array [ 
     object { 
     string domain?; 
     string reason?; 
     string message?; 
     string location?; 
     string locationType?; 
     string extendedHelp?; 
     string sendReport?; 
     }*; 
    ] errors?; 
    }* error?; 
}*; 

我與Laravel 5.4練習。我應該製作一個特質並使用自己的JSON響應格式嗎?因爲每次返回JSON響應時都必須編寫這種響應非常麻煩。

+0

娜,我相信當你迴歸你的對象時,拉拉維爾正在照顧你。您還可以使用response() - > json([])指定輸出,例如 – DevMoutarde

+0

請查看http://jsonapi.org/ json api標準。如果你選擇使用它,有基於php的模塊支持它。 – ayip

+0

@ayip可以在中型項目中使用它嗎?因爲它似乎是最後一次更新是在2015年。我已閱讀了一些文檔,我想使用它 –

回答

2

可以使用Middleware攔截響應對象,並對其進行格式化,只要你喜歡,比如我通常使用這種追加頭的響應:

<?php 
# app/Http/Middleware/ResponseAPI.php 

namespace App\Http\Middleware; 

use Closure; 

class ResponseAPI { 

    /** 
    * 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) 
    { 
     $response = $next($request); 

     if (in_array($response->status(), [200, 201, 404, 401, 422])) { 
      $response->header('Content-Type', 'application/json'); 
     } 

     return $response; 
    } 

} 

-

<?php 
# app/Http/Kernel.php 
. 
. 
. 
protected $routeMiddleware = [ 
    # others middlewares 
    'api.response' => \App\Http\Middleware\ResponseAPI::class 
]; 

-

<?php 
# app/Http/routes.php 

$app->group(['prefix' => 'api/v1', 'middleware' => ['api.response']], function($app) { 
    # all routes 
}); 
+0

我認爲這是在這種情況下唯一正確的決定。非常感謝。 – gogagubi