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...
Should I also versionning all files related to the api like FormRequest, Ressource, migration, Policies, Observers and so on...?
It depends.
FormRequest, resources -> Yes. I would version them myself.
Policies -> If there are big changes between them - yeah. You should be already versioning contrllers and other things around, so why not.
Migrations -> No, as that would mean a separate database. Just make sure nothing crashes for older users
Observers -> Maybe. This one is tricky to answer exactly.
But all in all - you have to keep in mind that you have to support older versions of the code. So whatever you do, you have to check if it makes sense. For example, removing a function from anywhere - can be pretty bad. So a version with all the things - is needed. But for an additional field - it might not be so important.