Create REST API with the Laravel 5.5

This tutorial provides an example of building a complete RESTful API using Laravel 5.5.* Framework. You gonna use the different HTTP methods during the REST API development, quick introduction about each method.

GET to retrieve data
POST to add data
PUT to update data
DELETE to delete data

Each method as a purpose isn’t it?. Let’s download and install Laravel 5.5.* Framework as the first step. Before installing, Just want to give a quick introduction to the app which you are going to build is TODO application. You can search for todos, add a todo to list, update and delete todos. Exciting right, let’s start your journey-

Create REST applications with the Laravel framework

STEP – 1 (Download and install Laravel 5.5.* Framework)

You can setup project with latest version by issue following command from your terminal.

If you want to setup project with a specific version, issue following command from your terminal.

Here, “todo” is project name, above command create a directory with project name and downloads all files inside it. Now move control to your project directory(todo) by issuing below command and serve application by using artisan command.

It will show http://localhost:8000/ URL if it is up successfully.

That’s about installation and congratulation, you have finished step one successfully. Let’s create make database configurations.

Configure Your Database

Create a database and edit .env and fill it with your database settings. This article assumes a MySQL database.

Create Migration File

Below command set up the basic migration scripts that we’ll be using to create the database table.

Now required migration file is in place, so let’s add a table column as shown below.

Edit app/database/migrations/SOME_DATE_create_tasks_table.php and edit and update the up() and down() methods:

Add Sample Users and todos

We gonna use Laravel’s seeds to create a few sample users and todos.

Let issue following commands to create seeder class from your root of the project.

Generated seeders by the above commands will be placed in the database/seeders directory. In our case, we have two seed files called UsersTableSeeder.php and TasksTableSeeder.php.

Update seeder run methods as shown below
UsersTableSeeder.php

TasksTableSeeder.php

Next, make sure that seeder class gets run when the database is seeded. Edit app/database/seeds/DatabaseSeeder.php

Add Model Factories

Next, create app/database/factories/UserFactory.php and app/database/factories/TaskFactory.php and place below code blocks

Create Task Model

Laravel comes with a User model setup, so let’s create a model for our tasks table.

Create a modal with

since you are following Laravel naming conventions you don’t have to change anything in the task model.

Run the Migrations

Below are the Laravel’s artisan commands and issue below commands from your project root. These commands will create those tables and inset sample users and tasks to the database.

api-response

When building an API it is common for people to just grab stuff from the database and pass it to json_encode(). This might be passable for “trivial” APIs but if they are in use by the public, or used by mobile applications then this will quickly lead to inconsistent output. So to avoid this problems we gonna use ellipsesynergie/api-response package. This package handles the response properly in your API and this package uses Fractal.

Fractal – Fractal provides a presentation and transformation layer for complex data output, the like found in RESTful APIs, and works really well with JSON. Think of this as a view layer for your JSON/YAML/etc.

Install package with the composer, issue the command from your root of the project:

Add this following service provider to your config/app.php file.

Create Task Controller

Now define your api routes in routes/api.php

Lets update task controller with below code, please read comments for better understanding.

Create a Transformer folder in your app directory and create a file called app\Transformer\TaskTransformer.php with below code

That’s it.Rest APIs are ready now you can access the APIs with below-shown endpoints using advance reset client or Curl.

Start the server with php artisan serve or use other other methods.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

0 0 votes
Article Rating
Subscribe
Notify of
guest
36 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Shany Mathew
Shany Mathew
4 years ago

helpful

عيسى محمد علي

Thank you, that was a precious article!

Sooraj J
Sooraj J
4 years ago

cannot work array of tasks

gaspan gurero
gaspan gurero
4 years ago

how to use cacth it(json) in laravel again?

Vladimir Nikolic
4 years ago

