如何确定请求来自 REST api

新手上路,请多包涵

我有一个带有控制器的 RESTful API,当它被我的 android 应用程序击中时应该返回一个 JSON 响应,当它被网络浏览器击中时应该返回一个“视图”。我什至不确定我是否以正确的方式处理这个问题。我正在使用 Laravel,这就是我的控制器的样子

class TablesController extends BaseController {

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

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

我需要这样的东西

class TablesController extends BaseController {

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

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

看看反应如何彼此不同?

原文由 frankelot 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 246
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';
}

原文由 Unnawut 发布,翻译遵循 CC BY-SA 3.0 许可协议

注意::这是给未来的观众的

我发现使用前缀 api 进行 api 调用很方便。在路由文件中使用

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

在上面的方法中,我为 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();
    }
}

is 方法允许您验证传入请求 URI 是否与给定模式匹配。使用此方法时,您可以使用 * 字符作为通配符。

原文由 Shafi 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题