If you are working on a project long enough, you will need versioning at some point. If you have used any APIs like Stripe or Facebook, they have version numbers. Knowing which version you use is essential because it may be a part of the URL endpoint or some parameter. So, how do you implement versioning in your project?
Until now, we had endpoint /api/categories
without any version. Let's create version two, a copy of version one.
To do that, first, let's move the existing API to version one. Create an app\Http\Controllers\Api\V1
directory and move CategoryController
and ProductController
inside it. Change the namespace in both Controllers.
namespace App\Http\Controllers\Api; namespace App\Http\Controllers\Api\V1; // ...
Next, change the Controller path in the routes/api.php
.
routes/api.php:
Route::get('/user', function (Request $request) { return $request->user();})->middleware('auth:sanctum'); Route::apiResource('categories', \App\Http\Controllers\Api\CategoryController::class) Route::apiResource('categories', \App\Http\Controllers\Api\V1\CategoryController::class) ->middleware('auth:sanctum'); Route::get('products', [\App\Http\Controllers\Api\ProductController::class, 'index']); Route::get('products', [\App\Http\Controllers\Api\V1\ProductController::class, 'index']);
Last, we must change the prefix from /api
to /api/v1
. Routes are configured in the...