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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With