How we can use open standards and specifications to design and build RESTful APIs that are easier to developer, maintain and use. Focusing on JSON-API (http://jsonapi.org/) and the Fractal php package (http://fractal.thephpleague.com/)
8. OPENSTANDARDS
What makes an open standard ?
Cooperation
Adherence to Principles
Due process, Broad concensus, Transparency,
Balance, Openness
Collective Empowerment
Availability
Voluntary Adoption
4 . 1
14. OVERVIEW
well-de ned conventions for listing, creating,
updating and deleting resources
recommendations for details not covered in the
main spec
server and client libraries in most popular
languages
8
38. Class transformer
use LeagueFractalTransformerAbstract;
use LeagueFractalResourceCollection;
class MeetupTransformer extends TransformerAbstract
{
public function transform(Meetup $meetup)
{
return [
'id' => $meetup->id,
'name' => $meetup->name,
'description' => $meetup->description,
'next-meetup' => $meetup->events->getNext()->date
];
}
}
$data = new Collection($meetups, new MeetupTransformer);
21 . 2
39. De ning includes
use LeagueFractalTransformerAbstract;
use LeagueFractalResourceCollection;
class MeetupTransformer extends TransformerAbstract
{
protected $availableIncludes = ['venues'];
public function transform($meetup) { ... }
public function includeVenue($meetup)
{
$venue = $meetup->venue;
$transformer = new VenueTransformer;
return $this->item($venue, $transformer, 'venues');
}
}
$data = new Collection($meetups, new MeetupTransformer);
21 . 3
40. Creating a resource
use LeagueFractalSerializerJsonApiSerializer;
$manager = new LeagueFractalManager();
$baseUrl = 'http://meetup.dev';
$manager->setSerializer(new JsonApiSerializer($baseUrl));
// ORM call
$meetup = Meetup::find(1);
// Make a resource out of the data and
$resource = new Item($meetup, new MeetupTransformer, 'meetups');
// Run all transformers
$manager->createData($resource)->toArray();
21 . 4
48. Use a base class
class JsonApiError extends Exception {
protected $status;
protected $title;
protected $detail;
protected $source;
protected $meta;
public function toArray() {...}
}
24 . 1
49. Extend it for speci c errors
class NotFoundError extends JsonApiError {
protected $status = 404;
protected $title = 'Resource not found';
}
24 . 2