Search

Ho to Create Restful API in Laravel Latest Version ?

  • Share this:
post-title

A RESTful API is an application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. It is an architectural style and approach to communications often used in web services development. REST API helps us to do Web and Mobile Development simultaneously by helping us connect database and do operations.

These APIs communicate with the application through endpoints. Let's say for example www.example.com/users gives details of all users. This endpoint can be used in any web application or mobile application to achieve the task of displaying users.

STEP 1: Installing Laravel via Composer

You can ignore this step if you already have an application downloaded or else, run the following command to create a brand new laravel project.

composer create-project laravel/laravel {directory} 10.0 --prefer-dist

STEP 2: Run the project

php artisan serve

Visit the link to check the project running. Here we will go to link http://127.0.0.1:8000 and view the default homepage of Laravel.

Laravel Home Page

STEP 3: Configure Database Connection

In this type of project, we must give precedence to the database connection, generically it should be configured before getting started. Incorporate the following code in .env file with your database details.

DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=laravelapiDB_USERNAME=rootDB_PASSWORD=

STEP 4: Setup a model in Laravel

As we know laravel follows MVC structure, the model connects the database table to project. and laravel by default make user model if you want to some edit so you can do.. other wise new model create the command with migration.

php artisan make:model User -m

STEP 5: Create Resources

When building an API, you may need a transformation layer that sits between your models and the JSON responses that are actually returned to your application’s users. This is achieved by resources. Create resource by below command.

php artisan make:resource UsersCollection

By default, resources will be placed in the app/Http/Resources directory of your application. 

After create resource below code copy and past your app/Http/Resources/UsersCollection.php file

UsersCollection.php This Class use for return list type json define some key and value according to response 

<?php

namespace App\Http\Resources\V1;
use Illuminate\Http\Resources\Json\ResourceCollection;

class UsersCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {   
        
        return $this->collection->map(function($data){
            return [
                'id' => $data->id,
                'user_name' => $data->user_name,
            ];
        });
    }

    public function with($request){
        return [ 
            "status"=> true,
            "message"=> "Users Data !"
        ];
    }
}

UserCollection.php This Class use for return Object type json define some key and value according to response 

<?php

namespace App\Http\Resources\V1;
use Illuminate\Http\Resources\Json\JsonResource;

class UserCollection extends JsonResource
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {   
        return [
            'id' => $this->id,
            'user_name' => $this->user_name
        ];
    }
}

STEP 6: Create a Controller to make function

Controller is the entity where we write the backend logic for our application. Controllers are saved in app/Http/Controllers . For this application we will make a function index in UserController which will return all list of users in database.

Make Controller.
php artisan make:controller UserControlle
Make Function in UserController.php which is stored at app/Http/Controllers .

store This method use for create a user

public function store(Request $request){
    try {
        $validation = Validator::make($request->all(),[ 
            'user_name' => 'required|max:25'
        ]);
        if($validation->fails()){
            return response()->json(['status' =>false,'message' =>$validation->errors()->first()],422);
        }
        $user = new User();
        $user->user_name = $request->user_name;
        if($user->save()){
            return response()->json(['status' =>true,'message' => 'User Data Created !','data'=>new UserCollection($user)],200);
        }else{
            return response()->json(['status' =>false,'message' => 'There was an error while processing your request !'],200);
        }
    } catch (\Exception $e) {
        return response()->json(['status' =>false,'message' => 'There was an error while processing your request: ' .
        $e->getMessage()],500);
    }
}

index This method use for get all user data

//this method use for get all user data
public function index(Request $request){
    try {
        $users = User::all();
        return new UserCollection($users);
    } catch (\Exception $e) {
        return response()->json(['status' =>false,'message' => 'There was an error while processing your request: ' .
        $e->getMessage()],500);
    }
}

userDetails This method use for get single user detail

//this method use for get single user detail
public function userDetails(Request $request){
    try {
        $user = User::find($request->user);
        return response()->json(['status' =>true,'message' => 'User Data !','data'=>new UserCollection($user)],200);
    } catch (\Exception $e) {
        return response()->json(['status' =>false,'message' => 'There was an error while processing your request: ' .
        $e->getMessage()],500);
    }
}

update This method use for update user detail

//this method use for updated user
public function update(Request $request){
    try {
        $validation = Validator::make($request->all(),[ 
            'user_name' => 'required|max:25'
        ]);
        if($validation->fails()){
            return response()->json(['status' =>false,'message' =>$validation->errors()->first()],422);
        }
        $user = User::find($request->user);
        $user->user_name = $request-user_name;
        if($user->save()){
            return response()->json(['status' =>true,'message' => 'User Data Created !','data'=>new UserCollection($user)],200);
        }else{
            return response()->json(['status' =>false,'message' => 'There was an error while processing your request !'],200);
        }
    } catch (\Exception $e) {
        return response()->json(['status' =>false,'message' => 'There was an error while processing your request: ' .
        $e->getMessage()],500);
    }
}

STEP 7: Create Endpoint for API call.

All Laravel api routes are defined inside your api.php files, which are located in the routes directory. These files are automatically loaded by the framework. The routes

//users route
Route::group(['prefix'=>'user','middleware' => ['auth:sanctum']], function(){
    Route::get('/list', [UserController::class,'index']);
    Route::get('/single/{user}', [UserController::class,'userDetails']);
    Route::post('/create', [UserController::class,'create']);
    Route::put('/update/{user}', [UserController::class,'update']);
});

EndPoint

{hostname} : localhost Or example.com

https://{hostname}/api/v1/user/list
https://{hostname}/api/v1/user/single/1
https://{hostname}/api/v1/user/store
https://{hostname}/api/v1/user/update/1
About author
Here’s My little description of your attention on Me and My blog. I am here to help you with PHP programming.
View all posts (53)