Laravel API: Create and Check an API in Laravel

by | May 9, 2023 | Etcetera | 0 comments

Laravel Eloquent is a simple approach to have interaction along side your database. It’s an object-relational mapper (ORM) that simplifies the complexities of databases via providing a model to engage with tables.

As such, Laravel Eloquent has superb tools for rising and checking out APIs to reinforce your development. In this hands-on article, you’ll see how easy it’s to create and test APIs the use of Laravel.

In this demonstration, you’ll get began via creating a model that you just’ll have the ability to use to build the API and database table. Then, you’ll see learn how to add a controller as a business commonplace sense layer and a path to complete the API. You’ll then learn how to perform checking out APIs the use of Postman previous to in any case focusing on authentication and error coping with.

Must haves

To get started, proper right here’s what you’ll need:

API Basics

Get began via rising a brand spanking new Laravel project the use of composer:

composer create-project laravel/laravel laravel-api-create-test

To start out out the server, execute the following command, which runs the application server on port 8000:

cd laravel-api-create-test
php artisan serve

You’ll have to see the following computer screen:

The Laravel landing page

Then, create a model with a -m flag for the migration the use of the code underneath:

php artisan make:model Product -m

Now reinforce the migration record to include the specified field. Add title and description fields for the product model and the ones two table fields throughout the database/migrations/{date_stamp}_create_products_table.php record.


The next step is to make the ones fields fillable. Within app/Models/Product.php, make title and description fillable fields.

secure $fillable = ['title', 'description'];

Consider you have got the following viral app concept? Here is how you’ll be able to briefly create and check your API ⬇Click on to Tweet

How To Create a Controller

Now, create a controller record for the product via executing the following command. This may occasionally every now and then create the app/Http/Controllers/Api/ProductController.php record.

php artisan make:controller ApiProductController --model=Product

Now, add the commonsense for rising and retrieving the products. Throughout the index way, add the following code to retrieve all of the products:

$products = Product::all();
return response()->json([
    'status' => true,
    'products' => $products

After that, you’ll have to add a StoreProductRequest class for storing the new products throughout the database. Add the following class at the top of the an identical record.

public function store(StoreProductRequest $request)
    $product = Product::create($request->all());

    return response()->json([
        'status' => true,
        'message' => "Product Created successfully!",
        'product' => $product
    ], 200);

Now, you’ll create the request, which you’ll have the ability to do via executing the following command:

php artisan make:request StoreProductRequest

If you want to add validations, you’ll have the ability to use the app/Http/Requests/StoreProductRequest.php record. For this demonstration, there aren’t any validations.

See also  ChatGPT: The entirety You Wish to Know Proper Now

How To Create a Route

The entire step previous to checking out the API is together with a path. To do so, add the following code throughout the routes/api.php record. Add the use statement at first of the record and the Route statement throughout the body:

use AppHttpControllersApiProductController;
Route::apiResource('products', ProductController::class);

Quicker than you get began checking out the API, ensure that the products table is in your database. If it doesn’t exist, create one the use of a control panel like XAMPP. Then again, you’ll have the ability to execute the following command to migrate the database:

php artisan migrate

How To Take a look at an API

Quicker than checking out the API, ensure that the authorize way throughout the app/Http/Requests/StoreProductRequest.php is able to return true.

Now, you’ll have the ability to create a brand spanking new product the use of Postman. Get began via hitting a POST request to this URL: Because of it’s a POST request for rising a brand spanking new product, you’ll have to move a JSON object with a reputation and description.

    "description":"Easiest Apples of the field"
Creating a new product in Postman
Rising a brand spanking new product in Postman

After clicking the Send button, you’ll have to see the following:

Postman after clicking Send
After clicking on Send

Now, fetch the created products the use of the GET request. The URL is the same. The results will seem to be the following:

The products fetched by the GET request.
The products fetched during the GET request.

How To Authenticate an API Using Sanctum

Authentication is the most important when securing an API. Laravel makes it easy via providing the potential of the Sanctum token, which you’ll have the ability to use as middleware. It secures the API the use of tokens generated when the individual logs in the use of the correct credentials. Remember that shoppers can’t get right to use the secured API and no longer the usage of a token.

See also  Consistent Touch E mail Advertising: A Detailed Evaluate

The first step to together with authentication is so that you can upload a Sanctum package the use of the code underneath:

composer require laravel/sanctum

Then, publish the Sanctum configuration record:

php artisan dealer:publish --provider="LaravelSanctumSanctumServiceProvider"

After that, add Sanctum’s token as middleware. Throughout the app/Http/Kernel.php record, use the following class and trade middlewareGroups with the following code throughout the secure middleware groups’ API.

use LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful;
secure $middlewareGroups = [
    'web' => [
        // IlluminateSessionMiddlewareAuthenticateSession::class,

    'api' => [

The next step is to create a UserController and add the code to get the token to authenticate.

php artisan make:controller UserController

After rising the UserController, navigate to the app/Http/Controllers/UserController.php record and trade the prevailing code with the following code:

        // print_r($knowledge);
            if (!$particular person || !Hash::check out($request->password, $user->password)) {
                return response([
                    'message' => ['These credentials do not match our records.']
                ], 404);
             $token = $user->createToken('my-app-token')->plainTextToken;
            $response = [
                'user' => $user,
                'token' => $token
             return response($response, 201);

Quicker than you’ll have the ability to test the authentication, create an individual the usage of seeders. The following command creates a UsersTableSeeder record.

php artisan make:seeder UsersTableSeeder

Throughout the database/seeders/UsersTableSeeder.php record, trade the prevailing code with the following code to seed the individual:

            'name' => 'John Doe',
            'email' => '',
            'password' => Hash::make('password')

Now run the seeder the use of this command:

php artisan db:seed --class=UsersTableSeeder

The rest step left throughout the authentication drift is to use the created middleware to protect the path. Navigate to the routes/api.php record and add the products path throughout the middleware.

use AppHttpControllersUserController;

Route::workforce(['middleware' => 'auth:sanctum'], function () {
    Route::apiResource('products', ProductController::class);


After together with a trail to the middleware, you’ll get an inside server error if you happen to try to fetch the products.

See also  3 Eye-Catching Gradients You Can Apply to Your Fullwidth Header Module with Divi’s Gradient Builder
An internal server error after adding a route
An inside server error after together with a path

On the other hand when you log in, get a token, and use it throughout the header, it’s going to authenticate you and get began operating. You’ll send a POST request to with the following body:

Successful authentication and the Bearer token
A luck authentication

Use the token received as a Bearer token and add it for the reason that Authorization header.

Adding the Bearer token as the Authorization header
Together with the Bearer token for the reason that Authorization header

How To Care for API Errors

Each time you send a request to the server, it responds. With the response, it moreover sends a standing code consistent with the nature of the response. For example, a 200 status code implies that the request has succeeded, and a 404 signifies that the server can’t to search out the requested helpful useful resource.

On the other hand, a status code isn’t enough. A human-readable error message is wanted. Laravel comes with many ways to deal with errors. You’ll use a try-catch block, the fallback way, or send a custom designed response. The following code you added to the UserController demonstrates this.

if (!$particular person || !Hash::check out($request->password, $user->password)) {
    return response([
        'message' => ['These credentials do not match our records.']
    ], 404);

Center of attention at the a laugh portions of API dev with out being worried in regards to the complexities of its database. Here is how 🚀Click on to Tweet


Laravel’s Eloquent Type makes it simple to create, validate, and test APIs. Its object-relational mapping provides a easy technique to interacting with the database.

Additionally, appearing as middleware, Laravel’s Sanctum token let you to secure your APIs in brief.

And if you want to have further optimization, Kinsta’s Database Web hosting answer simplifies setting up and managing databases for your entire web projects.

The submit Laravel API: Create and Check an API in Laravel gave the impression first on Kinsta®.

WP Hosting

[ continue ]

WordPress Maintenance Plans | WordPress Hosting

read more


Submit a Comment

Your email address will not be published. Required fields are marked *