Skip to content

Instantly share code, notes, and snippets.

@sixlive
Last active September 13, 2017 17:07
Show Gist options
  • Save sixlive/0383545078219482434fbc0ed16f3323 to your computer and use it in GitHub Desktop.
Save sixlive/0383545078219482434fbc0ed16f3323 to your computer and use it in GitHub Desktop.
How I typically build APIs

When I build an API I typically use a pretty simple format. It is actually pretty much Fractal out of the box by way of Spatie's Larave Fractal package. Personally, I've found other formats more verbose than I need. I've built some pretty robust APIs using this format without issue. I also rely heavily on sending status codes for request status and consumer notification.

When building an app that consumes the API I typically build SDKs. I've been using Apiary to document my APIs and you get a pretty nice tool set from them, making SDK generation and testing so much easier.

Response Examples

The responses were built using the following code:

routes/api.php

<?php

use App\User;
use Illuminate\Http\Request;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;

function transformer($user)
{
    return [
        'id' => $user->id,
        'name' => $user->name,
        'email' => $user->email,
    ];
}

Route::get('/users/{user}', function (User $user) {
    return fractal()
        ->item($user)
        ->transformWith('transformer')
        ->respond();
});

Route::get('/users', function () {
    $usersPaginator = User::paginate(3);

    return fractal()
        ->collection($usersPaginator->getCollection())
        ->transformWith('transformer')
        ->paginateWith(new IlluminatePaginatorAdapter($usersPaginator))
        ->respond();
});

Standard Response

{
  "data": {
    "id": 1,
    "name": "Dayna Lesch DDS",
    "email": "[email protected]"
  }
}

Response with meta

{
  "data": [
    {
      "id": 1,
      "name": "Dayna Lesch DDS",
      "email": "[email protected]"
    },
    {
      "id": 2,
      "name": "Damion Robel",
      "email": "[email protected]"
    },
    {
      "id": 3,
      "name": "Benedict Streich",
      "email": "[email protected]"
    }
  ],
  "meta": {
    "pagination": {
      "total": 10,
      "count": 3,
      "per_page": 3,
      "current_page": 1,
      "total_pages": 4,
      "links": {
        "next": "http:\/\/localhost:8000\/api\/users?page=2"
      }
    }
  }
}
published: true
@phppirate
Copy link

Do you always use data as your root property?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment