Creating Restful API in Laravel 5.7

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.restapisample.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.

So today we will develop REST API in Laravel 5.7

STEP 1: Install Composer

Composer is a dependency manager for PHP like Pip is for python. Here we will use composer to install laravel project and its dependency. To install composer visit https://getcomposer.org/download/

STEP 2: Installing Laravel via Laravel Installer.

First, download the Laravel installer using Composer.

composer global require "laravel/installer"

Once installed, the laravel new command will create a fresh Laravel installation in the directory you specify. For instance, laravel new RestApi will create a directory named RestApi containing a fresh Laravel installation with all of Laravel’s dependencies already installed.

laravel new RestApi

To check what is the version of the project installed, you can use the command.

php artisan --version

STEP 3: Run the project

php artisan serve
Image for post
Image for post
console after command above.

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

Image for post
Image for post
The project running

STEP 4: Create a Database

Laravel comes bundled up with default migrations to make users table, we will run the migrations. Then populate the database. But the prerequisites are as follows.

Image for post
Image for post
Creating a database named restapi

2. Make a database connection to laravel project. Edit .env file in the project. My Xampp phpmyadmin user is root and password is null. The database name we gave is restapi.

Image for post
Image for post
.env file edit in laravel project.

3. Migrate database by below command.

php artisan migrate

4. Check Database and populate.

Image for post
Image for post
The database structure of restapi
Image for post
Image for post
table users populated with dummy data

STEP 5: Create a model in Laravel

As we know laravel follows MVC structure, the model connects the database table to project. The command to create model is

php artisan make:model User

The model named user.php is saved in directory app .We have to know tell the model what is the unique table it is connected to and the primary key. Make the following changes in the model.

class User extends Authenticatable
{
protected $table = 'users';
protected $primaryKay = 'id';
}

STEP 6: 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 UserResource

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

Every resource class defines a toArray method which returns the array of attributes that should be converted to JSON when sending the response. Notice that we can access model properties directly from the $this variable. For UserResource saved in app/Http/Resources we will change toArray function as below.

class UserResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
];
}
}

STEP 8: 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 getusers in UserController which will return all list of users in database.

php artisan make:controller UserController

2. Make Function in UserController.php which is stored at app/Http/Controllers .

<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;//Use User Model
use App\User;
//Use Resources to convert into json
use App\Http\Resources\UserResource as UserResource;
class UserController extends Controller
{
public function getusers()
{
$users = User::get();
return UserResource::collection($users);
}
}

STEP 9: Create Endpoint for API call.

We will now create an endpoint for our api. In the routes there exists the api.php file. This will hold all the API endpoints.

For getting list of all users we will create a /getusers route in this file.

Image for post
Image for post
making route for api
Route::get('getusers','UserController@getusers');

STEP 10: Call your API

In Laravel every api is prefixed by /api. So for getting the list of all users, we need to hit point /api/getusers.

Image for post
Image for post

2. Check through postman.

Image for post
Image for post

That's it we are done. Congratulations.

Written by

:)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store