To use an API key when requesting a route, you typically need to include the key as a parameter in the request. The specific implementation will depend on the framework or library you are using for your API.
Here's a general example using Laravel's routing system:
- First, you need to define a route that requires an API key. You can do this in your
routes/web.phporroutes/api.phpfile:
Route::get('/api/some-route', 'ApiController@someMethod')->middleware('api_key');
- Next, create a middleware that will check for the presence of the API key. You can generate a middleware using the following command:
php artisan make:middleware ApiKeyMiddleware
This will create a new middleware class in the app/Http/Middleware directory.
- Open the newly created
ApiKeyMiddlewareclass and modify thehandlemethod to check for the API key:
<?php
namespace App\Http\Middleware;
use Closure;
class ApiKeyMiddleware
{
public function handle($request, Closure $next)
{
$apiKey = $request->query('api_key');
if ($apiKey !== 'YOUR_API_KEY') {
return response('Unauthorized.', 401);
}
return $next($request);
}
}
In this example, we're checking if the api_key query parameter matches a predefined value. You can modify this logic to suit your needs, such as checking against a database or an environment variable.
- Register the middleware in the
app/Http/Kernel.phpfile by adding it to the$routeMiddlewarearray:
protected $routeMiddleware = [
// ...
'api_key' => \App\Http\Middleware\ApiKeyMiddleware::class,
];
- Finally, make sure to replace
'YOUR_API_KEY'in theApiKeyMiddlewareclass with your actual API key.
With this setup, any request to /api/some-route?api_key=YOUR_API_KEY will be allowed, while requests without a valid API key will receive a 401 Unauthorized response.
Remember to adapt this solution to your specific framework or library if you're not using Laravel.