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

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 67 courses (1172 lessons, total 43 h 18 min)
  • 88 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses