Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 not even sure I'm approaching this the right way. I'm using Laravel and this is what my controller looks like

class TablesController extends BaseController {      public function index()     {         $tables  = Table::all();          return Response::json($tables);     } } 

I need something like this

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

See how the responses differ from each other?

like image 774
frankelot Avatar asked Jul 05 '14 21:07

frankelot


People also ask

How do I find my REST API details?

Step #1 – Enter the URL of the API in the textbox of the tool. Step #2 – Select the HTTP method used for this API (GET, POST, PATCH, etc). Step #3 – Enter any headers if they are required in the Headers textbox. Step #4 – Pass the request body of the API in a key-value pair.

Which method allows you to verify that the incoming request path matches a given pattern?

rs. Path annotation in JAX-RS is used to define a URI matching pattern for incoming HTTP requests. It can be placed upon a class or on one or more Java methods.


1 Answers

Note::This is for future viewers

The approach I found convenient 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.

like image 123
Shafi Avatar answered Nov 30 '22 07:11

Shafi