This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

Making a Post API in Laravels


Making an api utilizing laravel may be very easy and makes it a lot simpler for us to develop, it additionally helps you perceive and apply good programming practices.

So on this instance we’re going to make an api on posts, which we’re going to have with authentication and in the long run you will have a problem which I’ll clarify to you later as we advance with the mission!



Beginning with the mission

To create a mission with Laravel from scratch we are going to begin by going to the console and write the next command:

composer create-project --prefer-dist laravel/laravel apiposts
Enter fullscreen mode

Exit fullscreen mode

Now we’ve a mission created we’re going to join it to our database we do that in our .env file:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=apipost
DB_USERNAME=root
DB_PASSWORD=root
Enter fullscreen mode

Exit fullscreen mode

Prepared we’ve our database related now we’re going to create the fashions we want, in Laravel we’ve the migrations which might be the variations of our database. This has many advantages once we develop as a staff since we can know what adjustments have been made within the base and in case of errors we are able to roll again to a earlier model.

Laravel already brings default migrations that we are able to alter to our liking, in our case we are going to create a brand new one as follows:

php artisan make:migration create_posts_table
Enter fullscreen mode

Exit fullscreen mode

Now we’ve our migration however some extra issues are lacking like controller, mannequin, seeders, manufacturing facility, request that can assist us with our mission.
We will create them one after the other with the artisan instructions however Laravel permits us to automate this and create every thing with a single command, we’re going to delete the migration of posts that we’ve created.

And let’s run the command:

php artisan make:mannequin Submit --all
Enter fullscreen mode

Exit fullscreen mode

This command will create Mannequin, manufacturing facility, seeder, requests, controller and coverage.

We’ll use them in a second, however first we’ll go to the database/migrations folder and open the final migration that was completed and we’ll see one thing like this:

<?php

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public perform up()
    {
        Schema::create('posts', perform (Blueprint $desk) {
            $table->id();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public perform down()
    {
        Schema::dropIfExists('posts');
    }
};
Enter fullscreen mode

Exit fullscreen mode

Contained in the up perform we’re going to outline our desk fields, the fields that we’ll use for now can be id, title, content material, deleted_at and the timestamps which might be created_at and updated_at by default.

So our perform would appear to be this:

public perform up()
    {
        Schema::create('posts', perform (Blueprint $desk) {
            $table->id();
            $table->string('title');
            $table->textual content('content material');
            $table->dateTime('deleted_at')->nullable();
            $table->timestamps();
        });
    }
Enter fullscreen mode

Exit fullscreen mode

Prepared now we’ve our migration prepared, now for this to be mirrored in our database we’ve to run a command, do not forget that the database you configured should already be created, however with none desk.

run migrations:

php artisan migrate
Enter fullscreen mode

Exit fullscreen mode

As you’ll be able to see all our tables have names within the plural and our mannequin within the singular as a result of conference utilized by Laravel, I like to recommend that every one the fashions and tables have names in English to observe the conference.

Tables of apipost database

The subsequent factor we’re going to do is fill our publish desk with pretend information to have the ability to develop the listing methodology and never do inserts in our database since it’s tedious, for this we are able to use the Laravel factories so, we’ve already created our manufacturing facility because of the command we used above however don’t be concerned you’ll be able to create others with the command

php aritsan make:manufacturing facility NameFactory

In our databases/factories/PostFactory file we’ve a technique referred to as definition contained in the return we are able to do the next:

public perform definition()
     {
         return [
             'title' => $this->faker->sentence,
             'content' => $this->faker->paragraph,
             'deleted_at' => null,
         ];
     }
Enter fullscreen mode

Exit fullscreen mode

What this may do is use faker to have the ability to fill our desk with pretend information however now we’ve to name it and use this we use it within the database/seeders/DatabaseSeeders file:

<?php

namespace DatabaseSeeders;

use IlluminateDatabaseSeeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the appliance's database.
     *
     * @return void
     */
    public perform run()
    {
        AppModelsPost::manufacturing facility(120)->create();
    }
}

Enter fullscreen mode

Exit fullscreen mode

As you’ll be able to see we use the Submit mannequin and we are saying that it creates 120 data with the manufacturing facility methodology if you happen to use one other model of Laravel the syntax could change however you’ll be able to see it within the official documentation.

You could marvel what the seeders are for, the seeders are the place you’ll be able to insert information into your database utilizing eloquent strategies, which is the orm that Laravel has configured by default. The factories are those that assist us generate some data with pretend information in a large method, passing solely a sure variety of data, as you already realized, a question builder is just not used, it is just sufficient to point the fields and the worth they’ll have.

That’s the reason the factories are referred to as throughout the database seeder, the opposite seeders additionally must be referred to as throughout the database seeder since that is the one one that’s executed once we name them utilizing the command:

php artisan db:seed // Seeders are executed and data can be inserted into our desk
Enter fullscreen mode

Exit fullscreen mode

data of the posts table

Now we all know what migrations, seeders and factories are for, now we are going to begin creating our api routes and strategies.

Within the routes folder we’ve a number of recordsdata, as you’ll be able to see we’ve net.php, api.php, channels and console.

We are going to focus on simply the net and api, the place net is for net routes and api is the one we’re going to use on this tutorial.

within the api.php file we’ve an outlined route which is the next:

Route::middleware('auth:sanctum')->get('/consumer', perform (Request $request) {
     return $request->consumer();
});
Enter fullscreen mode

Exit fullscreen mode

We’re going to delete this and we’re going to create a route as follows:

Route::get('/hi there', perform () {
    return 'Whats up World';
});
Enter fullscreen mode

Exit fullscreen mode

As we are able to see, we prepend the Route class with its methodology, which is the verb that we’ll have on this route because the second parameter, we are able to use a callback and return a textual content.

Now we are going to take a look at this in postman:

To begin the event server we are able to execute the command:

php artisan serve
Enter fullscreen mode

Exit fullscreen mode

call api from postman

Performed however now we should begin creating our routes for our api, we are going to use versioning for our api since this fashion we are going to use an excellent observe and our api can develop with out affecting different initiatives that use it.

We are going to create the routes, Laravel permits us to create routes along with a single line which we are going to do as follows:

Route::useful resource('v1/posts', PostController::class)->solely(['index']);
Enter fullscreen mode

Exit fullscreen mode

We use useful resource to create a number of routes, however since we are going to solely use the index methodology for now, we are going to inform it by way of the one perform that we solely need that route and so we are able to add those we want.

Additionally, you will discover that we add v1 to the endpoint of our assets, that is to have the ability to mutate our api shortly and safely with out different apps that use it breaking sooner or later, for instance, if we wish to change the best way the information is displayed or we wish to take away fields from our api we’d create a useful resource with v2 and thus we are able to higher management how our api has modified over time

Now one thing essential we’re going to create the controller of our posts, we have already got a controller however we aren’t going to make use of it, we’re going to create one other controller with the command:

  php artisan make:controller Api/V1/PostController --api
Enter fullscreen mode

Exit fullscreen mode

Prepared now we’ve our api Controllers and versioned these are positioned within the app/Http/Controllers/Api folder and right here we are able to create the v2, v3 folder as wanted.

Once we created our controller we informed it to be of sort api with the –api flag so we are going to solely have 5 strategies in contrast to regular api controllers which have 7 strategies.

Now we have to change the controller that we reference our path to within the api.php file:

<?php

use AppHttpControllersApiV1PostController;
use IlluminateSupportFacadesRoute;

Route::useful resource('v1/posts', PostController::class)->solely(['index']);
Enter fullscreen mode

Exit fullscreen mode

With doing this we’ve it prepared now we are going to begin creating our primary endpoint

Let’s have a look at what routes we’ve in our laravel and what controller methodology is executed once we name them.

We see this with the command:

php artisan route:listing
Enter fullscreen mode

Exit fullscreen mode

Routes

As we are able to see we’ve a number of default routes however the one which pursuits us is the one in place 5 as you’ll be able to see it’s referred to as /api/v1/posts and as you’ll be able to see it has this “ApiV1PostController@index” because of this once we name this route will execute the index methodology so that’s the place we’re going to write the logic to answer the consumer.

We’re going to make a name to our database and we’re going to make the data come ordered and paginated, then we are going to return it as a response of sort json.

The strategy can be one thing like this:

  public perform index()
     {
         $posts = Submit::newest()->paginate();
         return response()->json($posts);
     }
Enter fullscreen mode

Exit fullscreen mode

On this method we return the posts as json to the consumer so, now we are going to see how the information arrives from the postman:

call api from postman

Prepared we have already got the response in a paginated method now we’re going to work on our second endpoint which is the present methodology to indicate a single publish in line with the id of the parameters, for this we should in our api.php add one other methodology other than the index that this could be the present and we are going to change our useful resource methodology to apiResource this in order that it doesn’t create extra pointless routes because the useful resource has 7 routes, this one solely has 5

Route::apiResource('v1/posts', PostController::class)->solely(['index', 'show']);
Enter fullscreen mode

Exit fullscreen mode

Now if we listing our routes we are going to see a brand new one that’s:

  GET|HEAD api/v1/posts/{publish} ........................................... ............................................ posts.present › Api V1PostController@present
Enter fullscreen mode

Exit fullscreen mode

As we are able to see, this retains a {publish}, this refers to the truth that we should move the id of our publish to have the ability to present the information.

So let’s go to the controller to change the present methodology:

 public perform present($id)
    {
        //
    }
Enter fullscreen mode

Exit fullscreen mode

First we’ve to search for the publish in our database after which return it as a response.

We’ve got a parameter which is the id that the consumer places within the url, and due to eloquent and the simplicity of laravel we are able to do the next:

public perform present(Submit $publish)
    {
        return response()->json($publish);
    }
Enter fullscreen mode

Exit fullscreen mode

Including the Mannequin as the kind of the variable, Laravel understands this and offers you the file to which the mannequin belongs.

Now let’s have a look at in postman:

call method show from postman

That simple we have already got the present methodology of our api.

Now we are going to see the delete methodology. The identical course of we add the strategy to our useful resource in api.php and go to the destroy methodology in our controller.

Route::apiResource('v1/posts', PostController::class)->solely(['index', 'show', 'destroy']);
Enter fullscreen mode

Exit fullscreen mode

PostController :

 public perform destroy($id)
    {

    }
Enter fullscreen mode

Exit fullscreen mode

Right here we are able to do the identical as within the present make Laravel carry us the file mechanically:

 public perform destroy(Submit $publish)
    {
        $post->deleted_at = now();
        $post->save();
        return response()->json(['message' => 'Post deleted'], Response::HTTP_NO_CONTENT);
    }
Enter fullscreen mode

Exit fullscreen mode

As you’ll be able to see we solely reassign the worth of the deleted_at discipline with the now() perform and the logical deletion is finished, we don’t delete it from the database. We return null and as a second parameter we move a no content material code which is 204 we are able to ship it as a quantity however I desire to make use of Response you’ll be able to see the remainder of the code within the official Laravel doc.

Let’s have a look at this within the postman:

call method destroy from postman

Now we are going to add that in our index methodology solely the posts that aren’t deleted are seen, so we are going to add a situation:

  public perform index()
     {
         $posts = Submit::the place('deleted_at', null)->newest()->paginate();
         return response()->json($posts);
     }
Enter fullscreen mode

Exit fullscreen mode

On this method this methodology is solved and the deleted posts will not be proven.

Now we are going to add that in our present methodology we don’t need the ifno of a deleted publish to be seen, so we are going to add an if:

public perform present(Submit $publish)
     {
         if ($post->deleted_at) {
             return response()->json(['message' => 'Post have been deleted'], Response::HTTP_NOT_FOUND);
         } else {
             return response()->json($publish);
         }
     }
Enter fullscreen mode

Exit fullscreen mode

We have already got solved this different methodology that simple.

However what occurs if we do the next:

error in found posts

As you’ll be able to see we’ve an html error which isn’t proper, so how can we repair this?

At any time when we devour an api in Laravel we should move the property within the headers

Settle for : utility/json
Enter fullscreen mode

Exit fullscreen mode

With this, Laravel already is aware of that it ought to ship us the error in json, so now we are going to get hold of the next response:

error not found in json

We’ve got an issue which is that I do not wish to present this error on this option to the customers so we are going to change the present perform on this method:

public perform present($id)
     {
         attempt {
             $publish = Submit::the place('deleted_at', null)->findOrFail($id);
             return response()->json($publish);
         } catch (ModelNotFoundException $e) {
             return response()->json(['message' => $e->getMessage()], Response::HTTP_NOT_FOUND);
         }
     }
Enter fullscreen mode

Exit fullscreen mode

As you’ll be able to see, we are actually utilizing the findOrFail methodology, this may throw us a ModelNotFoundException sort exception and we are going to return the message with a not discovered code.

On this method we get hold of a shorter message and we don’t element the consumer a lot for safety causes.

{
    "message": "No question outcomes for mannequin [AppModelsPost] 1" // Submit deleted
}
Enter fullscreen mode

Exit fullscreen mode

Now we are able to do the identical within the destroy methodology.

public perform destroy($id)
    {
        attempt {
            $publish = Submit::the place('deleted_at', null)->findOrFail($id);
            $post->deleted_at = now();
            $post->save();
            return response()->json(null, Response::HTTP_NO_CONTENT);
        } catch (ModelNotFoundException $e) {
            return response()->json(['message' => $e->getMessage()], Response::HTTP_NOT_FOUND);
        }

    }
Enter fullscreen mode

Exit fullscreen mode

We’re nearly completed, now we’re going to format our responses, since we are actually returning the mannequin and this isn’t completed in Laravel on this method. We’ll do it utilizing assets and collections.
The assets assist us to format our mannequin and thus return the collections, they’re precisely the identical however it’s to return collections, we see it in observe. Now we are going to create a useful resource as follows.

php artisan make:useful resource V1/PostResource
Enter fullscreen mode

Exit fullscreen mode

Right here we will even apply versioning since we are able to mutate these assets as our api grows.

Now we go to the file app/Http/Assets/V1/PostResource:

<?php

namespace AppHttpResourcesV1;

use IlluminateHttpResourcesJsonJsonResource;

class PostResource extends JsonResource
{
    /**
     * Remodel the useful resource into an array.
     *
     * @param  IlluminateHttpRequest  $request
     * @return array|IlluminateContractsSupportArrayable|JsonSerializable
     */
    public perform toArray($request)
    {
        return [
            'title' => $this->title,
            'content' => $this->body,
            'created_at' => $this->created_at,
        ];
    }
}
Enter fullscreen mode

Exit fullscreen mode

We make a return and assign keys and what discipline we wish to be assigned I’ll go away it this fashion and now we’re going to use it in our PostController:

public perform present($id)
     {
         attempt {
             $publish = Submit::the place('deleted_at', null)->findOrFail($id);
             return new PostResource($publish);
         } catch (ModelNotFoundException $e) {
             return response()->json(['message' => $e->getMessage()], Response::HTTP_NOT_FOUND);
         }
     }
Enter fullscreen mode

Exit fullscreen mode

Right here we return a brand new occasion of the publish useful resource do not forget that we are able to solely move one file to our useful resource, for a number of data we’re going to create a group however for this I’ll use a model 2 of my api and we are going to perceive some great benefits of this observe.

First we are going to create the routes useful resource in api.php :

<?php

use AppHttpControllersApiV1PostController as PostControllerV1;
use AppHttpControllersApiV2PostController as PostControllerV2;
use IlluminateSupportFacadesRoute;

Route::apiResource('v1/posts', PostControllerV1::class)->solely(['index', 'show', 'destroy']);
Route::apiResource('v2/posts', PostControllerV2::class)->solely(['index']);
Enter fullscreen mode

Exit fullscreen mode

As you’ll be able to see, I create the route solely with the index methodology and I create one other controller within the V2 folder of controllers and I assign an alias to it to keep away from battle within the imports, now we create the controller:

php artisan make:controller Api/V2/PostController --api
Enter fullscreen mode

Exit fullscreen mode

Now we’re going to do the index methodology identical to within the PostController model 1.

// V2/PostController
public perform index()
    {
        $posts = Submit::the place('deleted_at', null)->newest()->paginate();
        return response()->json($posts);
    }
Enter fullscreen mode

Exit fullscreen mode

Prepared we’ve it let’s have a look at the postman:

call v2 api method index from postman

As you’ll be able to see it’s precisely the identical however now in model 2 I solely wish to ship the id and the title so for this we’re going to create the gathering that can assist us give this a construction:

php artisan make:useful resource V2/PostCollection
Enter fullscreen mode

Exit fullscreen mode

Now we go to the File app/Http/Assets/V2/PostCollection

and we must do one thing like this:

public perform toArray($request)
    {
        return [
            'data' => $this->collection,
            'target' => [
                'organization' => 'com.jordan',
                'author' => [
                    'name' => 'Jordan',
                    'email' => 'jordan@mail.com',
                ],
            ],
            'sort' => 'publish',
        ];

    }
Enter fullscreen mode

Exit fullscreen mode

As you’ll be able to see, we add extra data and throughout the information property I would like it to return all the information of the gathering. We use this in V2/PostController:

// V2/PostController
public perform index()
    {
        $posts = Submit::the place('deleted_at', null)->newest()->paginate();
        return new PostCollection($posts);
    }
Enter fullscreen mode

Exit fullscreen mode

call v2/api method index from postman

call v2/api method index from postman

However we’ve an issue, though our construction has modified, all of the publish fields are nonetheless displayed. To unravel this, we create a v2 useful resource and we are going to use it in our assortment:

php artisan make:useful resource V2/PostResource
Enter fullscreen mode

Exit fullscreen mode

And we modify it:

<?php

namespace AppHttpResourcesV2;

use IlluminateHttpResourcesJsonJsonResource;

class PostResource extends JsonResource
{
    /**
     * Remodel the useful resource into an array.
     *
     * @param IlluminateHttpRequest $request
     * @return array|IlluminateContractsSupportArrayable|JsonSerializable
     */
    public perform toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
        ];
    }
}
Enter fullscreen mode

