2014-07-05 68 views
2

我有一個RESTful API,帶有控制器,當我的android應用程序被擊中時它應該返回一個JSON響應,而當它被一個web瀏覽器擊中時會出現一個「視圖」 。我甚至不確定我是以正確的方式接近這一點。我使用Laravel,這就是我的控制器看起來像如何確定請求來自REST api中

class TablesController extends BaseController { 

    public function index() 
    { 
     $tables = Table::all(); 

     return Response::json($tables); 
    } 
} 

我需要的是這樣的

類TablesController延伸BaseController {

public function index() 
{ 
    $tables = Table::all(); 

    if(beingCalledFromWebBrowser){ 
     return View::make('table.index')->with('tables', $tables); 
    }else{ //Android 
     return Response::json($tables); 
    } 
} 

看到回覆彼此的區別呢?

回答

2

您可以使用Request::wantsJson()這樣的:

if (Request::wantsJson()) { 
    // return JSON-formatted response 
} else { 
    // return HTML response 
} 

基本上什麼Request::wantsJson()做的是,它會檢查請求的accept頭是否application/json,並基於該返回true或false。這意味着你需要確保你的客戶端也發送一個「accept:application/json」頭文件。

請注意,我的答案在此並不確定「請求是否來自REST API」,而是檢測客戶端是否請求JSON響應。我的答案仍然應該是這樣做的,因爲使用REST API不一定意味着需要JSON響應。 REST API可以返回XML,HTML等


參考Laravel的Illuminate\Http\Request

/** 
* Determine if the current request is asking for JSON in return. 
* 
* @return bool 
*/ 
public function wantsJson() 
{ 
    $acceptable = $this->getAcceptableContentTypes(); 

    return isset($acceptable[0]) && $acceptable[0] == 'application/json'; 
} 
+0

事情是,當從瀏覽器點擊API時,我沒有對我的所有請求使用ajax。我是不是該? – feresr

+0

對,我修改了我的答案。您需要確保您的應用程序通過在「application/json」請求中設置「accept」標頭來請求json。將在內部如何工作的時刻進行更新。 – Unnawut

0

注::這是未來的觀衆

我發現這種方法方便是使用前綴api進行api調用。在路由文件中使用

Route::group('prefix'=>'api',function(){ 
    //handle requests by assigning controller methods here for example 
    Route::get('posts', 'Api\Post\[email protected]'); 
} 

在上面的方法中,我爲api呼叫和web用戶分開控制器。但是如果你想使用相同的控制器,那麼laravel Request有一個方便的方法。您可以識別控制器中的前綴。

public function index(Request $request) 
{ 
    if($request->is('api/*')){ 
     //write your logic for api call 
     $user = $this->getApiUser(); 
    }else{ 
     //write your logic for web call 
     $user = $this->getWebUser(); 
    } 
} 

的是方法可以驗證該輸入的請求URI的給定模式的匹配。使用此方法時,您可以將*字符用作通配符。