Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

SitePoint PHP Blog:
PHP Fractal – Make Your API’s JSON Pretty, Always!
Feb 27, 2017 @ 16:28:55

The SitePoint PHP blog has a tutorial posted by author Younes Rafie covering the use of the Fractal library from The PHP League to create "pretty" JSON API output.

If you’ve built an API before, I’ll bet you’re used to dumping data directly as a response. It may not be harmful if done right, but there are practical alternatives that can help solve this small problem.

One of the available solutions is Fractal. It allows us to create a new transformation layer for our models before returning them as a response. It’s very flexible and easy to integrate into any application or framework.

They use a Laravel application as the base, creating a simple database of user information and relating users to roles. The tutorial then starts in on using Fractal, building out "transformers" for the data. These transformers take in the data/object and, inside of a "transform" method, modify the output and return a "prettier" version. They show it in use in a controller, outputting a collection of user data, only returning the name and email values. The tutorial also covers a few other Fractal-related topics including pagination, including sub-resources and eager loading.

tagged: fractal api json output transform tutorial

Link: https://www.sitepoint.com/php-fractal-make-your-apis-json-pretty-always/


Trending Topics: