Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

drewdan's avatar
Level 15

API Versioning in Laravel

Hey Guys,

I appreciate this question is a little broad, but hoping to get some insight from those who may be more experiences than I.

I am currently trying to build an API for an application I work on. We will be using the JSON:API spec to build this. I am using the Spatie Fractal package to transform the models into the correct format for this API. However, I have lots of Transformers for all of my models. Whilst this is fine in the initial iteration of this API. I would like to know how I might handle changes as I am concerned I will end up with hundreds of transformers which are all very similar, or potentially just an extension of the previous.

As I understand, an API should not introduce breaking changes, if there was to be one, that would need to be a different version of the API I have seen with Stripes API, you choose the version of the API you wish to interact with. But, how is this done? if I changed a model and added a new attribute, would I then have to create a whole new set of transformers for a new version?

If anyone knows of any blogs or guidance around this and best practices, I would be ever so grateful.

Thanks Guys!

0 likes
5 replies
gitwithravish's avatar

@drewdan

I do not have a lot of experience in building APIs, but what I can understand here is you want to work around code duplication. Let's say you have 100 controllers and you want to make a new api then one approach is to put all of those controllers under new folder \Controller\V2 and make changes in those few controllers because of which you needed to create a new version of API.

Checkout 3rd approach in this blog. it is about making different views within the same controller for different api versions. Maybe you can do something similar with your transformers as well?

Maybe make multiple functions for different versions when needed. If there is no difference in a transformer for new api version, you can use the old view of that transformer even in the latest api version. You can pass the api version info from route parameter to your controller and transformer so that they know how to behave differently for different api versions.

https://thenewstack.io/tricks-api-versioning/

Other resource for API building in laravel.

https://b-ok.asia/book/5268710/195723

1 like
Sinnbeck's avatar

@ravish I am not quite sure if I like the idea. Depends on how much the api can change between versions. As I understand the post, it will break the single responsibility principle.

But honestly I have never built a versioned api in my career, so I might be the wrong person to ask :)

2 likes
drewdan's avatar
Level 15

Thanks both for the responses, I will take a look through the materials and post my conclusion here in a while. :)

Please or to participate in this conversation.