You have a typo i would say in TaskController, line 13.
class TaskController extends Controller
{
protected $respose;

Muhamad Safii
Muhamad Safii
4 years ago

Thank you

budhi apriyanto
budhi apriyanto
4 years ago

so how to access api from browser without use php artisan serve, I try use /api/task not found result in browser?

Mujahid Abbas
Mujahid Abbas
4 years ago

You can access api information using an app Postman. Go to the your api url and change whatever request (post, get) .

Govind
Govind
4 years ago

http://127.0.0.1:8000/tasks This url and i am get the problem ..
Sorry, the page you are looking for could not be found.
NotFoundHttpException in RouteCollection.php line 161:

please solve this error.. Thank you

Rolando J. Valencia Torres
Rolando J. Valencia Torres
4 years ago
Reply to  Govind
Ahmed Sinan
Ahmed Sinan
4 years ago

This is the Error I get

FatalErrorException in TaskController.php line 56:
Call to a member function withPaginator() on null

i do have this on the top as well,
use EllipseSynergieApiResponseContractsResponse;

Eduardo Diaz
Eduardo Diaz
4 years ago

Error, when you say create a transformer, do not forget extends:
class TaskTransformer extends TransformerAbstract

https://uploads.disquscdn.com/images/a0587018259f32f19c3083a526cec0a477e3c387d12e1d3d2e7dee464dba3cae.png

Anthony Walter
Anthony Walter
3 years ago
Reply to  Eduardo Diaz

Thank you for this!!!! I was thinking this was the error when I was getting cannot find “name:SetCurrentScope()”, but this post made me certain enough to change it and my JSON is now working woot!

gvk
gvk
3 years ago

When run this URL http://myapp.dev/api/task
I’m getting error like this

gvk
gvk
3 years ago

When hit the URL http://myapp.dev/api/task
I’m getting like this

Whoops, looks like something went wrong.

1/1
FatalThrowableError in TaskController.php line 27:
Class ‘AppHttpControllersTransformer’ not found
in TaskController.php line 27
at TaskController->index()
at call_user_func_array(array(object(TaskController), ‘index’), array()) in Controller.php line 55
at Controller->callAction(‘index’, array()) in ControllerDispatcher.php line 44
at ControllerDispatcher->dispatch(object(Route), object(TaskController), ‘index’) in Route.php line 189
at Route->runController() in Route.php line 144
at Route->run(object(Request)) in Router.php line 653
at Router->IlluminateRouting{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->IlluminateRouting{closure}(object(Request)) in SubstituteBindings.php line 41
at SubstituteBindings->handle(object(Request), object(Closure)) in Pipeline.php line 137
at Pipeline->IlluminatePipeline{closure}(object(Request)) in Pipeline.php line 33
at Pipeline->IlluminateRouting{closure}(object(Request)) in ThrottleRequests.php line 49
at ThrottleRequests->handle(object(Request), object(Closure), ’60’, ‘1’) in Pipeline.php line 137
at Pipeline->IlluminatePipeline{closure}(object(Request)) in Pipeline.php line 33
at Pipeline->IlluminateRouting{closure}(object(Request)) in Pipeline.php line 104
at Pipeline->then(object(Closure)) in Router.php line 655
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 629
at Router->dispatchToRoute(object(Request)) in Router.php line 607
at Router->dispatch(object(Request)) in Kernel.php line 268
at Kernel->IlluminateFoundationHttp{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->IlluminateRouting{closure}(object(Request)) in CheckForMaintenanceMode.php line 46
at CheckForMaintenanceMode->handle(object(Request), object(Closure)) in Pipeline.php line 137
at Pipeline->IlluminatePipeline{closure}(object(Request)) in Pipeline.php line 33
at Pipeline->IlluminateRouting{closure}(object(Request)) in Pipeline.php line 104
at Pipeline->then(object(Closure)) in Kernel.php line 150
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 117
at Kernel->handle(object(Request)) in index.php line 53

arjun
3 years ago
Reply to  gvk

are you importing “use AppTransformerTaskTransformer;” in your controller

gvk
gvk
3 years ago
Reply to  arjun

Yuup. But Still I’m getting same error 😉

arjun
3 years ago
Reply to  gvk

Here is the source code, its working I have verified it -https://arjunphp.com/assets/uploads/2017/09/create-rest-laravel-framework.zip

gvk
gvk
3 years ago
Reply to  arjun

Thanks bro. Got it. Please help me and share the materials which are helpful to learn Laravel ReSTful API. Because I’m looking forward to work with Laravel API. If you have any help me. Thanks

arjun
3 years ago
Reply to  gvk

Welcome..sure I will make a post on it

gvk
gvk
3 years ago
Reply to  arjun

Hi Arjun, Can I have your mail id….I have some work with you..

arjun
3 years ago
Reply to  gvk

arjunphp(at)gmail.com

Amir Khan
Amir Khan
2 years ago
Reply to  arjun

i have downloaded your source code but where is database xml file how i import your database and for get all data what would be url path ???

arjun
2 years ago
Reply to  Amir Khan

Amir just run php artisan migrate command from your project root folder after configuring database settings in .env file(app/database/migrations/). The migrate command will read you db migration files and create tables in the database.

Amir Khan
Amir Khan
2 years ago
Reply to  arjun

hello arjun thanx for reply but when i run php artisan command it give me error that require vendor/autoload.php and when we check our webservice in postman what we will use url?

arjun
2 years ago
Reply to  Amir Khan

you have to run the $ composer install to download project dependencies

Luan Lary
Luan Lary
3 years ago

This is the best tutorial of laravel that ever i seen

Sanchit Mahajan
Sanchit Mahajan
3 years ago

Good tutorial… But how to store image? Thank You.

Vince Kronlein
3 years ago

There’s no need for fractal with 5.5. You can use the API Resources included in the framework: https://laravel.com/docs/5.5/eloquent-resources.

Great article though. Thanks.

arjun
3 years ago
Reply to  Vince Kronlein

Thanks for the comments, here is the post with API Resources –
https://arjunphp.com/how-to-create-apis-in-laravel-5-5-using-api-resources/

Vince Kronlein
3 years ago
Reply to  arjun

NICE!

Jean Paul Cahuana Pinto
Jean Paul Cahuana Pinto
3 years ago

Really nice. but I think put/post will be better like this:

public function store(Request $request) {
if ($request->isMethod(‘put’)) {
//Get the task
$task = Task::find($request->task_id);
if (!$task) {
return $this->response->errorNotFound(‘Task Not Found’);
}
$task = new Task;
$task->id = $request->input(‘task_id’);
} else {
$task = new Task;
}

$task->name = $request->input(‘name’);
$task->description = $request->input(‘description’);
$task->user_id = 1; //$request->user()->id;

if($task->save()) {
return $this->response->withItem($task, new TaskTransformer());
} else {
return $this->response->errorInternalError(‘Could not updated/created a task’);
}
}

What do you think?

arjun
3 years ago

It’s not correct approach, in 404 case those line will not execute and if it find the record with the given ID, you are recreating task object and assigning ID.

willer silva de morais
willer silva de morais
3 years ago

Congratulations, Excellent tutorial, Thank you!

DMCA.com Protection Status
36
0
Would love your thoughts, please comment.x
()
x