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:
1'releases' => [ 2 'GET/orders' => [ 3 '<=1.0' => [ 4 PrepareParameterException::class, 5 ], 6 ], 7 '(POST|PUT)/orders' => [ 8 '<=2.0' => [ 9 ThrowCustomException::class,10 ValidateZipCode::class,11 ],12 '<=1.0' => [13 PrepareParameterException::class,14 ],15 ],16],
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:
1// Instead of version checks everywhere...2if (RequestVersion::isAtLeast('2.0')) {3 // ...4}5 6// A VersionStatement class instead based on version7if (ValidateZipCode::permitted()) {8 // ...9}
Here's an example of the ValidateZipCode
class from the README:
1namespace App\VersionControl\Orders;2 3use ReindertVetter\ApiVersionControl\Concerns\VersionStatement;4 5class ValidateZipCode6{7 use VersionStatement;8}
Version middleware takes it a step further, processing all requests and responses different from the latest version in a middleware:
1use Closure; 2use Illuminate\Http\Request; 3 4class PrepareParameterException 5{ 6 /** 7 * @param $request 8 * @param \Closure $next 9 * @return mixed10 */11 public function handle(Request $request, Closure $next)12 {13 // Set the default parameter because it is required in a newer version.14 $request->query->set('sort', 'DESC');15 16 /** @var \Illuminate\Http\Response $response */17 $response = $next($request);18 19 return $response;20 }21}
You can learn more about this package, get full installation instructions, and view the source code on GitHub.
0 comments:
Post a Comment
Thanks