sadeee nadeee sadeee nadeee - 3 years ago 142
reST (reStructuredText) Question

Creating a API for a laravel web application

I want to create a API for a website developed using laravel. API is used to obtain data to a android application.I am new to API concept.So I am stuck at the moment. I don't know where to start. Can anyone guide me in the correct direction?

Answer Source

defining routes changes depending on the version of Laravel.

In Laravel 5.3 we can define api in a separate api.php file instead of the routes.php file.

I can say a few basic points which will help for REST API.

  1. Authentication :

    You can use auth_token in your backend (database) and on successful login update the auth token and in every api request you should pass the auth token. This will match with the auth token in the backend if it is same then we will let the user to get data response.

  2. Route:

    It is same as we are defining routes in laravel routes.php file. But it is good to prefix it like this.

    Route::group(['prefix' => 'api/v1'], function()
       Route::post('authenticate', 'APIV1Controller@authenticate');

    Using this you can group the routes and it is good to maintain versions ( v1 ) so that we can update api by maintaining different versions like v2.


    You can use postman or the REST API Client addon for Firefox to hit the API.

  4. Headers:

    To hit the API we need to specify headers. To pass JSON request, the header should be

    Content-Type: application/json
  5. Always have status_code and message in your api response. The response should be return in JSON Format.

    Simple Example :


    Route::group(['prefix' => 'api/v1'], function()
        Route::post('getUserData', 'APIV1Controller@getUserData');


    public function getUserData(Request $request){
    $user = User::select('name','phone')
        return response()->json(['statusCode' => '200','message' => 'User Found','userDetails'=>$user]);
          return response()->json(['statusCode' => '400','message' => 'User Not Found']);

    In Postman:

    URL :

    Headers: Content-Type: application/json

    Request : {"email":""}

    Hit the api and you will get the response.

    Response :

    {"statusCode":"200","message":"User Found","userDetails":{"name":"Ganesh","phone":"1525353535"}}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download