Laravel API Resource Tutorial

Laravel API Resource Tutorial

In this tutorial we’ll build a full json crud api using Laravel and the new Eloquent API Resources feature. This approach is used when you want to build the entire back end of your application using Laravel, while leaving the front end to Vue, React, or Angular. By using Laravel and Eloquent API Resources, you can format your data responses however you like while also adding meta information, pagination links and information, custom data wrapping, conditional attributes, and relationships.


Local Development Environment

Here we just set up a new project named lpgvue to get started. Why that name? It’s short for Laravel Play Ground / Vue. Essentially we just want to have a local development environment that gets us set up with the latest and greatest version of Lavavel so we can build and tinker as we like.

composer global require laravel/installer
composer create-project –prefer-dist laravel/laravel lpgvue
composer require –dev barryvdh/laravel-ide-helper
php artisan ide-helper:generate

With the commands above, we now have a nice fresh Laravel project to work with.


Creating Data To Work With

Laravel makes it really easy to scaffold out tables to hold sample data to work with. In addition to Migrations, you can set up database seeding to quickly fill those tables up with data so that you can test your API.


Add A Database

First we add a database to our server using a graphical user interface tool. Check out setting up your database for Laravel for more info.
create database on homestead

We are using Homestead of course, the premier Vagrant Box available for local development environments. That means our user name and password are homestead and secret respectively. We do however need to specify the database we just created in the env file.
set env mysql credentials


Adding A Migration

We can use Artisan to generate a migration that will provide the schema for a posts table which will hold our posts.

php artisan make:migration create_posts_table –create=posts

In the highlighted lines below, we add fields for the title and body of the posts.
database/migrations/xxxx_xx_xx_xxxxxx_create_posts_table.php


Database Seeding

To enable database seeding, we can again use Artisan to make a seeder class for us.

php artisan make:seeder PostsTableSeeder

The code we add below specifies to make 25 sample posts in the database.
database/seeds/PostsTableSeeder.php

We need to also update the DatabaseSeeder.php file to now make use of the PostsTableSeeder class.
database/seeds/DatabaseSeeder.php

php artisan make:factory PostFactory

Finally, we need a Factory that allows us to specify the shape of the data that will populate the database. We want the title to use 40 characters and the body to use 200 characters. To set something like this up, just use these steps.

database/factories/PostFactory.php


Create A Data Model

The application will also need a Model for the posts table. We could have done the model and the migration in one shot, but this approach will also work.

php artisan make:model Post

With that, all of the data set up is complete. Now, we want to migrate the database, then seed the database. Here we go!

php artisan migrate
php artisan db:seed

You should see messages about the migrations running successfully and database seeding completing successfully. Now when viewing the database using a GUI tool, all of the sample data is now populated.

laravel database seeding


Building Controllers and Routes

Now we get to start building the actual code and files that will power the REST API! First up, we need a resource based Post controller. Artisan makes this easy.


Create A Controller

php artisan make:controller PostController –resource

The resulting file is below with the comments and a couple of methods removed. For our little tutorial we’ll just use index(), store(), show(), and destroy().
app/Http/Controllers/PostController.php


Configure The Routes File

Laravel gives you two entry points for routes. One is for standard web requests, and the other is tailored for api requests. We are building an API here so we need to populate our routes in the api.php file. The code is below with comments that explain the purpose for each route.

routes/api.php

Notice that there are two routes that point to the same store() method. This is because the store() method can either update a post when using the PUT http verb, or create a new post when using the POST http verb. Pretty cool stuff.


Create An API Resource

Now we can start working with API Resources in Laravel. The documentation describes this feature as a type of transformation layer that lives between the data model layer and the JSON response layer. We can go ahead and create a new API Resource like so.

php artisan make:resource Post

The command above creates a new Resources folder and populates the following file.

app/Http/Resources/Post.php

This file is your Transformer of sorts which allows you to customize the JSON response data of your api in several ways. We can put it to use now.

Now we can visit http://lpgvue.io/api/posts in the browser and see the nicely formatted JSON output. The data is nicely contained in the data property, along with links for pagination and meta information. Very cool!


Customizing The Returned Data

The generated resource we created above can be customized so that you can return exactly what you like from the API. By modifying the return statement like we do below, only the id, title, and body are now sent which cleans things up just a touch.

app/Http/Resources/Post.php

Here is the resulting output when visiting http://lpgvue.io/api/posts


Database Field To API Response Mapping

This feature of Laravel’s API Resource is really cool. Your database fields do not have to exactly match the keys used in the JSON responses. Of course, it is probably best if they do for everyone’s sanity. However, if you need to use custom properties in the response data you can do that. Let’s see how that works.

app/Http/Resources/Post.php

The JSON Response from the API now uses those custom properties.


Returning A Single Resource

Now let’s look at returning a single resource in the show() method of our controller.
app/Http/Controllers/PostController.php

This is the resulting output when visiting http://lpgvue.io/api/post/5


Adding Additional Data

To add some additional data to the responses sent such as the api version and what not, you can set up the with() method like we do here.
app/Http/Resources/Post.php

When visiting http://lpgvue.io/api/post/5 we now see that additional meta data in the response. So we can see this is a really powerful way to customize exactly what you want the API to produce.


Create and Update

The same endpoint can be used to either update a post, or create a new one entirely. The only difference is the HTTP verb used when making the request. If a PUT request is used, then it is assumed that a Post will be updated. If a POST request is used, that means a new Post is being created. The code here allows for either a Post update or a Post creation using the same store() method in the PostController.


Testing A Post Update

To test an API when you don’t yet have a formal front end built, you can use a great tool like Postman. Testing with Postman allows us to send API requests to the application using the HTTP verb of our choice. Here we will set up a PUT request to the http://lpgvue.io/api/post endpoint. This will allow us to update a post. The first step is to set the request type as PUT and add a header to the request to specify content type of application/json.
laravel and postman api put request

The second step is to click on the Body tab, select raw, and add the json payload to the request. In order to update a post we need to specify the id, title, and body with data to be updated.
postman json application payload example

The final step is to click that Send button and if everything goes right, you will see a response with the updated post in the payload.
200ok response to put request


Testing A Post Creation

Now that we are familiar with the basic workflow in Postman, we should be able to easily create a new Post as well. To do this, we can set up a POST request to the same endpoint of http://lpgvue.io/api/post that we just used in the update example. Notice we set the json payload to include a new title and body for the post. We do not need to include an id, as the application will allocate a new id automatically.
create new resource laravel api postman

When you click Send, Postman will fire off that POST request and you should get back a 201 Created response with the newly created post in the body of the response.
201 created new resource success

Viewing the posts table in our database directly also shows that new post that got created.
new post via api worked


Deleting A Resource

To round out our API and allow for full CRUD functionality via the JSON Rest Api, we can add the ability to delete a Post.

Now, let’s try deleting the Post with the id of 5. The delete request is very easy. All you have to do is provide the endpoint to hit, including the id, and hit Send. Make sure the HTTP verb type is set to DELETE.
laravel rest delete request

Now when we visit http://lpgvue.io/api/posts to view all the posts, notice that they get listed in order as 1, 2, 3, 4, and then 6. So that means our delete of post id 5 worked.


More About Laravel API Resources


Laravel API Resource Tutorial Summary

In this tutorial we built a full JSON CRUD API using the Laravel API Resource feature. We can see that it is really easy to get a backend API set up using Laravel and the many tools it gives us. Next up we’ll take a look at building a Vue Front End that can consume our API.