TIP 09 / 09

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

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

Inside the method boot, add the following code:

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

    // Register the routes for API version 2.
     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

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

Inside the method map, add the following code:

php
// Remove this call to $this->mapApiRoutes().
    $this->mapApiV1Routes();
    $this->mapApiV2Routes();

And add these methods:

code
  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

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

Route File Versioning

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