How to determine where a request is coming from in a REST api

后端 未结 4 779
离开以前
离开以前 2021-02-07 07:12

I have an RESTful API with controllers that should return a JSON response when is being hit by my android application and a \"view\" when it\'s being hit by a web browser. I\'m

4条回答
  •  情深已故
    2021-02-07 07:28

    Note::This is for future viewers

    The approach I found convenient is to using a prefix api for api calls. In the route file use

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

    In the above approach, I separate controllers for api call and web users. But if you want to use the same controller then laravel Request has a convenient way. You can identify the prefix within your controller.

    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();
        }
    }
    

    The is method allows you to verify that the incoming request URI matches a given pattern. You may use the * character as a wildcard when utilizing this method.

提交回复
热议问题