API Version Control in Laravel
Published on by Paul Redmond
API Version Control is a package by Reindert Vetter designed to manage versions of API endpoints elegantly.
This package provides a configuration file where you define the releases and the version capabilities. Later, you can use things like version statements to determine the capabilities of specific versions of your API:
'releases' => [ 'GET/orders' => [ '<=1.0' => [ PrepareParameterException::class, ], ], '(POST|PUT)/orders' => [ '<=2.0' => [ ThrowCustomException::class, ValidateZipCode::class, ], '<=1.0' => [ PrepareParameterException::class, ], ],],
This package has two ways to manage the versions of your API endpoints, using the following techniques:
- Version statement
- Version middleware
Version statements include classes that mix in the VersionStatement
trait. Thus you can determine if the API code is to be executed without checking a particular version of the API everywhere in your code:
// Instead of version checks everywhere...if (RequestVersion::isAtLeast('2.0')) { // ...} // A VersionStatement class instead based on versionif (ValidateZipCode::permitted()) { // ...}
Here's an example of the ValidateZipCode
class from the README:
namespace App\VersionControl\Orders; use ReindertVetter\ApiVersionControl\Concerns\VersionStatement; class ValidateZipCode{ use VersionStatement;}
Version middleware takes it a step further, processing all requests and responses different from the latest version in a middleware:
use Closure;use Illuminate\Http\Request; class PrepareParameterException{ /** * @param $request * @param \Closure $next * @return mixed */ public function handle(Request $request, Closure $next) { // Set the default parameter because it is required in a newer version. $request->query->set('sort', 'DESC'); /** @var \Illuminate\Http\Response $response */ $response = $next($request); return $response; }}
You can learn more about this package, get full installation instructions, and view the source code on GitHub.