Advertisement
  1. Code
  2. PHP
  3. Laravel

Laravel 4: A Start at a RESTful API (Updated)

Scroll to top

RESTful API's are hard! There are a lot of aspects to designing and writing a successful one. For instance, some of the topics that you may find yourself handling include authentication, hypermedia/HATEOS, versioning, rate limits, and content negotiation. Rather than tackling all of these concepts, however, let's instead focus on the basics of REST. We'll make some JSON endpoints behind a basic authentication system, and learn a few Laravel 4 tricks in the process.

If you need help with your Laravel development, try some of the useful Laravel scripts and plugins available on Envato Market.


The App

Let's build an API for a simple Read-It-Later app. Users will be able to create, read, update and delete URLs that they wish to read later.

Ready to dive in and get started?

Install Laravel 4

Create a new install of Laravel 4. If you're handy with CLI, try this quickstart guide. Otherwise, we have a video tutorial here on Nettuts+ that covers the process.

We're going to first create an encryption key for secure password hashing. You can do this easily by running this command from your project root:

1
$ php artisan key:generate

Alternatively, you can simple edit your app/config/app.php encryption key:

1
/*

2
|--------------------------------------------------------------------------

3
| Encryption Key

4
|--------------------------------------------------------------------------

5
|

6
| This key is used by the Illuminate encrypter service and should be set

7
| to a random, long string, otherwise these encrypted values will not

8
| be safe. Make sure to change it before deploying any application!

9
|

10
*/
11
12
'key' => md5('this is one way to get an encryption key set'),

Database

Once you have a working install of Laravel 4, we can get started with the fun. We'll begin by creating the app's database.

This will only require two database tables:

  1. Users, including a username and password
  2. URLs, including a url and description

We'll use Laravel's migrations to create and populate the database.

Configure Your Database

Edit app/config/database.php and fill it with your database settings. Note: this means creating a database for this application to use. This article assumes a MySQL database.

1
'connections' => array(
2
3
    'mysql' => array(
4
        'driver'    => 'mysql',
5
        'host'      => 'localhost',
6
        'database'  => 'read_it_later',
7
        'username'  => 'your_username',
8
        'password'  => 'your_password',
9
        'charset'   => 'utf8',
10
        'collation' => 'utf8_unicode_ci',
11
        'prefix'    => '',
12
    ),
13
),

Create Migration Files

1
$ php artisan migrate:make create_users_table --table=users --create
2
$ php artisan migrate:make create_urls_table --table=urls --create

These commands set up the basic migration scripts that we'll be using to create the database tables. Our job now is to fill them with the correct table columns.

Edit app/database/migrations/SOME_DATE_create_users_table.php and add to the up() method:

1
public function up()
2
{
3
    Schema::create('users', function(Blueprint $table)
4
    {
5
        $table->increments('id');
6
        $table->string('username')->unique();
7
        $table->string('password');
8
        $table->timestamps();
9
    });
10
}

Above, we're setting a username (which should be unique), a password, as well as the timestamps. Save that, and now edit app/database/migrations/SOME_DATE_create_urls_table.php, and add to the up() method:

1
public function up()
2
{
3
    Schema::create('urls', function(Blueprint $table)
4
    {
5
        $table->increments('id');
6
        $table->integer('user_id');
7
        $table->string('url');
8
        $table->string('description');
9
        $table->timestamps();
10
    });
11
}

The only important note in this snippet is that we're creating a link between the url and users table, via the user_id field.

Add Sample Users

We can use Laravel's seeds to create a few sample users.

Create a file within the app/database/seeds folder that has the same name as the table that it corresponds to; in our case, UserTableSeeder.php. Add:

1
<?php
2
3
class UserTableSeeder extends Seeder {
4
5
    public function run()
6
    {
7
        DB::table('users')->delete();
8
9
        User::create(array(
10
            'username' => 'firstuser',
11
            'password' => Hash::make('first_password')
12
        ));
13
14
        User::create(array(
15
            'username' => 'seconduser',
16
            'password' => Hash::make('second_password')
17
        ));
18
    }
19
20
}

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

