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

drtechie's avatar

How to expose API only for developers?

I started a new project with Spark. I would like to expose the API only for developers. Setting $useApi to true exposes it for all users. Can it be done? Where should I start?

0 likes
3 replies
willvincent's avatar

You can't really only expose it to some people, unless maybe you know the IP addresses they'll be using and white list those but block all other requests to the api routes... seems unnecessary though to me.

Better to just require authentication to make use of the api. An api key, etc.

drtechie's avatar

When I meant developers, I meant developers mentioned in the SparkServiceProvider. The kiosk section is only shown for developers. Same way I would like to show API section only for developers. Not just that, the API middleware auth:api must accept requests only if the token matches a developer.

The former (showing API section only to devs) can be accomplished by conditional tags in the blade templates.

/**
     * All of the application developer e-mail addresses.
     *
     * @var array
     */
    protected $developers = [
        '[email protected]'
    ];

    /**
     * Indicates if the application will expose an API.
     *
     * @var bool
     */
    protected $usesApi = true;
drtechie's avatar
drtechie
OP
Best Answer
Level 1

Well, I did make it work.

settings.blade.php Show API Link only to developers by adding another condition, so that only devs can generate tokens.

<!-- API Link -->
@if (Spark::usesApi() && Spark::developer(Auth::user()->email))
       <li role="presentation">
               <a href="#api" aria-controls="api" role="tab" data-toggle="tab">
                       <i class="fa fa-fw fa-btn fa-cubes"></i>API
               </a>
        </li>
@endif

And in routes/api.php add the 'dev' middleware, so that only developers can access API.

Route::group([
    'prefix' => 'api',
    'middleware' => ['auth:api', 'dev']
], function () {
    //
    Route::get('/test', function() {
        return 'Hello';
    });
});

Although the API links is not shown in frontend the routes for generating tokens are still accessible. Let's say a user still painstakingly POSTs the right data to /settings/api/token to generate a token, he won't be able to get any data from API because of the 'dev' middleware.

Please or to participate in this conversation.