The world is completely turning towards the easiness of using mobile devices and looking for solutions online. Web design and web development are progressing to a massive extent in today's world.

Most of the demand has been turned to smartphones as website development encompasses mobile app development as well. That being said, for mobile apps, the backend requires restful API. 

If you don’t know what REST API is, that’s ok! We’ve got you covered. 

In this blog, I will explain what is the REST API in Laravel is and how it works. I will also explain how to develop a restful API in Laravel. 

Let’s get started!

What is the REST API?

API is an application programing interface, which helps us to connect one device to another device; for example, spouse we have one website live, and now we want to build one mobile app so we will create API to connect data to device, we have to use JSON data to pass in the device so this can be done with API only.

Sometimes, there is a need for network communicatREST API or Representational State Transfer API.

How does the REST API work?

At the very first, we have to install the Laravel app in our system so we can follow Laravel's official documentation, which will help us to move further. Here is the link to the document which can be followed to install the Laravel application: http://laravel.com/ 

To install the app, please use this command, but please make sure you should have a composer in your system, as a composer is a dependency tool which helps to install all dependencies in the application; you can follow this link :

https://getcomposer.org/download/

Once you install composer you can download Laravel, please use this command : 

composer create-project –prefer-dist laravel/laravel laravel-sanctum-auth

Once project is install then need to set database detail in .ENV file so just fill your database nane in ENV file.

The next step is to to install API package. There are many packages available but your can install as per your choice.

So to install the package, you have to follow the command as per given in laravel documentation . As I am going to use Sanctum, I will use this command :

composer require laravel/sanctum

 After I run this command, my package will be installed and it will be ready to use. Just follow the screenshot below :

Once we are done with package setup, the next step is to create model for database. We will create one mode and migration which will connect to direct database , 

app/Models/User.php file.

<?php

namespace AppModels;

use IlluminateContractsAuthMustVerifyEmail;

use IlluminateDatabaseEloquentFactoriesHasFactory;

use IlluminateFoundationAuthUser as Authenticatable;

use IlluminateNotificationsNotifiable;

// sanctum

use LaravelSanctumHasApiTokens;

class User extends Authenticatable

{

    use HasApiTokens, HasFactory, Notifiable;

 

    /**

     * The attributes that are mass assignable.

     *

     * @var array

     */

    protected $fillable = [

        ‘name',

        'email',

        ‘password',

    ];

 

    /**

     * The attributes that should be hidden for arrays.

     *

     * @var array

     */

    protected $hidden = [

        ‘password',

        ‘remember_token',

    ];

 

    /**

     * The attributes that should be cast to native types.

     *

     * @var array

     */

    protected $casts = [

        'email_verified_at' => ‘datetime',

    ];

}

 Now we have to create one controller so please use this command to create controller 

Php artisan make::controller CONTROLLER NAME

app/Http/Controllers/API/BaseController.php file:

<?php

namespace AppHttpControllersAPI;

use IlluminateHttpRequest;

use AppHttpControllersController as Controller;

class BaseController extends Controller

{

    /**

     * success response method.

     *

     * @return IlluminateHttpResponse

     */

    public function sendResponse($result, $message)

    {

      $response = [

            ‘success' => true,

            ‘data'    => $result,

            ‘message' => $message,

        ];

 

        return response()->json($response, 200);

    }

    /**

     * return error response.

     *

     * @return IlluminateHttpResponse

     */

    public function sendError($error, $errorMessages = [], $code = 404)

    {

      $response = [

            ‘success' => false,

            ‘message' => $error,

        ];

 

        if(!empty($errorMessages)){

            $response[‘data'] = $errorMessages;

        }

 

        return response()->json($response, $code);

    }

}

Please note : Whenever we create API, we always send response in JSON with status code.

For API we always create auth token. It means if token will be created and verified, then we can authenticate users.

<?php

namespace AppHttpControllersAPI;

use IlluminateHttpRequest;

use AppHttpControllersAPIBaseController as BaseController;

use IlluminateSupportFacadesAuth;

use Validator;

use AppModelsUser;

class AuthController extends BaseController

{

