Backend Development

How to use Laravel Scramble in Production

Recently, I've been building a REST API for NurseryPeople. It's a site I built several years ago on Laravel, and every once in a while when I feel like it, I work on it as a side project to keep me busy.

The latest thing I've been doing is building a simple REST API. The idea is that I will be able to use this API for a mobile app I have planned in the future.

One of the first thoughts I had was how to generate API documentation. Of course, I could use a service to write the API's documentation manually as I build it, but I want the documentation to be generated automatically since I'm a one-man team on NurseryPeople. I don't want to spend a ton of time writing documentation when I could be writing code.

Quickly I started the search for an API auto-generating documentation package for Laravel and found Laravel Scramble. The package is in early development, but after installing and using the package, I soon found that it would fit my needs perfectly. Laravel Scramble updates documentation on the fly and is near-perfect in accuracy if you're building an API following Laravel conventions.

After I built out the initial API for NurseryPeople, I wanted to be able to view the Scramble-generated docs from the production application, but Scramble prevents accessing this page by default in production.

In their docs, they say to define the viewApiDocs Gate to access the docs in production but don't say how to define the Gate.

So how do you define the viewApiDocs Gate?

To define a viewApiDocs Gate, the process is pretty simple. First, you need to go to your AuthServiceProvider and find your boot() method. In this method, you will define the Gate as follows:

   /**
     * Register any authentication/authorization services.
     *
     * @return void
     */
    public function boot()
    {
        //

        Gate::define('viewApiDocs', function (User $user) {
            return $user->isAdmin();
        });
    }

Inside your Gate definition, you can do whatever you would like. If you want everyone to be able to access your API documentation, you can return true. For my case, I wanted to limit the docs to only admins of the site, mainly me. hehe

Hope this helps!
Thanks,
Chris

Chris Wray website logo

Trying to do my part in making the world a better place.

This site is hosted for free, so I am thanking the services I am using by adding a link to their websites here in the footer.

© 2020 Chris Wray. All rights reserved.