Skip to main content
Quick Tip

API Versioning

When to version?

If you are working on a project that may have multi-release in the future or your endpoints have a breaking change like a change in the format of the response data, and you want to ensure that the API version remains functional when changes are made to the code.

Change The Default Route Files

The first step is to change the route map in the App\Providers\RouteServiceProvider file, so let's get started:

Laravel 8 and above:

Add a 'ApiNamespace' property

/**
* @var string
*
*/
protected string $ApiNamespace = 'App\Http\Controllers\Api';

Inside the method boot, add the following code:

$this->routes(function () {
Route::prefix('api/v1')
->middleware('api')
->namespace($this->ApiNamespace.'\\V1')
->group(base_path('routes/API/v1.php'));
}
 
//for v2
Route::prefix('api/v2')
->middleware('api')
->namespace($this->ApiNamespace.'\\V2')
->group(base_path('routes/API/v2.php'));
});

Laravel 7 and below:

Add a 'ApiNamespace' property

/**
* @var string
*
*/
protected string $ApiNamespace = 'App\Http\Controllers\Api';

Inside the method map, add the following code:

// remove this $this->mapApiRoutes();
$this->mapApiV1Routes();
$this->mapApiV2Routes();

And add these methods:

protected function mapApiV1Routes()
{
Route::prefix('api/v1')
->middleware('api')
->namespace($this->ApiNamespace.'\\V1')
->group(base_path('routes/Api/v1.php'));
}
protected function mapApiV2Routes()
{
Route::prefix('api/v2')
->middleware('api')
->namespace($this->ApiNamespace.'\\V2')
->group(base_path('routes/Api/v2.php'));
}

Controller Folder Versioning

Controllers
└── Api
├── V1
│ └──AuthController.php
└── V2
└──AuthController.php

Route File Versioning

routes
└── Api
│ └── v1.php
│ └── v2.php
└── web.php

Tip given by Feras Elsharif

Enjoyed This Tip?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.