Exit fullscreen mode

Now we’ve to inform our assortment to make use of this useful resource:

<?php

namespace AppHttpResourcesV2;

use IlluminateHttpResourcesJsonResourceCollection;

class PostCollection extends ResourceCollection
{

    public $collects = PostResource::class;
    /**
     * Remodel the useful resource assortment into an array.
     *
     * @param IlluminateHttpRequest $request
     * @return array|IlluminateContractsSupportArrayable|JsonSerializable
     */
    public perform toArray($request)
    {
        return [
            'data' => $this->collection,
            'target' => [
                'organization' => 'com.jordan',
                'author' => [
                    'name' => 'Jordan',
                    'email' => 'jordan@mail.com',
                ],
            ],
            'sort' => 'publish',
        ];

    }
}
Enter fullscreen mode

Exit fullscreen mode

On this method we resolve our drawback.

call v2/posts method index from postman

So the purposes that devour our previous api is not going to have issues or will fall.

On this method we’ve made an api with a number of strategies making use of good programming practices as really useful by the laravel documentation. The problem is that you just end the replace and retailer strategies of the api in addition to the opposite strategies of model 2.

If one thing is just not clear to you, you’ll be able to remark and I’ll enable you with pleasure.

You’ll find the whole code within the following github repository

The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

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

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?