Posted on Updated on - Arjun

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 first step. Before installing, Just want to give quick introduction about 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, lets 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 specific version, issue following command from your terminal.

Here “todo” is directory name all files will be downloaded into “todo” folder. Now move control to your project directory(todo) by issuing below command 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 lets add a table columns 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, issue that commands from your project root. These commands will create those tables, and inset sample users and tasks to 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 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 end points 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.

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

    helpful

  • Thank you, that was a precious article!

  • Sooraj J

    cannot work array of tasks

  • gaspan gurero

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

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

  • Muhamad Safii

    Thank you

  • budhi apriyanto

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

    • Mujahid Abbas

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

  • Govind

    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

  • Ahmed Sinan

    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

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

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

    • Anthony Walter

      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

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

  • gvk

    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

    • are you importing “use AppTransformerTaskTransformer;” in your controller

      • gvk

        Yuup. But Still I’m getting same error 😉

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

          • gvk

            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

          • Welcome..sure I will make a post on it

          • gvk

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

          • arjunphp(at)gmail.com

DMCA.com Protection Status