How to build REST API in Laravel in High availability environments

How to build REST API in Laravel in High availability environments

To organize your API versions in separate folders and ensure that they can be deployed independently, follow these steps:

  1. Create a new folder named v1 inside the app/Http/Controllers/Api directory. This folder will contain the controllers for API version 1.
  2. Move the existing UserController into the v1 Folder and update its namespace accordingly:
namespace App\Http\Controllers\Api\v1;

use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index(Request $request)
    {
        // Logic for API version 1
    }
}
  1. When you need to create a new version of the API, create another folder named v2 inside the app/Http/Controllers/Api directory. Copy the necessary controllers from the v1 folder to the v2 Folder and update their namespaces and logic as needed. For example:
namespace App\Http\Controllers\Api\v2;

use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index(Request $request)
    {
        // Logic for API version 2
    }
}
  1. Now, define your routes in the routes/api.php File by creating separate route groups for each API version, specifying the folder as a namespace and the version number in the URI:
use Illuminate\Support\Facades\Route;

// API version 1 routes
Route::prefix('v1')->namespace('Api\v1')->group(function () {
    Route::get('users', 'UserController@index');
});

// API version 2 routes
Route::prefix('v2')->namespace('Api\v2')->group(function () {
    Route::get('users', 'UserController@index');
});

With this setup, your API endpoints will have version numbers in the URI, such as /v1/users and /v2/users. The corresponding controllers for each version are located in separate folders, allowing you to manage and deploy them independently.

Remember to update your RouteServiceProvider’s mapApiRoutes() method in app/Providers/RouteServiceProvider.php to load the api.php file:

protected function mapApiRoutes()
{
    Route::prefix('api')
        ->middleware('api')
        ->namespace($this->namespace)
        ->group(base_path('routes/api.php'));
}

By organizing your API versions in separate folders and using Laravel’s routing system, you can maintain and deploy different versions of your API independently without merging them into new code.

By Louis M.

About the authorMy LinkedIn profile

Related Links:

Discover more from Devops7

Subscribe now to keep reading and get access to the full archive.

Continue reading