In this article you will read how to set up Application Programming Interfaces (APIs) via Laravel and Fractal. 

API Development is one of the things we are strongly committed to at Codana. We like to build strong APIs for different purposes.
When we use Laravel to build an application we always use Fractal.

There are a lot of examples in the documentation and on the internet how this is easy to implement in Laravel.
Here we have listed some recommended practices, which we use in some of our own projects.

What's Fractal for Laravel?

Fractal is a library written by the PHP League, a group that creates open source framework-independent libraries. To make this easy to use within Laravel applications a wrapper is provided.

You use fractal to return consistent responses from your API, to easily convert your data to JSON/YAML, because you send everything systematically through the same transformers you always make sure that data types are consistently the same. This layer between your output and your data models ensures that schema changes do not automatically get through to your API. So you monitor the backwards compatibility of your API much better.
 

Use the injected service to build responses.

There are facades to make this easier, but by doing so, your IDE can help you build your results.


public function __construct(Fractal $fractal)
{
	$this->fractal = $fractal;
}

public function respondWithData(User $user): JsonResponse
{
	return $this->fractal
      ->item($user)
      ->transformWith(new UserDetailsTransformer())
      ->respond();
}

 

Use includes where they are useful and reusable transformers.

It is very tempting to build up specific responses by giving extra data from a specific transformer.
In order to maintain as much consistent data as possible to the consumers of the API, it is recommended to reuse transformers where possible.

->parseIncludes('user.emailSettings')

 

Extra data is passed on to the constructor of the transformer.

If you need extra data in a transformer, you can give it to the constructor.

So don't do it this way.

// The bad way.
$this->fractal
  ->item(['data' => $data, 'currentUser' => $user])
  ->transformWith(new DataForUserTransformer());

It is clearer to do this, you can typehint on `transform` in the DataForUserTransformer (on the two arguments).
 

// The better way.
$this->fractal->collection($data)
      ->transformWith(new DataForUserTransformer($user));

 

Use a NullTransformer where necessary.

Sometimes you build an endpoint that is not strictly restful. For example, an endpoint where the average sales of the past week are calculated. In such cases, you can use a transformer that easily returns what you put in, without the need for other ways of building up responses.

final class NullTransformer extends TransformerAbstract
{
    public function transform(array $data): array
    {
        return $data;
    }
}

class Controller {

public function respondWithData(Request $request): JsonResponse
{
  $data = calculateForRequest($request);
  return $this->fractal
      ->item($data)
      ->transformWith(new NullTransformer())
      ->respond();
}
}

 

Eager loading is your best friend.

If you have configured fractal to always require an include, or otherwise display related data, make sure that the eager is loaded before you send it to fractal.

Adding eager loading before sending this data to fractal ensures that the data is already available in memory and does not need to be retrieved from the database on an item-by-item basis. This provides free performance gains for this endpoint.
 

Conclusion

Fractal always ensures that your code has a better structure and that your API is consistent and easy to consume. By using these tips you can have even more fun.

Author: Joris Vercammen
Developer
Joris Vercammen

More insights

Address register & GEOpunt API

Have you ever had to decide whether you should use Google maps, openstreetmaps, or another GIS provider for address suggestions? If you only need Belgian addresses, be sure to read on!

Author: Noah Gillard
PHP / Laravel Developer
Noah Gillard AI generated Face
Logo vlaamse overheid

Next.js: Just another framework?

About every 10 years, new technology emerges that brings about a change in the way we develop software. Is Next.js this new technology?

Author: Dries Cappon
UX, Design, React.js, Next.js
Dries Cappon
Next.js

Laravel 10 release

The release of Laravel 10: The king of types. Alles wat je moet weten over de nieuwe major release!

Author: Noah Gillard
PHP / Laravel Developer
Noah Gillard AI generated Face
laravel 10 banner

Saloon - Package / SDK API integrations

API integrations for a range of services. Little to no reusable code? With Saloon you turn it into a compact/clean SDK/Package that you can reuse in all your projects and maintain in one place.

Author: Noah Gillard
PHP / Laravel Developer
Noah Gillard AI generated Face
Saloon hero image

Codana wins Digital Champ of the year award 2022

Codana is the winner of the FeWeb Digital Champ award 2022! 

Author: Joris De Groot
Strategic Director and Managing Partner
Joris De Groot
FeWeb Digital Champ award Codana

Life as a React developer at Codana: 1 year in service

"You can start working with us as a React developer!". Bliss! Needless to say, I was super happy to hear this! But, I had never written a line of React before.

Author: Thomas Timmermans
Frontend Developer
Thomas Timmermans
Ik na 1 jaar in dienst