1
public function run()
2
{
3
    Eloquent::unguard();
4
5
    // Add or Uncomment this line

6
    $this->call('UserTableSeeder');
7
}

Run the Migrations

Here's how to create those two tables, and insert our sample users.

1
// Create the two tables

2
$ php artisan migrate
3
4
// Create the sample users

5
$ php artisan db:seed

Models

Laravel 4 continues to use the excellent Eloquent ORM. This will make the process of handling database calls a snap. We'll require one model per table.

Luckily, Laravel comes with a User model setup, so let's create a model for our urls table.

Create and edit file app/models/Url.php.

1
<?php
2
3
class Url extends Eloquent {
4
5
    protected $table = 'urls';
6
7
}

Authentication

Laravel's filters can handle authentication for us. In particular, Laravel now comes with a Basic Authentication filter, which we can use as a quick authentication model to be used with our API requests.

If you open app/filters.php, you'll see what it looks like:

1
Route::filter('auth.basic', function()
2
{
3
    return Auth::basic();
4
});

We just need to make one adjustment. By default, this filter looks for an "email" field to identify the user. Since we're using usernames instead of emails, we just need to adjust that preference. Change the Auth::basic() call by giving it our username field as a parameter:

1
Route::filter('auth.basic', function()
2
{
3
    return Auth::basic("username");
4
});

Routes

Let's test this out. Create a route, called testauth, and make sure that our auth.basic filter runs before it.

Edit app/routes.php:

1
Route::get('/authtest', array('before' => 'auth.basic', function()
2
{
3
    return View::make('hello');
4
}));

We can test this with a curl request. From your terminal, try pointing to your build of Laravel. In mine, it looks like this (Your URL will likely be different!):

1
$ curl -i localhost/l4api/public/index.php/authtest
2
HTTP/1.1 401 Unauthorized
3
Date: Tue, 21 May 2013 18:47:59 GMT
4
WWW-Authenticate: Basic
5
Vary: Accept-Encoding
6
Content-Type: text/html; charset=UTF-8
7
8
Invalid credentials

As you can see, an unauthorized request is detected and a "Invalid Credentials" message is returned with a 401 status code. Next, try including basic authentication.

1
$ curl --user firstuser:first_password localhost/l4api/public/index.php/authtest
2
HTTP/1.1 200 OK
3
Date: Tue, 21 May 2013 18:50:51 GMT
4
Vary: Accept-Encoding
5
Content-Type: text/html; charset=UTF-8
6
7
<h1>Hello World!</h1>

It worked!

At this point, the baseline work of our API is done. We have:

  • Installed Laravel 4
  • Created our database
  • Created our models
  • Created an authentication model

Creating Functional Requests

You may be familiar with Laravel's RESTful controllers. They still exist in Laravel 4; however, we can also use Laravel's Resourceful Controllers, which set up some paradigms that we can use to make a consistent API interface. We'll be using a Resourceful controller.

Here's a breakdown of what each method in the resourceful controller will handle. Please note that you can remove the /resource/create and /resource/{id}/edit routes, since we won't be needing to show 'create' or 'edit' forms in an API.

Create a Resourceful Controller

1
$ php artisan controller:make UrlController

Next, setup a route to use the controller, and require each route to be authenticated.

Edit app/routes.php and add:

1
// Route group for API versioning

2
Route::group(array('prefix' => 'api/v1', 'before' => 'auth.basic'), function()
3
{
4
    Route::resource('url', 'UrlController');
5
});

A few things are happening there.

  1. This is going to respond to requests made to http://example.com/api/v1/url.
  2. This allows us to add extra routes, if we need to expand our API. For instance, if you add a user end-point, such as /api/v1/user.
  3. There is also a naming mechanism in place for versioning our API. This gives us the opportunity to roll out new API versions without breaking older versions - We can simply create a v2 route group, and point it to a new controller!

Note: You may want to consider more advanced API versioning techniques, such as using an Accept header or subdomain which can help you point different API versions separate code bases.

Add the Functionality

Edit the new app/controllers/UrlController.php file:

1
// Edit this:

2
public function index()
3
{
4
    return 'Hello, API';
5
}

Let's test it:

1
$ curl -i localhost/l4api/public/index.php/api/v1/url
2
HTTP/1.1 401 Unauthorized
3
Date: Tue, 21 May 2013 19:02:59 GMT
4
WWW-Authenticate: Basic
5
Vary: Accept-Encoding
6
Content-Type: text/html; charset=UTF-8
7
8
Invalid credentials.
9
10
$ curl --user firstuser:first_password localhost/l4api/public/index.php/api/v1/url
11
HTTP/1.1 200 OK
12
Date: Tue, 21 May 2013 19:04:19 GMT
13
Vary: Accept-Encoding
14
Content-Type: text/html; charset=UTF-8
15
16
Hello, API

We now have a resourceful controller with authentication working, and are ready to add functionality.

Create a URL

Edit app/controllers/UrlController.php:

1
/**

2
 * Store a newly created resource in storage.

3
 *

4
 * @return Response

5
 */
6
public function store()
7
{
8
    $url = new Url;
9
    $url->url = Request::get('url');
10
    $url->description = Request::get('description');
11
    $url->user_id = Auth::user()->id;
12
13
    // Validation and Filtering is sorely needed!!

14
    // Seriously, I'm a bad person for leaving that out.

15
16
    $url->save();
17
18
    return Response::json(array(
19
        'error' => false,
20
        'urls' => $urls->toArray()),
21
        200
22
    );
23
}

It's time to test this with another curl request. This one will send a POST request, which will correspond to the store() method created above.

1
$ curl -i --user firstuser:first_password -d 'url=http://google.com&description=A Search Engine' localhost/l4api/public/index.php/api/v1/url
2
HTTP/1.1 201 Created
3
Date: Tue, 21 May 2013 19:10:52 GMT
4
Content-Type: application/json
5
6
{"error":false,"message":"URL created"}

Cool! Let's create a few more, for both of our users.

1
$ curl --user firstuser:first_password -d 'url=http://fideloper.com&description=A Great Blog' localhost/l4api/public/index.php/api/v1/url
2
3
$ curl --user seconduser:second_password -d 'url=http://digitalsurgeons.com&description=A Marketing Agency' localhost/l4api/public/index.php/api/v1/url
4
5
$ curl --user seconduser:second_password -d 'url=http://www.poppstrong.com/&description=I feel for him' localhost/l4api/public/index.php/api/v1/url

Next, let's create methods for retrieving URLs.

1
/**

2
 * Display a listing of the resource.

3
 *

4
 * @return Response

5
 */
6
public function index()
7
{
8
    //Formerly: return 'Hello, API';

9
10
    $urls = Url::where('user_id', Auth::user()->id)->get();
11
12
    return Response::json(array(
13
        'error' => false,
14
        'urls' => $urls->toArray()),
15
        200
16
    );
17
}
18
19
/**

20
 * Display the specified resource.

21
 *

22
 * @param  int  $id

23
 * @return Response

24
 */
25
public function show($id)
26
{
27
    // Make sure current user owns the requested resource

28
    $url = Url::where('user_id', Auth::user()->id)
29
            ->where('id', $id)
30
            ->take(1)
31
            ->get();
32
33
    return Response::json(array(
34
        'error' => false,
35
        'urls' => $url->toArray()),
36
        200
37
    );
38
}

Let's test them out:

