Being a backend developer, I would surely accept that third-party API is one thing that is being consumed in everyday work to integrate the functionality of providers in a project. API is an interface or code that acts as a mediator between two different programs. Also, people use it to complete mobile app development

Usually, mobile apps are not connected to any database; that's why many backend developers provide the data through API. Here, one that needs to be focused on is security. Whenever data is shared through API, it needs to be secured so that no third person can access it or make any changes. 

Well! Creating an authenticated API is not a cakewalk. You can create it in different languages like Java, .net, node.js, or PHP.

Don't know how to create authenticated APIs? Do not worry! Today we are going to learn the creation of Authenticated API in Laravel, which is a popular PHP framework used in most companies. 

Now without any further ado, let's jump onto the steps following which you can easily create an Authenticated API in Laravel. 

Steps to create Authenticated API in Laravel

Let's begin!

Step 1: Open the Terminal

Firstly, you need to open the terminal, but make sure you have Composer installed in your PC. 

Step 2: Create a Laravel Project

After opening the terminal, its time to create a Laravel project with the following command-

“composer create-project laravel/laravel laravel-api”

create a laravel project

Step 3: Open Project in Code Editor

Now, open your project in your favorite code editor. To help you understand each step. I am using Visual studio code editor.      

Step 4: Download the Official Passport Package

Then type in composer require Laravel/passport. This command will download the official Passport package from Composer Package Manager. To better understand, you can refer to the below-added screenshot- 

download the official passport package

Step 5: Update DB Settings

Navigate to your .env file and update your DB settings.

update db settings

Step 6: Add Tables to Database

Now go to your terminal and run the artisan command added below- 

“php artisan migrate”

Once this command is in process, you will see that this will add all the required tables to your database. 

Step 7: Run PHP Artisan Passport

Now it's time to run PHP artisan passport: install command in terminal. It will help you to create the encryption key which is required for generating secure tokens.

Step 8: Open app/User.php File

Open app/User.php file and add the following code- 

open app user.php file

Step 9: Open app/Providers/AuthServiceProvider.php File

After the addition of code, open app/Providers/AuthServiceProvider.php file and again run the code added below- 

open app Providers AuthServiceProvider.php file

Step 10: Change ‘driver' to ‘passport'

Now, open config/auth.php and find ‘guards' => and under this you will get ‘api' => and under this, you need to change ‘driver' to ‘passport'. 

change driver to passport

Step 11: Open routes/api.php

Now, you have to open routes/api.php and run the below-added code just as shown in the screenshot below- 

open routes api.php

Step 12: Create a Controller File

Again, return to the terminal and type php artisan make:controller AuthController. This specific command will help you in creating a controller file that helps in handling different requests for example, login and register.

Step 13: The Final Step

Once the controllers are created, you need to add the below-added code- 

After creating the controller add the below code in it . 

<?php

       namespace AppHttpControllers;

       use IlluminateHttpRequest;

       use IlluminateSupportFacadesAuth;

       use AppUser;

       class AuthController extends Controller {

           public function register(Request $request){

               $request->validate([

                   ‘name' => ‘required|string',

                   'email' => ‘required|string|email|unique:users',

                   ‘password' => ‘required|string|confirmed'

               ]);

               $user = new User([

                   ‘name' => $request->name,

                   'email' => $request->email,

                   ‘password' => bcrypt($request->password)

               ]);

               $user->save();

               return response()->json([

                   ‘message' => ‘Successfully created user!'

               ], 201);

           }

           public function login(Request $request){

               $request->validate([

                   'email' => ‘required|string|email',

                   ‘password' => ‘required|string'

               ]);

               $credentials = request(['email', ‘password']);

               if(!Auth::attempt($credentials))

                   return response()->json([

                       ‘message' => ‘Unauthorized'

                   ], 401);

               $user = $request->user();

               $tokenResult = $user->createToken(‘token');

               $token = $tokenResult->token;

               $token->save();

               return response()->json([

                   ‘access_token' => $tokenResult->accessToken,

                   ‘token_type' => ‘Bearer'

               ]);

           }

           public function get_user(Request $request){

               return response()->json($request->user());

           }

       }

Test your API

You are almost done with the coding part. Now, it's time to test the API. Don't know how to do it? Need not fret! Just follow the below added steps-

  • Open Postman. It is basically a software to test API's. 
  • Now, navigate to the url bar and type http://localhost:3000/api/register, and in the params, write name, email, password, and password_confirmation and their respective values.
  • And for login, type http://localhost:3000/api/login and in params, type email and password along with their respective values. Now, press the return key and you will get your access token.

That's it folks ! This is how you can create your own API's.

Did you know that you can also create custom objects using API?

The Last Say 

Hopefully, you have learned how to create your own API's by following this step-by-step guide. Well! The screenshots and examples covered in this blog cover all the points, which will surely help you to keep a note of each pointer.  

So, what are you waiting for? Feel free to explore the application and use it in a secure way. 

Still need any help in using Laravel or any other web development activities? Get in touch with our web experts. 

Frequently Asked Questions

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

Calling an API using the Laravel PHP framework is a common task, and Laravel provides convenient tools and libraries to make API requests. You can use the HTTP facade to make GET, POST, PUT, DELETE, or other types of HTTP requests to the API.

An API, or Application Programming Interface, is a set of rules, protocols, and tools that allow different software applications to communicate with each other. It defines the methods and data formats that applications can use to request and exchange information, perform specific actions, or access the functionality of another software component, such as an operating system, library, or web service.

Laravel is a versatile framework that provides the tools and features necessary to create RESTful APIs, web applications, and more. When you develop a RESTful API using Laravel, you typically define routes, controllers, and models to handle HTTP requests and responses in accordance with RESTful principles.