    public function signin(Request $request)

    {

        if(Auth::attempt(['email' => $request->email, ‘password' => $request->password])){ 

            $authUser = Auth::user(); 

            $success[‘token'] =  $authUser->createToken(‘MyAuthApp')->plainTextToken; 

            $success[‘name'] =  $authUser->name;

            return $this->sendResponse($success, ‘User signed in');

        } 

        else{ 

            return $this->sendError(‘Unauthorised.', [‘error'=>'Unauthorised']);

        } 

    }

    public function signup(Request $request)

    {

        $validator = Validator::make($request->all(), [

            ‘name' => ‘required',

            'email' => ‘required|email',

            ‘password' => ‘required',

            ‘confirm_password' => ‘required|same:password',

        ]);

        if($validator->fails()){

            return $this->sendError(‘Error validation', $validator->errors());       

        }

        $input = $request->all();

        $input[‘password'] = bcrypt($input[‘password']);

        $user = User::create($input);

        $success[‘token'] =  $user->createToken(‘MyAuthApp')->plainTextToken;

        $success[‘name'] =  $user->name;

        return $this->sendResponse($success, ‘User created successfully.');

    }

}

This route file :

Finally, to run the project, we need to run this command:

php artisan serve

Wrapping up!

APIs power many of today's most popular websites and services, from social networks to financial apps. In this blog, you were introduced to REST API in Laravel. We hope this laid a foundation for your understanding of what is REST API and how it works. 

If you are looking for web development services, you need not look further. At webdew, you will be able to find a proactive team of skilled web designers and developers to design and build your business website. Contact us to know more. 

Frequently Asked Questions

REST is a widely adopted architectural style for designing networked applications, and Laravel provides robust support for building RESTful APIs. Laravel's support for REST ensures that your API follows these conventions, enhancing interoperability and reducing ambiguity.
REST APIs are inherently scalable, allowing your application to handle increased loads as needed. Laravel's flexible architecture and caching mechanisms make it well-suited for building scalable RESTful APIs.

The four types of APIs are: Open APIs (Public APIs), Partner APIs (External APIs), Internal APIs (Private APIs) and Composite APIs (Gateway APIs).
Open APIs, also known as Public APIs, are accessible to external developers and are meant to be used by a wide audience.
Partner APIs are shared with specific external partners or organizations under certain agreements. They are not open to the general public and often require authentication or access permissions.
Internal APIs are used within an organization for communication between different software components, teams, or services.
Composite APIs are a combination of multiple APIs or services into a single interface. They provide a higher-level abstraction, simplifying complex interactions by encapsulating multiple calls into a single request.

The key difference between a general API and a REST API in the context of Laravel lies in the architectural style and principles they adhere to. An API (Application Programming Interface) is a broader concept, encompassing any set of rules and protocols for software applications to communicate with each other. In contrast, a REST API (Representational State Transfer API) is a specific type of API that follows the principles and constraints of RESTful architecture. REST APIs in Laravel adhere to resource-based URLs, use standard HTTP methods like GET, POST, PUT, and DELETE for CRUD operations, emphasize statelessness, and leverage standard status codes.

A RESTful API consists of four main components, often referred to as the “Four Pillars of REST.” These components are: Resource, HTTP Methods (Verbs), Representation, Stateless Communication.
Resources are the fundamental abstractions in a REST API. A resource represents an object or concept in the application, such as a user, product, order, or any other entity.
RESTful APIs use standard HTTP methods (also known as HTTP verbs) to perform actions on resources.
Representations define the format in which resources are exchanged between clients and the API.
RESTful communication is stateless, meaning that each request from a client to the server must contain all the information needed to understand and process the request.