1
$ curl --user firstuser:first_password localhost/l4api/public/index.php/api/v1/url
2
{
3
    "error": false,
4
    "urls": [
5
       {
6
            "created_at": "2013-02-01 02:39:10",
7
            "description": "A Search Engine",
8
            "id": "2",
9
            "updated_at": "2013-02-01 02:39:10",
10
            "url": "http://google.com",
11
            "user_id": "1"
12
        },
13
        {
14
            "created_at": "2013-02-01 02:44:34",
15
            "description": "A Great Blog",
16
            "id": "3",
17
            "updated_at": "2013-02-01 02:44:34",
18
            "url": "http://fideloper.com",
19
            "user_id": "1"
20
        }
21
    ]
22
}
23
24
$ curl --user firstuser:first_password localhost/l4api/public/index.php/api/v1/url/1
25
{
26
    "error": false,
27
    "urls": [
28
        {
29
            "created_at": "2013-02-01 02:39:10",
30
            "description": "A Search Engine",
31
            "id": "2",
32
            "updated_at": "2013-02-01 02:39:10",
33
            "url": "http://google.com",
34
            "user_id": "1"
35
        }
36
    ]
37
}

Almost done. Let's now allow users to delete a url.

1
/**

2
 * Remove the specified resource from storage.

3
 *

4
 * @param  int  $id

5
 * @return Response

6
 */
7
public function destroy($id)
8
{
9
    $url = Url::where('user_id', Auth::user()->id)->find($id);
10
11
    $url->delete();
12
13
    return Response::json(array(
14
        'error' => false,
15
        'message' => 'url deleted'),
16
        200
17
        );
18
}

Now, we can delete a URL by using a DELETE request:

1
$ curl -i -X DELETE --user firstuser:first_password localhost/l4api/public/index.php/api/v1/url/1
2
HTTP/1.1 200 OK
3
Date: Tue, 21 May 2013 19:24:19 GMT
4
Content-Type: application/json
5
6
{"error":false,"message":"url deleted"}

Lastly, let's allow users to update a url.

1
/**

2
 * Update the specified resource in storage.

3
 *

4
 * @param  int  $id

5
 * @return Response

6
 */
7
public function update($id)
8
{
9
    $url = Url::where('user_id', Auth::user()->id)->find($id);
10
11
    if ( Request::get('url') )
12
    {
13
        $url->url = Request::get('url');
14
    }
15
16
    if ( Request::get('description') )
17
    {
18
        $url->description = Request::get('description');
19
    }
20
21
    $url->save();
22
23
    return Response::json(array(
24
        'error' => false,
25
        'message' => 'url updated'),
26
        200
27
    );
28
}

To test URL updates, run:

1
$ curl -i -X PUT --user seconduser:second_password -d 'url=http://yahoo.com' localhost/l4api/public/index.php/api/v1/url/4
2
HTTP/1.1 200 OK
3
Date: Tue, 21 May 2013 19:34:21 GMT
4
Content-Type: application/json
5
6
{"error":false,"message":"url updated"}
7
8
// View our changes
9
$ curl --user seconduser:second_password localhost/l4api/public/index.php/api/v1/url/4
10
{
11
    "error": false,
12
    "urls": [
13
        {
14
            "created_at": "2013-02-01 02:44:34",
15
            "description": "I feel for him",
16
            "id": "3",
17
            "updated_at": "2013-02-02 18:44:18",
18
            "url": "http://yahoo.com",
19
            "user_id": "1"
20
        }
21
    ]
22
}

And That's It

We now have the beginnings of a fully-functioning API. I hope that you've learned a lot about how to get an API underway with Laravel 4.

To recap, we achieved the following in this lesson:

  1. Install Laravel
  2. Create the database, using migrations and seeding
  3. Use Eloquent ORM models
  4. Authenticate with Basic Auth
  5. Set up Routes, including versioning the API
  6. Create the API functionality using Resourceful Controllers

The Next Steps

If you'd like to push your API up a notch, you might consider any of the following as a next step.

  1. Validation (Hint: Laravel has a Validation library).
  2. API-request error handling – It's still possible to receive HTML response on API requests (Hint: Laravel Error Handling, plus Content Negotiation.)
  3. Content Negotiation - listening for the Accept header. (Hint: Laravel's Request Class will give you the request headers).
  4. Check out the API Craft Google Group.
  5. Learn about the different types caching and how Validation Caching can improve your API.
  6. Unit test your code.
  7. Check out Apigee's great API resources.
  8. Try some of the useful Laravel scripts and plugins available on Envato Market.
Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.