Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

petruskellerdev's avatar

API Key in routes

Where can I see a podcast or get a PDF on how to use an API key when requesting a route in PHP?

0 likes
1 reply
LaryAI's avatar
Level 58

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:

  1. First, you need to define a route that requires an API key. You can do this in your routes/web.php or routes/api.php file:
Route::get('/api/some-route', 'ApiController@someMethod')->middleware('api_key');
  1. 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.

  1. Open the newly created ApiKeyMiddleware class and modify the handle method 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.

  1. Register the middleware in the app/Http/Kernel.php file by adding it to the $routeMiddleware array:
protected $routeMiddleware = [
    // ...
    'api_key' => \App\Http\Middleware\ApiKeyMiddleware::class,
];
  1. Finally, make sure to replace 'YOUR_API_KEY' in the ApiKeyMiddleware class 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.

1 like

Please or to participate in this conversation.