Scaffold a laravel api

This is a quick scaffold solution for setting up a simple laravel api.

This tutorial does not include more advanced api requirements such as user authentication or a database connection. It also does not indicate how to send data through the api.

Prerequisites

You must have php installed on your system and have composer set up.

You will need to use the command line, so some command line knowledge is required.

Add laravel

Use composer to add the laravel installer through the command tool

composer global require “laravel/installer=~1.1”

See the documentation here

In your command line tool, navigate to the folder you would like to place the laravel project and insert the below

laravel new api

The last word, “api”, can be whatever you want to project to be named.

A folder will have been created called api and in that folder will be a fresh install of laravel.

Check your laravel installed successfully by running the following statement in your command line tool:

php artisan serve

That should open a website with the address: http://localhost:8000

If you do not see that, or can not access the laravel site on that url, you will need to check that all the prerequisites are installed properly before continuing.

Adding the api end points

To create your api end points you will need to edit the routes.php files. This file will be in app/Http/

Add these lines of code:

Route::get('/test/', array('uses' => 'APIController@doThisTest'));

Route::get('/anothertest/', array('uses' => 'APIController@doAnotherTest'));

In the code this part array(‘uses’ => ‘APIController@doThisTest’) indicates that it will use a controller called APIController and use a method called doThisTest.

You now need to create a controller called APIController.

In app/Http/Controllers/ create a file called APIController.php and add the following code:

<?php

namespace App\Http\Controllers;

class APIController extends Controller {

    public function doThisTest() {
      return "Hello world";
    }

    public function doAnotherTest() {
      return "Hello moo";
    }

}

Viewing the api

This code will have created two endpoints:

  • http://localhost:8000/test/
  • http://localhost:8000/anothertest/

 

Summary

That’s the start. You can extend the api further by adding user authentication and create an interface for inputting data through the api.