Categories
Laravel

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.

By Arjun

I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.

36 replies on “Create REST API with the Laravel 5.5”

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

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

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;

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!

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

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

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

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.

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?

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?

Leave a Reply

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